【发布时间】:2016-02-25 23:35:30
【问题描述】:
我正在使用集合视图和集合视图可重用标题。在标题中,我试图获取用户的位置。我不断收到此错误:
Trying to start MapKit location updates without prompting for
location authorization. Must call -[CLLocationManager
requestWhenInUseAuthorization] or -[CLLocationManager
requestAlwaysAuthorization] first.
我查看了这个问题:Location Services not working in iOS 8,但没有一个建议的解决方案对我有用。我已将密钥(NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription)添加到我的 info.Plist 中,但这并没有帮助。该应用程序从不要求用户获取其位置。这是我的代码:
编辑:我现在的代码:
import UIKit
import MapKit
import Parse
import ParseUI
import CoreLocation
class ReusableHeaderMap: UICollectionReusableView, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
@IBOutlet weak var newMap: MKMapView!
override func awakeFromNib() {
locationManager.delegate = self
let status = CLLocationManager.authorizationStatus()
if status == CLAuthorizationStatus.Denied {
}
else if status == CLAuthorizationStatus.NotDetermined {
self.locationManager.requestAlwaysAuthorization()
}
else if status == CLAuthorizationStatus.AuthorizedAlways {
self.locationManager.startUpdatingLocation()
}
else {
print("it took the else route")
}
print("status is \(status)")
self.newMap.layer.cornerRadius = 8
self.newMap.clipsToBounds = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if locations.count > 0 {
locationManager.stopUpdatingLocation()
let location1 = locations.first as CLLocation!
let mapSpan = MKCoordinateSpan(latitudeDelta: 0.05, longitudeDelta: 0.05)
let mapRegion = MKCoordinateRegion(center: location1.coordinate, span: mapSpan)
self.newMap.setRegion(mapRegion, animated: true)
}
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.Denied {
print("there will be limited functionaliy")
}
else if status == CLAuthorizationStatus.AuthorizedAlways {
self.locationManager.startUpdatingLocation()
}
else {
print("it took the else route")
}
}
}
我的 info.plist 有这个键:
<key>NSLocationAlwaysUsageDescription</key>
<string>Get User Location</string>
【问题讨论】:
-
我假设您正在设备上进行测试。从设备中删除该应用,然后重试。
-
我试过了,但没有用,我仍然收到同样的错误信息。
-
你从
CLLocationManager.authorizationStatus()得到了什么价值?你的didChangeAuthorizationStatus()方法被调用了吗? -
状态未确定。是的,正在调用 didCHangeAuthorizationStatus()。在那里,我有“else if status == CLAuthorizationStatus.NotDetermined { self.locationManager.requestWhenInUseAuthorization() }”,但它从来没有提示用户请求授权。
标签: ios swift cllocationmanager