gpt4 book ai didi

ios - CLLocationManager requestWhenInUseAuthorization() 不工作

转载 作者:搜寻专家 更新时间:2023-10-31 08:14:20 25 4
gpt4 key购买 nike

我正在尝试在我的 iOS 应用程序中使用定位服务,但由于某些原因 requestWhenInUseAuthorization 无法正常工作。当用户第一次使用该应用程序时,提示会正常要求权限,但是当您第二次打开该应用程序时,由于某种原因 didChangeAuthorizationStatus 方法未被调用,因此我无法显示用户当前在 map 上的位置。

我的代码如下:

 override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
var config:NSURLSessionConfiguration = NSURLSessionConfiguration.defaultSessionConfiguration()
config.URLCache = NSURLCache(memoryCapacity: 2 * 1024 * 1024, diskCapacity: 10 * 1024 * 1024, diskPath: "MarkerData")
markerSession = NSURLSession(configuration: config)
}



func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {

locationManager.startUpdatingLocation()
mapView.delegate = self
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}

最佳答案

首先,您需要在 info.plist 文件中添加 NSLocationWhenInUseUsageDescriptionNSLocationAlwaysUsageDescription(如果您想在后台使用)。见下图:

enter image description here

接下来,在您的 swift 文件中,您需要在 viewDidLoad() locationManager.requestWhenInUseAuthorization()locationManager.requestAlwaysAuthorization()方法。

最后,您可以在 locationManager 委托(delegate)方法中执行 mapView.camera = GMSCameraPosition(target: locations.last!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)

示例代码:

class ViewController: UIViewController, CLLocationManagerDelegate {

var locationManager = CLLocationManager();

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

var camera = GMSCameraPosition.cameraWithLatitude(-33.86,
longitude: 151.20, zoom: 6)
var mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
mapView.myLocationEnabled = true
self.view = mapView

locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
if #available(iOS 8.0, *) {
print("iOS >= 8.0.0")
locationManager.requestAlwaysAuthorization()
}
locationManager.startUpdatingLocation()

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println(locations.last)

var mapView = self.view as! GMSMapView

mapView.camera = GMSCameraPosition(target: locations.last!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
}
}

你可以this post ,了解有关 iOS 8 中 LocationManager 更改的更多详细信息。

关于ios - CLLocationManager requestWhenInUseAuthorization() 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28661963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com