iOS App Development iOS8

Swift Tutorial : CoreLocation and Region Monitoring in iOS 8

CoreLocation and Region Monitoring

We will learn how to use CoreLocation and Region Monitoring in Swift. You will be able to change your app to accommodate breaking changes in Core Location.

Location Authorization

Request for authorization for all location functionality. The authorization message can be customized. In iOS 8 there are two Authorization types

  • When in use
  • Always Authorization

Prerequisites for getting CoreLocation to work in iOS 8

Info.plist keys

Two news keys are added to the info.plist and one of them is mandatory if you want to use location in your app.

  • NSLocationAlwaysUsageDescription
  • NSLocationWhenInUseUsageDescription

The value of the keys is the message which you want to display when requesting the authorization.

images

Add Require Frameworks

Add CoreLocation and MapKit(If you want to display a map) to the Build Phases

images

Enable Background mode

If you want any features for signification location changes or region monitoring make sure you enable the background mode to location in the capabilities tab.

images

Creating a GPX file.

Xcode allows you to add custom gpx file to simulate location. To create a gpx file go to http://gpx-poi.com/ provide the longitude and latitude and any other features, then select for mac and download the xml file.
And then add it to Xcode as described below.

You can edit the scheme to make this newly added gpx location as your default location.

images

Lets look at flow for getting any location information

If you are interested in learning iOS Development I suggest you take a look at Building an app every month in 2015

For CoreLocation

  • Make sure the view controller conforms to protocol CLLocationManagerDelegate.
  • Set the CLLocationManager delegate to self.
  • Set the desired accuracy to best
  • If you app will access the location only in the foreground or when the app is in use, request for requestWhenInUseAuthorization().
  • Finally you need to implement func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
  • If you want to display the map view we could use the location coordinate which we just got in didUpdateLocation and set it up as a mapView region as shown in the code below.

For Region Monitoring

  • Make sure the view controller conforms to protocol CLLocationManagerDelegate.
  • Set the CLLocationManager delegate to self.
  • Set the desired accuracy to best
  • We need to request for requestAlwaysAuthorization().
  • Finally you need to implement didEnterRegion and didExitRegion and put any custom login in those functions.
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
        NSLog("Entering region")
    }
    func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
        NSLog("Exit region")
}
Testing Region Monitoring.
I add my home location as the default location and when I enable the region monitoring I could change the location in the xcode to simulate entering and leaving my home.
//
//  ViewController.swift
//  CoreLocation
//
//  Created by Shrikar Archak on 12/27/14.
//  Copyright (c) 2014 Shrikar Archak. All rights reserved.
//

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    var manager: CLLocationManager?

    @IBOutlet weak var mapView: MKMapView!
    @IBOutlet weak var address: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
        manager = CLLocationManager()
        manager?.delegate = self;
        manager?.desiredAccuracy = kCLLocationAccuracyBest

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    @IBAction func getLocation(sender: AnyObject) {
        let available = CLLocationManager.isMonitoringAvailableForClass(CLCircularRegion)
        manager?.requestWhenInUseAuthorization()
        manager?.startUpdatingLocation()


    }


    @IBAction func regionMonitoring(sender: AnyObject) {
        manager?.requestAlwaysAuthorization()

        let currRegion = CLCircularRegion(center: CLLocationCoordinate2D(latitude: 37.411822, longitude: -121.941125), radius: 200, identifier: "Home")
        manager?.startMonitoringForRegion(currRegion)

    }
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
        manager.stopUpdatingLocation()
        let location = locations[0] as CLLocation
        let geoCoder = CLGeocoder()
        geoCoder.reverseGeocodeLocation(location, completionHandler: { (data, error) -> Void in
            let placeMarks = data as [CLPlacemark]
            let loc: CLPlacemark = placeMarks[0]

            self.mapView.centerCoordinate = location.coordinate
            let addr = loc.locality
            self.address.text = addr
            let reg = MKCoordinateRegionMakeWithDistance(location.coordinate, 1500, 1500)
            self.mapView.setRegion(reg, animated: true)
            self.mapView.showsUserLocation = true

        })
    }

    func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
        NSLog("Entering region")
    }

    func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
        NSLog("Exit region")
    }

    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        NSLog("\(error)")
    }

}

Please let me know if you have any questions/feedback.

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

  • http://www.rosin355.com Rosin355

    Hi,
    love this tutorial… Such long time was try to find something related to Region Monitoring… Thanks for sharing…

    One question… What plugin you use for sharing code on your website?

    Thanks

    cheers

    • https://shrikar.com shrikar

      Hi Rosin,
      I use a plugin called WP Code highlight.

      • http://www.rosin355.com Rosin355

        Thanks a lot…

  • Ryan Westcott

    First of all: great tutorial! Thank you!

    Now, I’m on Xcode 7 beta 5 and getting an error on line 37. The error image is below. Anyone else getting this error? If so please help, thanks!

    • Ryan Westcott

      Ahhh, fixed it!

    • Pallindrome

      Use this code:

      func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

      manager.stopUpdatingLocation()

      let location = locations[0] as CLLocation

      let geoCoder = CLGeocoder()

      geoCoder.reverseGeocodeLocation(location, completionHandler: { (data, error) -> Void in

      let placeMarks = data ?? []

      let loc: CLPlacemark = placeMarks[0]

      self.map.centerCoordinate = location.coordinate

      let addr = loc.locality

      self.address.text = addr

      let reg = MKCoordinateRegionMakeWithDistance(location.coordinate, 1500, 1500)

      self.map.setRegion(reg, animated: true)

      self.map.showsUserLocation = true

      })

      }

  • Ryan Westcott

    Hello MX, I’m having the same problem. Did you ever find out how to fix it?

  • Pallindrome

    When I click region monitoring nothing happens ! can anyone tell why !

/* ]]> */