等待异步功能完成

时间:2015-01-11 09:32:23

标签: objective-c swift asynchronous parse-platform

位置管理器需要一段时间来查询10000行的类(在Parse中)。 我试图阻止用户在查询完成之前选择一行(在tableViewController中)。 在允许用户选择之前强制用户等待查询完成的最佳方法是什么?

查询加载数据:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    CLGeocoder().reverseGeocodeLocation(manager.location, completionHandler: { (placemarks, error) -> Void in
        if (error != nil) {
            println("Error:" + error.localizedDescription)
        }
        if placemarks.count > 0 {
            let pm = placemarks[0] as CLPlacemark
            self.displayLocationInfo(pm)
            currentLoc = manager.location
            currentLocGeoPoint = PFGeoPoint(location:currentLoc)

            var query = PFQuery(className:"test10000")
            query.whereKey("RestaurantLoc", nearGeoPoint:currentLocGeoPoint, withinMiles:10) //filter by miles
            query.limit = 1000 //limit number of results
            query.findObjectsInBackgroundWithBlock {
                (objects: [AnyObject]!, error: NSError!) -> Void in
                if objects != nil {
                    unfilteredRestaurantArray = objects
                } else {
                    println("error: \(error)")
                }
            }

        } else {
            println("error: \(error)")
        }
    })
}

其他信息:

该程序使用带有segues的didSelectRowAtIndex:

override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    if indexPath.row == 0 {
        self.performSegueWithIdentifier("toQ2", sender: self)
    } else {
        self.performSegueWithIdentifier("toQ1", sender: self)
    }

viewDidLoad调用locationManager:

override func viewDidLoad() {
    self.locationManager.delegate = self //location manager start
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
}

1 个答案:

答案 0 :(得分:1)

定义一个变量,表明查询仍在运行。当您启动查询时,请禁用与表格的任何互动,或者在其上放置带有活动指示符的叠加层。要在查询完成时收到通知,您可以使用didSet hook,例如

var queryIsRunning : Bool { didSet { onQueryIsRunningChanged() } }

[...]

func onQueryIsRunningChanged()
{
    if queryIsRunning
    {
        // Code to disable user interactions
    }
    else
    {
        // Code to re-enable user interactions
    }
}

也许有必要从主线程设置变量,这可以通过

来完成
dispatch_async(dispatch_get_main_queue(), { self.queryIsRunning = queryIsRunningState } )