0

I want to check and see if the location is on and if it's not or user didn't give permission to use location, app quits (won't run). Is there a way to do this as people are saying using exit(0) is not recommended and will make Apple sad. :D

2 Answers2

2

you could put a view onto the screen (full width and height) with a label that tells the user that it's only possible to use the app with location services enabled. of course the user should not be possible to interact with this view in any way.

here is an example helper class:

import UIKit
import CoreLocation

class LocationHelper: NSObject, CLLocationManagerDelegate {
    private static let sharedInstance = LocationHelper()
    private var locationManager: CLLocationManager! {
        didSet {
            locationManager.delegate = self
        }
    }

    private override init() {}

    class func setup() {
        sharedInstance.locationManager = CLLocationManager()
    }

    private func informUserToEnableLocationServices() {
        let infoPopup = UIAlertController(title: "Location Services", message: "Sorry, but you have to enable location services to use the app...", preferredStyle: .Alert)
        let tryAgainAction = UIAlertAction(title: "Try again", style: .Default) { (action) in
            if CLLocationManager.authorizationStatus() != .AuthorizedWhenInUse {
                self.informUserToEnableLocationServices()
            }
        }
        infoPopup.addAction(tryAgainAction)
        let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate
        let rootViewController = appDelegate?.window?.rootViewController
        rootViewController?.presentViewController(infoPopup, animated: true, completion: nil)
    }

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        switch status {
        case .NotDetermined:
            locationManager.requestWhenInUseAuthorization()
        case .AuthorizedWhenInUse:
            break
        default:
            informUserToEnableLocationServices()
        }
    }
}

simply call LocationHelper.setup() after the app launched and the class should handle the rest...

André Slotta
  • 13,774
  • 2
  • 22
  • 34
1

Apple does not like exit(0) for a reason. I would highly recommend not terminating the app yourself. Maybe you could let the user use the app with limited features? Another option would be to make an alert with no actions, or actions that don't do anything.

Zack
  • 1,585
  • 1
  • 18
  • 29