Skip to content

Instantly share code, notes, and snippets.

@akisute
Created August 2, 2014 14:23
Show Gist options
  • Save akisute/224e5ec62aed2a44e0e9 to your computer and use it in GitHub Desktop.
Save akisute/224e5ec62aed2a44e0e9 to your computer and use it in GitHub Desktop.
LocationManager with PromiseKit-Swift. Well I don't like this deferred at all.
import Foundation
import CoreLocation
class LocationManager : NSObject, CLLocationManagerDelegate {
class var sharedInstance : LocationManager {
get {
struct Static {
static let instance : LocationManager = LocationManager()
}
return Static.instance
}
}
let locationManager:CLLocationManager = CLLocationManager()
var requestAuthorizationDeffered:(Promise<Bool>, (Bool)->(Void), (NSError)->(Void))? = nil
var isAvailable:Bool {
get {
if !CLLocationManager.locationServicesEnabled() {
return false
}
switch CLLocationManager.authorizationStatus() {
case .Authorized, .AuthorizedWhenInUse: return true
default: return false
}
}
}
init() {
super.init()
self.locationManager.delegate = self;
}
func requestAuthorization() -> Promise<Bool> {
if let deffered = self.requestAuthorizationDeffered {
return deffered.0
}
self.locationManager.requestWhenInUseAuthorization()
let deffered = Promise<Bool>.defer()
self.requestAuthorizationDeffered = deffered
return deffered.0
}
// MARK: - CLLocationManagerDelegate
func locationManager(manager: CLLocationManager!, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if let deffered = self.requestAuthorizationDeffered {
deffered.1(self.isAvailable)
self.requestAuthorizationDeffered = nil
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment