【发布时间】:2016-05-24 10:17:12
【问题描述】:
我编写了一个使用设备位置的基本程序。我已经写好了,这就是 ViewController 的基础
override func viewDidLoad() {
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Location Updated")
lat = String(format: "%f", locationManager.location!.coordinate.latitude)
long = String(format: "%f", locationManager.location!.coordinate.longitude)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Failed Loc: \(error)")
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
print("Auth Changed: \(status)")
}
根据需要,在我的 info.plist 中有这个:
<key>NSLocationWhenInUseUsageDescription</key>
<string>uses loc</string>
我在模拟器上运行了代码,它给了我
Failed Loc: Error Domain=kCLErrorDomain Code=0 "(null)"
然后我确定了模拟器的位置并打印出来
Location Updated
应该如此。奇怪;但是,当我将其上传到我的 ios 设备上时,它会请求许可,然后我没有得到任何输出。没有输出错误,甚至没有触发 didChangeAuthorizationStatus
**编辑:这里是 ViewController 文件的标题:
import CoreLocation
class Central_ViewController: UIViewController, UIScrollViewDelegate, UITabBarDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
**编辑 2:
self.locationManager.requestWhenInUseAuthorization()
if(CLLocationManager.locationServicesEnabled()) {
print("Location Services Enabled")
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.startUpdatingLocation()
}else {
print("Location Services NOT Enabled") // This needs to be completed to produce an error
}
打印
Location Services Enabled
Location Services Enabled
但它仍然没有更新位置也没有产生错误。
【问题讨论】:
-
你能发布你的视图控制器声明吗?
-
是的,请查看编辑。
-
在 viewDidLoad
if CLLocationManager.locationServicesEnabled() {中设置代理之前应该检查一下,不要忘记在此之前添加locationManager.requestWhenInUseAuthorization() -
我已经事先打印出来了,它的评估结果为真。所以这不是问题。你是说我需要在设置委托之前 requestAuth 吗?
-
我遇到的情况是这段代码在模拟器上完美运行,但在设备上却不行。这里出了什么问题?
标签: ios swift cllocationmanager