gpt4 book ai didi

ios - CLLocationManager 返回 Nil 值

转载 作者:行者123 更新时间:2023-11-29 01:37:14 24 4
gpt4 key购买 nike

我正在尝试使用 CLLocationManager 以两个坐标的形式返回用户位置。

  • 我认为我拥有适当的授权 (authorizedWhenInUse),但在获取实际位置时它返回 nil

  • 我还将 NSLocationWhenInUseUsageDescription 添加到我的 plist

    import UIKit
    import CoreLocation
    class ViewController: UIViewController, CLLocationManagerDelegate {
    // Create an instance of the CLLocationManager
    var locManager = CLLocationManager()

    // View did load function (run things inside of here)
    override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    locManager.delegate = self
    locManager.desiredAccuracy = kCLLocationAccuracyBest

    // Check authorizationStatus
    let authorizationStatus = CLLocationManager.authorizationStatus()
    // List out all responses
    switch authorizationStatus {
    case .AuthorizedAlways:
    println("authorized")
    case .AuthorizedWhenInUse:
    println("authorized when in use")
    case .Denied:
    println("denied")
    case .NotDetermined:
    println("not determined")
    case .Restricted:
    println("restricted")
    }

    // Get the location
    locManager.startUpdatingLocation()

    if( CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse){
    // Extract the location from CLLocationManager
    let userLocation = locManager.location

    // Check to see if it is nil
    if userLocation != nil {
    println("location is \(userLocation)")
    } else {
    println("location is nil")
    }
    } else {
    println("not authorized")
    }

    }
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

最佳答案

SDK 中的 CLLocationManager.h 头文件提供了有关“.location”属性的有用提示:

Discussion:
* The last location received. Will be nil until a location has been received.

最好的办法是实现:

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

委托(delegate)方法并从那里获取您的位置,当设备的 GPS 解析手机所在位置时调用该方法。

类似于:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]!) {

let userLocation = manager.location

print("location = \(userLocation.latitude) \(userLocation.longitude)")

}

关于ios - CLLocationManager 返回 Nil 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32832672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com