【问题标题】:How to call "didUpdateLocation" method from viewDidLoad?如何从 viewDidLoad 调用“didUpdateLocation”方法?
【发布时间】:2019-09-17 11:48:19
【问题描述】:

我正在制作一个天气应用程序,它通过发送当前坐标来获取温度信息。所以我正在使用 CLLocationManager。我还没有发出任何 HTTP 请求。我想在我的屏幕上看到“位置不可用”,但它不起作用。

我正在关注一个教程并编写了完全相同的代码,但在教程中它正在工作。在调试会话中,它不会跳转到 didFailwithError 或 didUpdateLocations 方法。我在我的 info.plist 和我手机的定位服务是开放的。根据我的研究 locationManager.startUpdatingLocation() 应该自动调用 这些方法,但是当我运行我的应用程序时,UI 上什么也没有显示。

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   print("you got the location")

}

//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
    cityLabel.text = "Location Unavaiable"
}

let locationManager = CLLocationManager ()
override func viewDidLoad() {
    super.viewDidLoad()

    //TODO:Set up the location manager here.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

}

【问题讨论】:

    标签: ios swift4 cllocationmanager


    【解决方案1】:

    您更新位置太快了,实际上是在您获得用户许可之前。

    在您请求许可后

    locationManager.requestWhenInUseAuthorization()
    

    委托方法会调用

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    
    }
    

    现在是时候开始更新了。保护状态是个好主意,因为除非用户允许,否则您不想开始更新。

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    
            guard status == .authorizedWhenInUse else { return }
            manager.startUpdatingLocation()
    
    }
    

    现在您将获得位置更新

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

    【讨论】:

    • 你是在设备上还是在模拟器上?
    • 我在模拟器上
    • 好的,好消息。模拟器没有定位服务,你也必须模拟它。从 Xcode 菜单 > 产品 > 方案 > 编辑方案。从左侧选择run,在右侧选择options。在列表顶部,选中 Allow Location Simulation 并选择任何城市作为默认位置。
    • 不幸的是,没有任何改变。这很有趣也很烦人。
    • 令人惊讶的是,上次我运行它的代码!谢谢你的帮助:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    相关资源
    最近更新 更多