【问题标题】:Return user's latitude and longitude asynchronously [duplicate]异步返回用户的经纬度[重复]
【发布时间】:2020-09-27 00:57:33
【问题描述】:
func getCurrectLocationInfo()-> String {

    var strFormattedAddress : String = ""
    locationManager.requestWhenInUseAuthorization()
    var currentLoc: CLLocation!
    if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() == .authorizedAlways) {
       currentLoc = locationManager.location
       print(currentLoc.coordinate.latitude)
       print(currentLoc.coordinate.longitude)
        let latString = String(currentLoc.coordinate.latitude)
        let longString = String(currentLoc.coordinate.longitude)

    }
    self.getaddress(pdblLatitude: latString, withLongitude: longString) { address in
        print(address)
        strFormattedAddress = address

        return strFormattedAddress
    }
}

如何异步返回用户当前的经纬度。请指导。在上面的代码中,它返回空字符串

【问题讨论】:

  • 对于latStringlongString,您没有收到Use of unresolved identifier 错误吗?
  • 不是你标记的类似问题。
  • 是的。您尝试从异步任务中返回某些内容。 API 不同,但问题完全相同。
  • 每一个异步任务或事物都不一样,你不能用同名定义所有东西
  • 转义完成处理程序是转义完成处理程序,与使用的参数类型无关。

标签: ios xcode cllocationmanager


【解决方案1】:

由于函数是异步的,你需要用完成块修改你的函数,像这样:

func getCurrectLocationInfo(completion: @escaping (String) -> Void) {

    var strFormattedAddress : String = ""
    locationManager.requestWhenInUseAuthorization()
    var currentLoc: CLLocation!
    if(CLLocationManager.authorizationStatus() == .authorizedWhenInUse ||
    CLLocationManager.authorizationStatus() == .authorizedAlways) {
       currentLoc = locationManager.location
       print(currentLoc.coordinate.latitude)
       print(currentLoc.coordinate.longitude)
        let latString = String(currentLoc.coordinate.latitude)
        let longString = String(currentLoc.coordinate.longitude)

    }
    self.getaddress(pdblLatitude: latString, withLongitude: longString) { address in
        print(address)
        strFormattedAddress = address
        completion(strFormattedAddress)
    }
}

你需要这样称呼它:

LocationManager.shared.getCurrectLocationInfo) { locationInfo in 
    strPlaceSearched = locationInfo
}

【讨论】:

  • 转义闭包捕获非转义参数'completion'
  • 立即查看,我刚刚更新了。
  • 您能否指导我的电话“strPlaceSearched = LocationManager.shared.getCurrectLocationInfo(completion {success in })”中有什么问题
  • 成功了吗?我在回答中添加了如何使用该方法。
  • 我自己也修复了调用方法问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-03-11
  • 1970-01-01
  • 2021-12-06
  • 1970-01-01
  • 1970-01-01
  • 2014-08-25
  • 1970-01-01
相关资源
最近更新 更多