我正在尝试使用CLLocationManager以两个坐标的形式返回用户位置。
我认为我有正确的授权(authorizedWhenInUse
),但在获取实际位置时,它会返回nil
。
我的帖子中还添加了NSLocationWhenInUseUsageDescription
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.
}
}
答案 0 :(得分:1)
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])
委托方法并将您的位置从那里取出,当设备的GPS结算到手机所在位置时会调用该位置。
类似的东西:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [AnyObject]!) {
let userLocation = manager.location
print("location = \(userLocation.latitude) \(userLocation.longitude)")
}