CLLocation Manager in Swift to get Location of User

后端 未结 13 1982
不知归路
不知归路 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:23

    For Swift 3

    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()
    
            // Do any additional setup after loading the view, typically from a nib.
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
        func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print("locations = \(locations)")
        }
    
    
    }
    
    0 讨论(0)
  • 2020-11-27 05:24

    Just call the init(vc : UIViewController).

        import Foundation
        import CoreLocation
        import UIKit
    
    
        class LocManager : NSObject{
    
    
            var permission : ((Bool?)->())?
    
            private var locationManager : CLLocationManager!
    
            init(_ vc : UIViewController) {
                super.init()
                self.locationManager = CLLocationManager()
                self.locationManager.delegate = vc as? CLLocationManagerDelegate
                setUpLocationManagerDelegate()
            }
    
    
        }
    
        extension LocManager : CLLocationManagerDelegate {
    
            fileprivate func setUpLocationManagerDelegate(){
                   locationManager = CLLocationManager()
                   locationManager.delegate = self
                   locationManager.desiredAccuracy = kCLLocationAccuracyBest
                   locationManager.requestAlwaysAuthorization()
               }
    
            func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
                if let lat  = locations.last?.coordinate.latitude, let long = locations.last?.coordinate.longitude{
                    print("\n\nThe current Lat/Long Is Here\n\n")
                    let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
    
                }else{
                    print("Unable To Access Locaion")
                }
            }
    
            func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
    
                switch status {
                case .authorizedAlways,.authorizedWhenInUse:
                    print("Good to go and use location")
                    locationManager.startUpdatingLocation()
                    self.callPermisssionCompletion(val: true)
    
                case .denied:
                    print("DENIED to go and use location")
                    self.callPermisssionCompletion(val: false)
    
                case .restricted:
                    print("DENIED to go and use location")
                    self.callPermisssionCompletion(val: nil)
    
                case .notDetermined:
                    print("DENIED to go and use location")
                    self.callPermisssionCompletion(val: nil)
    
                default:
                    print("Unable to read location :\(status)")
                }
            }
    
    
            fileprivate func callPermisssionCompletion(val : Bool?){
    
                guard let comp = self.permission else {
                    print("\n\n Unable to  locate completions \n\n")
                    return
                }
                if let val =  val{
                    comp(val)
                }
    
            }
    
    
        }
    
    0 讨论(0)
  • 2020-11-27 05:25

    First add this two line in plist file

    1. NSLocationWhenInUseUsageDescription

    2. NSLocationAlwaysUsageDescription

    Then this is class working complete implement this

    import UIKit
    
    import CoreLocation
    
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
    
    var window: UIWindow?
    var locationManager: CLLocationManager!
    var seenError : Bool = false
    var locationFixAchieved : Bool = false
    var locationStatus : NSString = "Not Started"
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        initLocationManager();
        return true
    }
    
    // Location Manager helper stuff
    func initLocationManager() {
        seenError = false
        locationFixAchieved = false
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.locationServicesEnabled
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        locationManager.requestAlwaysAuthorization()
    }
    
    // Location Manager Delegate stuff
    // If failed
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        if (error) {
            if (seenError == false) {
                seenError = true
               print(error)
            }
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
        if (locationFixAchieved == false) {
            locationFixAchieved = true
            var locationArray = locations as NSArray
            var locationObj = locationArray.lastObject as CLLocation
            var coord = locationObj.coordinate
    
            println(coord.latitude)
            println(coord.longitude)
        }
    }
    
    // authorization status
    func locationManager(manager: CLLocationManager!,
        didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            var shouldIAllow = false
    
            switch status {
            case CLAuthorizationStatus.Restricted:
                locationStatus = "Restricted Access to location"
            case CLAuthorizationStatus.Denied:
                locationStatus = "User denied access to location"
            case CLAuthorizationStatus.NotDetermined:
                locationStatus = "Status not determined"
            default:
                locationStatus = "Allowed to location Access"
                shouldIAllow = true
            }
            NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
            if (shouldIAllow == true) {
                NSLog("Location to Allowed")
                // Start location services
                locationManager.startUpdatingLocation()
            } else {
                NSLog("Denied access: \(locationStatus)")
            }
    }
    }
    
    0 讨论(0)
  • 2020-11-27 05:26

    had the same issue. didUpdateLocations - was not working. Run your app. Go to the Settings page -> Privacy -> Location and turn off Location Services. didFailWithError will catch the error about absent Location Services. Then turn it on. Since that moment didUpdateLocations will catch locations.

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

    Add bellow 2 property in info.plist

    NSLocationWhenInUseUsageDescription : Location information is used for fraud prevention
    
    Privacy - Location Usage Description : Location information is used for fraud prevention
    
    0 讨论(0)
  • 2020-11-27 05:35

    If you want to get the user location updated by default, without clicking 'Simulate location' everytime, go to

    YourProject-->Build Phases-->Link Binary with libraries-->Add corelocation.framework
    

    The location gets updated automatically/by default when you run the app in the simulator. Tested and works in Swift 2 !

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