简体   繁体   中英

Getting current location using CLLocationManager in Swift

How do I get the current location of my iOS device?

It seems that Apple has made changes that to how get location and I could not find an up-to-date post. I answered this question myself below:

I couldn't find an up-to-date solution to getting the current location so here's how I did it.

My source is apple's sample code on location tracking and smart watch called PotLocCoreLocationwithiPhoneandAppleWatch : https://github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch

Here's what you have to do in your app.

Note that everything from steps 2-6 are in this gist: https://gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd

  1. In the project settings in xcode, click on the capabilities tab (it's the tab beside the general tab where you put in your bundle identifier). Then turn on Background Mode and enable Location updates . EDIT thanks to @Rob: And also add NSLocationWhenInUseUsageDescription to your plist. The value can be anything you like
  2. Inside your view controller, extend the CLLocationManagerDelegate

     class YourClass: UIViewController, CLLocationManagerDelegate { 
  3. Implement these two functions

     /** Increases that location count by the number of locations received by the manager. Updates the batch count with the added locations. */ func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { //use the "locations" variable here } /// Log any errors to the console. func locationManager(manager: CLLocationManager, didFailWithError error: NSError) { print("Error occured: \\(error.localizedDescription).") } 
  4. Create a let manager = CLLocationManager() variable

  5. On viewDidLoad() set the following: manager.requestWhenInUseAuthorization() , manager.allowsBackgroundLocationUpdates = true , and manager.startUpdatingLocation()
  6. In order to stop tracking do the following: manager.stopUpdatingLocation() and manager.allowsBackgroundLocationUpdates = false

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM