Swift 2 – Can't get user location with CLLocationManager

馋奶兔 提交于 2019-11-28 14:06:34

This works for me

Swift 2 - (Xcode 7.2.1)

ViewController.swift


import UIKit
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager = CLLocationManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        self.locationManager.stopUpdatingLocation()

        let latestLocation = locations.last

        let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
        let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)

        print("Latitude: \(latitude)")
        print("Longitude: \(longitude)")
    }
}

info.plist

Add a new line

Information Property List: NSLocationWhenInUseUsageDescription

Type: String

Value: The application uses this information to show you your location

Try getting the location by getting the last object for the array locations in the method locationManager(_:,didUpdateLocations locations: [CLLocations]) .

Something like this:

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let locValue:CLLocationCoordinate2D = locations.last!
        print("locations = \(locValue.latitude) \(locValue.longitude)")
}  

you have to use these location access permission in your plist.

  1. NSLocationAlwaysAndWhenInUseUsageDescription
  2. NSLocationWhenInUseUsageDescription

you are not using always and in InUse permiossion

Note by Apple:

This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!