我正在使用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 Simulator =>设置=>隐私=>位置=>我的应用。它向我显示了3个选项:“从不”,“在使用应用程序时”,“始终”。但是什么也没选择。
问题解决了。我manager被声明为viewDidLoad()方法内部的var ,但是它应该是一个类级别的属性。
manager
viewDidLoad()
将manager声明从中移出后viewDidLoad(),我的应用程序开始运行。
不确定如何manager.requestWhenInUseAuthorization()在幕后精确工作,以及为什么在其中精确manager定义viewDidLoad()不起作用。希望知道这个细节的人能启发我。
manager.requestWhenInUseAuthorization()