CLLocationManager requestWhenInUseAuthorization() not working

后端 未结 1 1826
星月不相逢
星月不相逢 2021-01-19 13:47

I am trying to use location services in my iOS app but for some reason requestWhenInUseAuthorization is not working. When the user first uses the app, the promp

相关标签:
1条回答
  • 2021-01-19 14:31

    First you need to add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription(if you want to use in background) in your info.plist file. See the following image:

    enter image description here

    Next, in your swift file, you need to call either locationManager.requestWhenInUseAuthorization() or locationManager.requestAlwaysAuthorization() in your viewDidLoad() method.

    Finally, you can do a mapView.camera = GMSCameraPosition(target: locations.last!.coordinate, zoom: 15, bearing: 0, viewingAngle: 0) in your locationManager delegate method.

    Sample code:

    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)
        }
    }
    

    You can will this post, for more details about LocationManager change in iOS 8.

    0 讨论(0)
提交回复
热议问题