如何在调用另一个方法之前等待调用didUpdateLocation方法?

时间:2016-12-05 07:26:19

标签: ios swift asynchronous cllocationmanager

我正在开发一个应用,我想在用户注册时存储用户的当前位置。

因此,只要用户单击注册按钮,就会调用locationManager.startUpdatingLocation(),然后执行注册操作。

但是,即使在didUpdateLocations委托方法返回坐标之前,也会触发注册方法,因此用户的位置在数据库中存储为nil。

尝试在didUpdateLocations中调用注册方法是一团糟,因为这个委托被多次调用。

    func signup() { 
        self.getLocation()
        let point = PFGeoPoint(latitude:locationLat, longitude:locationLon)
        ...
        newUser[PF_USER_LOCATION] = point
        newUser.signUpInBackground(block: { (succeed, error) -> Void in

            if let errorInSignup = error {
                ...    
            } else {
                ...
            }
        })
    }

    func getLocation() {
        if CLLocationManager.locationServicesEnabled() {            
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations  locations: [CLLocation]) {

        let locValue:CLLocationCoordinate2D = manager.location!.coordinate

        locationLat = locValue.latitude
        locationLon = locValue.latitude
    }

我只添加了部分代码。

等待收到坐标以调用注册功能的正确程序是什么?

requestWhenInUseAuthorisation()位于viewDidLoad()

1 个答案:

答案 0 :(得分:0)

喜欢

func signup() { 
        self.getLocation()

    }

在这里打电话

   func locationManager(_ manager: CLLocationManager, didUpdateLocations  locations: [CLLocation]) {
          manager.stoptUpdatingLocation() // initialy stop updation
        let locValue:CLLocationCoordinate2D = manager.location!.coordinate

        locationLat = locValue.latitude
        locationLon = locValue.latitude
         let point = PFGeoPoint(latitude:locationLat, longitude:locationLon)
        ...
        newUser[PF_USER_LOCATION] = point
        newUser.signUpInBackground(block: { (succeed, error) -> Void in

            if let errorInSignup = error {
                ...    
            } else {
                ...
                // call your main view
            }
        })
    }