CoreLocation iOS 8 and Swift

I started my first swift app with iOS 8 and needed to use core location, something that I haven’t used in a really long time. After writing all the code and testing out the app I couldn’t get the dang thing to use my location! After a frustrating 30 min of debugging I figured out what the issue is and decided to write this post to hopefully help you avoid that frustration. So here is what you need to do to get core location working with iOS 8 and swift.

CoreLocation Project setup

Add the CoreLocation.framework to your project

First step is to select your project in the project navigator, and select your project target. Once selected expand the link binary and click the add items button. Choose the CoreLocation.framework from the pop up window.
Screen Shot 2014-10-09 at 7.14.55 AM

Editing Info.plist

This is where I screwed up in my attempt, I forgot to add the property key in my plist. This caused the app not to get my location, and it didn’t give any warning or error to let me know there was even a problem. So add NSLocationWhenInUseUsageDescription or NSLocationAlwaysUsageDescription key in your Info.plist file to indicate the level of authorization you require. NSLocationWhenInUseUsageDescription will allow you to get the device location when you are using the app and NSLocationAlwaysUsageDescription will allow you to get the device location when you are using the app as well as in the background when the app isn’t running. The key you set is what will be displayed in the pop up asking for permission. Also as a side note if you need to localize your plist here is apple’s docs on how to do that Localizing Property List Values. I only need to use location while the app is in use so I used NSLocationWhenInUseUsageDescription and only wanted apple’s default message so I left the value blank.
Screen Shot 2014-10-09 at 7.37.09 AM

Create your view controller and add the CLLocationManagerDelegate

Now that we have all that project setup done we can get on to the code. So first step is to add the CLLocationManagerDelegate to your view controller, implement these delegate methods. Then init your CLLocationManager and start receiving your location data.

//
//  MapViewController.swift
//
//  Created by Barrett Breshears on 10/6/14.
//  Copyright (c) 2014 Sledge Dev. All rights reserved.
//

import UIKit
import CoreLocation

class MapViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        if (CLLocationManager.locationServicesEnabled()) {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        } else {
            println("Location services are not enabled");
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    // MARK: - CoreLocation Delegate Methods
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        removeLoadingView()
        if ((error) != nil) {
            print(error)
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        var locationArray = locations as NSArray
        var locationObj = locationArray.lastObject as CLLocation
        var coord = locationObj.coordinate
        println(coord.latitude)
        println(coord.longitude)
    }
}

Let me know if there are any questions or comments about the code or the project setup. Also don’t forget to follow me on twitter! I’m always looking for new internet friends.

Author: barrettbreshears

I don't take showers, only blood baths.

11 thoughts on “CoreLocation iOS 8 and Swift”

  1. I got this to work, but to clean up my code i want to move the locationManager func into its own class. Then access it from any view controller when I need to. How would you accomplish this? Thanks!

    1. I think it is best to implement these locationManager methods in the view controllers that need location data since they are delegate methods for the location manager. That is why we are implementing the CLLocationManagerDelegate protocol. If you move them into their own class it would just be duplicating the CLLocationManagerDelegate functionality.

  2. It works, thanks a lot! I’ll share it! Nvevertheless I have one minor question – How to modify the code to get the current coordinates exactly ones every time the function is triggered? I mean I do not need to update my location automatically, I want to obtain coordinates wherever I push some button or something. Thanks in Advance!

    1. You could create an @IBAction and call the locationManager.startUpdatingLocation(). Once you received the location you could stop it by calling locationManager.stopUpdatingLocation(). Hope it helps let me know if you have any other questions! Thanks for the comment.

  3. You are a lifesaver! I couldn’t figure out why it wasn’t accessing my location until I saw the info.plist part.

  4. This tutorial works great, but I don’t really understand it. I also don’t understand how to get the data into a URL call.

    Can you explain more as to what the below is doing?
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationManager.stopUpdatingLocation()
    if ((error) != nil){
    print(error)
    }

    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    var locationArray = locations as NSArray
    var locationObj = locationArray.lastObject as CLLocation
    var coord = locationObj.coordinate
    var locationLatitude = coord.latitude
    var locationLongitude = coord.longitude

    self.locationManager.stopUpdatingLocation()

    }

    I want to return latitude and longitude into a JSON request to get the local weather information. Just trying to figure out how to write that.

    Thanks in advance

Comments are closed.