首页 文章

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

提问于
浏览
1

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

因此,只要用户单击注册按钮,就会调用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

    do like

    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
                }
            })
        }
    

相关问题