CLLocation Manager in Swift to get Location of User

后端 未结 13 1980
不知归路
不知归路 2020-11-27 04:48

I am trying to convert an old app in ObjC to Swift as a practice exercise and have ran in to some issues. The way I had it in the old app, it was establishing the CLLocatio

相关标签:
13条回答
  • 2020-11-27 05:15

    You are missing two things. First, you have to ask for permission using requestAlwaysAuthorization or requestWhenInUseAuthorization(). So your viewDidLoad() should be like this:

    var locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
    

    Second, edit your Info.plist as indicated here.

    0 讨论(0)
  • 2020-11-27 05:15

    Here is my very simple code that works:

    first add Core Location framework in General/Linked Frameworks and Libraries

    then add following into Info.plist:

    <key>NSLocationWhenInUseUsageDescription</key>
    <string>blablabla</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>blablabla</string>
    

    this is my ViewController.swift file:

    import UIKit
    import CoreLocation
    
    class ViewController: UIViewController, CLLocationManagerDelegate {
    
        var locationManager:CLLocationManager!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    
    
        func locationManager(manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print("locations = \(locations)")
        }
    
    }
    
    0 讨论(0)
  • 2020-11-27 05:16

    don't forget to add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription in your configuration file (target/Info/custom iOS target properties

    0 讨论(0)
  • 2020-11-27 05:18

    I hope there are two ways.

    var locationManager: CLLocationManager = CLLocationManager()
    var initialLocation :CLLocation?
    var updatedUserLocation :CLLocation?
    
    override func viewDidLoad() {
        super.viewDidLoad() {
    
        //MapView Location
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()
        locationManager.startUpdatingHeading()
    }
    

    Implementing CLLocationManagerDelegate :

    //CLLocationManager Delegate
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
        // This only works when user location is updated.
        gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
    
    }
    
    func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
    
        //Error indicates GPS permission restricted
    
        gpsProviderStatusLabel.changeStatusToOff(gpsProviderStatusLabel)
    
        //Initial Location
        initialLocation = locations.first
    
        //Getting Updated Location
        updatedUserLocation = locations.last
    }
    

    Checking CLLocationDelegate Authorization:

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
    
        //This method does real time status monitoring.
    
            switch status {
            case .NotDetermined:
              print(".NotDetermined")
              break
    
            case .AuthorizedAlways:
              print(".AuthorizedAlways")
              gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
              break
    
    
            case .Denied:
              print(".Denied")
              gpsProviderStatusLabel.changeStatusToOff(gpsProviderStatusLabel)
              break
    
            case .AuthorizedWhenInUse:
              print(".AuthorizedWhenInUse")
              gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
              break
    
            case .Restricted:
              print(".Restricted")
              break
    
            default:
              print("Unhandled authorization status")
              break
    
            }
          }
    

    Note: changeStatusToOn or changeStatusToOff is a UILabel Extenion method which makes the Label text On/Off with Green/Red Colors.

    0 讨论(0)
  • 2020-11-27 05:19

    I'm not sure why, but it seems like startUpdatingLocation isn't presenting the user prompt on the iOS 7 simulator, but when I enabled it manually it worked as expected if I used the newer form of the delegate method:

    var manager:CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    
        manager = CLLocationManager()
        manager.delegate = self
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.startUpdatingLocation()
    }
    
    func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) { // Updated to current array syntax [AnyObject] rather than AnyObject[]
        println("locations = \(locations)")
    }
    

    The format you're using has been deprecated since iOS 5 or 6, so apparently it's not supported at all by the swift bridging layers.

    0 讨论(0)
  • 2020-11-27 05:22

    Swift:

    Add following in

    import CoreLocation
    class YourViewController: UIViewController
    {
           var locationManager:CLLocationManager!
    }
    
    
    //MARK:- Location Manager
    extension YourViewController: CLLocationManagerDelegate {
    
        func stratLocationManager()
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            self.checkUsersLocationServicesAuthorization()
            locationManager.startUpdatingLocation()
    
        }
    
        func checkUsersLocationServicesAuthorization(){
            /// Check if user has authorized Total Plus to use Location Services
            if CLLocationManager.locationServicesEnabled()
            {
                switch CLLocationManager.authorizationStatus()
                {
                case .notDetermined:
                    // Request when-in-use authorization initially
                    // This is the first and the ONLY time you will be able to ask the user for permission
                    self.locationManager.delegate = self
                    locationManager.requestWhenInUseAuthorization()
                    break
    
                case .restricted, .denied:
                    // Disable location features
                    PrintLogs("Location Access Not Available")
                    break
    
                case .authorizedWhenInUse, .authorizedAlways:
                    // Enable features that require location services here.
                    PrintLogs("Location Access Available")
                    break
                }
            }
        }
    
        func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print("locations = \(locations)")
        }
    }
    
    0 讨论(0)
提交回复
热议问题