作者:aaron飞飞 | 来源:互联网 | 2023-05-29 11:39
如何解决《requestWhenInUseAuthorization()在iOS8中不起作用Info.plist中的NSLocationWhenInUseUsageDescription键》经验,为你挑选了1个好方法。
我正在使用iOS SDK 8.1尝试调用requestWhenInUseAuthorization()方法来提示用户授予对我的应用程序的访问权限.我导入了CoreLocation.framework,并将NSLocationWhenInUseUsageDescription和NSLocationAlwaysUsageDescription键添加到info.plist中.当我运行应用程序时,它从未提示我进行位置访问.以下是我的代码,我错过了什么?
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
var manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
let authorizatiOnStatus= CLLocationManager.authorizationStatus()
switch authorizationStatus {
case .Authorized:
println("authorized")
case .AuthorizedWhenInUse:
println("authorized when in use")
case .Denied:
println("denied")
case .NotDetermined:
println("not determined")
case .Restricted:
println("restricted")
}
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let location = locations[0] as CLLocation
println("Latitude: \(location.coordinate.latitude). Longitude: \(location.coordinate.longitude).")
}
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case .Authorized:
println("authorized")
case .AuthorizedWhenInUse:
println("authorized when in use")
case .Denied:
println("denied")
case .NotDetermined:
println("not determined")
case .Restricted:
println("restricted")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
控制台只显示"未确定"一次,没有别的.所以我去了iPhone模拟器=>设置=>隐私=>位置=>我的应用程序.它向我展示了3个选项:"从不","使用应用程序时","始终".但没有选择任何东西.
1> toadead..:
问题解决了.我manager
被声明为局部var inside viewDidLoad()
方法,但它应该是类级属性.
我将manager
声明移出后viewDidLoad()
,我的应用程序工作了.
不知道究竟是如何manager.requestWhenInUseAuthorization()
在幕后工作,到底为什么manager
中定义viewDidLoad()
不起作用.希望知道这个细节的人启发我.