CLLocation Manager in Swift to get Location of User

后端 未结 13 2103
不知归路
不知归路 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: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)")
        }
    }
    

提交回复
热议问题