Created
October 28, 2017 15:13
-
-
Save dedeexe/067417dd1b8ec7435951665ee415e45a to your computer and use it in GitHub Desktop.
Class to get the current device location using Core Location
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// DeviceLocation.swift | |
// | |
// Created by dede.exe on 28/10/17. | |
// Copyright © 2017 dede.exe. All rights reserved. | |
// | |
import Foundation | |
import CoreLocation | |
public class DeviceLocation : NSObject { | |
private(set) public var locationManager = CLLocationManager() | |
private(set) var updateLocationsEvent : (([CLLocation]) -> ())? = nil | |
private(set) var startEvent : (() -> ())? = nil | |
private(set) var stopEvent : (() -> ())? = nil | |
private(set) var errorEvent : ((Error) -> ())? = nil | |
private var isActive : Bool = false | |
public override init() { | |
super.init() | |
} | |
public func startLocation() { | |
locationManager.delegate = self | |
locationManager.requestWhenInUseAuthorization() | |
if CLLocationManager.locationServicesEnabled() { | |
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters | |
locationManager.requestLocation() | |
locationManager.startUpdatingLocation() | |
isActive = true | |
startEvent?() | |
} | |
} | |
public func stopLocation() { | |
locationManager.stopUpdatingLocation() | |
if isActive { | |
stopEvent?() | |
} | |
} | |
public func onUpdateLocations(event: (([CLLocation]) -> ())? = nil) { | |
updateLocationsEvent = event | |
} | |
public func onStart(event: (() -> ())? = nil) { | |
startEvent = event | |
} | |
public func onStop(event: (() -> ())? = nil) { | |
stopEvent = event | |
} | |
public func onError(event: ((Error) -> ())? = nil) { | |
errorEvent = event | |
} | |
} | |
extension DeviceLocation : CLLocationManagerDelegate { | |
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { | |
self.updateLocationsEvent?(locations) | |
} | |
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { | |
self.errorEvent?(error) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment