【问题标题】:How to wait for didUpdateLocation method to be called before calling another method?如何在调用另一个方法之前等待调用 didUpdateLocations 方法?
【发布时间】:2016-12-05 07:26:18
【问题描述】:

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

因此,一旦用户单击注册按钮,就会调用 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()

【问题讨论】:

  • 更改调用方法肯定有效
  • 只有在收到当前位置时调用注册方法,才能使用闭包
  • 如果您愿意只针对 ios9 及更高版本,您可以使用requestLocation developer.apple.com/reference/corelocation/cllocationmanager/… 否则您需要在didUpdateLocations 中编写代码以检查适当的水平精度,然后停止位置更新并完成注册。当用户拒绝位置许可或无法在合理时间内确定位置时,您还需要提供适当的代码
  • 笔记@Paulw11 感谢您的指出

标签: ios swift asynchronous cllocationmanager


【解决方案1】:

喜欢

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

【讨论】:

  • 谢谢@Anbu.karthik 另外,我使用了 locationmanager.startUpdatingLocations()。这已经多次调用委托方法。 In 应该用 locationManager.requestLocation() 替换它,以便只调用一次。
  • @Sowndharya - 也关注一次 paul cmets
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-21
  • 2012-03-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多