Run code after a background process - parse.com

2019-03-03 10:03发布

问题:

I have a findObjectsInBackgroundWithBlock method in my viewController. Now i want to execute code, but just until this background method is finished. How can i do that?

I'm using the swift programming lanuage.

回答1:

Here is some example code that could help you. It is not clear how you would restrict the code (PRE-BACKGROUND CODE) to run only while the background processing has completed. You may want to insert some code in the notification response function either to confirm that that PRE-BACKGROUND CODE is completed or to terminate it.

//  ParseTestViewController.swift

import UIKit
import Foundation
import Parse

class ParseTestViewController: UIViewController {
var userData = [String]()

func codeToExecuteBeforeStringsAreAppended() {
}
func codeToExecuteAfterStringsAreAppended() {
    // can use the array 'userData'
}

override func viewDidLoad() {
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "notificationResponse:",
        name: "recordsLoaded",
        object: nil
    )

    self.getUserdataForUsername("MyName")
    /* ==========================
    Insert code tto be executed immediately after making the call that must not use the data returned by Parse. The function returns right away and the background may not have completed.
    */
    codeToExecuteBeforeStringsAreAppended()
}
func getUserdataForUsername (queryUserName: String) {
    var query = PFQuery(className:"UserData")
    query.whereKey("username", equalTo: queryUserName)
    let notification = NSNotification(name: "userDataRetrieved", object: self)
    query.findObjectsInBackgroundWithBlock {
        (objects: [AnyObject]?, error: NSError?) -> Void in

        if error == nil {
            for object in objects! {
                if let username = object["username"] as? String {
                    self.userData.append (username)
                }
            }
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
        NSNotificationCenter.defaultCenter().postNotification(notification)

    }
}

func notificationResponse (notification: NSNotification) {


    // this is executed after the background processing is done
    // Insert the code that uses the data retrieved from Parse
        codeToExecuteAfterStringsAreAppended()
        NSNotificationCenter.defaultCenter().removeObserver(self)
}
}


回答2:

This is pretty well covered in the documentation and guide on parse.com. But maybe you have a more specific question/scenario?

Guide to queries on parse.com

var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
  (objects: [AnyObject]?, error: NSError?) -> Void in

  if error == nil {
    // The find succeeded.
    println("Successfully retrieved \(objects!.count) scores.")
    // Do something with the found objects
    if let objects = objects as? [PFObject] {
      for object in objects {
        println(object.objectId)
      }
    }
  } else {
    // Log details of the failure
    println("Error: \(error!) \(error!.userInfo!)")
  }
}

Edit: specific version for PFUser to array of usernames

var usernames: [String]?
func loadUsernames () {

    if let query = PFUser.query() {
        query.findObjectsInBackgroundWithBlock {
            (objects: [AnyObject]?, error: NSError?) -> Void in

            if error == nil { // No error - should be good to go

                self.userNames = (objects as! [PFUser]).map({$0.username!})

                // Call/run any code you like here - remember 'self' keyword
                // It will not run until userNames is populated
                self.callSomeMethod()

            } else { // Error - do something clever

            }
        }
    }
}

override func viewDidLoad() {
    super.viewDidLoad()
    loadUsernames()
}