Core Location to an iOS Framework - ios

I am creating an iOS Framework and i want to use Core Location to interact with Beacons. For testing reasons i am trying to get user location.
This is the class i created in the framework.
import Foundation
import CoreLocation
public class BeaconManager:NSObject,CLLocationManagerDelegate{
var locationManager:CLLocationManager = CLLocationManager()
public override init() {
super.init()
locationManager.requestAlwaysAuthorization()
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
public func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
println(location)
}
}
}
And i am calling it from a test app that has the framework like this
import UIKit
import OtravitaSDK
import CoreLocation
class ViewController: UIViewController {
var bm = BeaconManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
But is not working , is not printing the location. I have set the NSLocationAlwaysUsageDescription both in framework's info.plist and the app's info.plist

you can add your decription in NSLocationAlwaysUsageDescription & NSLocationWhenInUseUsageDescription in plist
This code put into AppDelegate file
var locationManager:CLLocationManager?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//You can give this permission for fetch current location
var type = UIUserNotificationType.Badge | UIUserNotificationType.Alert | UIUserNotificationType.Sound;
var setting = UIUserNotificationSettings(forTypes: type, categories: nil);
UIApplication.sharedApplication().registerUserNotificationSettings(setting);
UIApplication.sharedApplication().registerForRemoteNotifications();
locationManager = CLLocationManager()
locationManager?.requestAlwaysAuthorization()
locationManager?.delegate = self
locationManager?.startUpdatingLocation()
// Override point for customization after application launch.
return true
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
if let location = locations.first as? CLLocation {
println(location)
}
}

What you need to do as of iOS 8 is configure your Info.plist file to cater for 2 kinds of location behaviour. You need to supply a default message that appears with a popup by default, asking the user for consent to use their location.
NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription
See this article for a full walkthrough and another SO post which discusses this topic. Hope this helps!

You can create at first the reporter class (with shared instance) which will implement the CLLocationManagerDelegate, so you could implement your logic inside delegate methods
import Foundation
import CoreLocation
class LocationReporter: NSObject, CLLocationManagerDelegate {
static let sharedInstance = LocationReporter()
func startUpdating(locationManager: CLLocationManager) {
locationManager.delegate = self
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
func stopUpdating(locationManager: CLLocationManager) {
locationManager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print("latitude: ", location.coordinate.latitude)
print("longitude: ", location.coordinate.longitude)
}
}
//implement other locationManger delegate methods
}
Next you can create a Client class
import Foundation
import CoreLocation
class LocationDetectionClient {
private let locationManager = CLLocationManager()
func start() {
LocationReporter.sharedInstance.startUpdating(locationManager: locationManager)
}
func stop() {
LocationReporter.sharedInstance.stopUpdating(locationManager: locationManager)
}
}
And finally call the Client methods where you need
let locationDetectionClient = LocationDetectionClient()
public func startLocationDetection() {
locationDetectionClient.start()
}
public func stopLocationDetection() {
locationDetectionClient.stop()
}
Hope this would help

Related

How to track set locationManager.delegate the right way?

I tried to use CoreLocation with Swift to track the user's location:
(Below you can find the code of may ViewController.swift file.)
But the code doesn't seems working as I've expected, because I'm still getting the same error every-time I'm launching the application:
I'm sure this is the problem why I'm not able to get a result from the locationManager() function that should print out the current location.
It says "Cannot assign value of type 'ViewController' to type 'CLLocationManagerDelegate?'"
import UIKit
import CoreLocation
class ViewController: UIViewController, WKUIDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
print("CLLocationManager is available")
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
}
let locationManager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print(location.coordinate)
}
}
}
Does anyone now how to fix this problem? - Any help would be very appreciated, thanks a million in advance.
You simply need to declare conformance to CLLocationManagerDelegate. You can either do this directly in the class declaration just as you did with WKUIDelegate or in an extension of ViewController.
class ViewController: UIViewController, WKUIDelegate, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
print("CLLocationManager is available")
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
}
let locationManager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print(location.coordinate)
}
}
}
With extension:
class ViewController: UIViewController, WKUIDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
print("CLLocationManager is available")
locationManager.desiredAccuracy = kCLLocationAccuracyThreeKilometers
locationManager.delegate = self
locationManager.startUpdatingLocation()
}
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
print(location.coordinate)
}
}
}

Error creating a global CLLocationManager

Apple Docs suggest not to store your CLLocationManager in a local variable. So I created a global constant outside the scope of my ViewController class just after the import statements. Trying to access the constant inside the class, however, throws compiler errors:
A similarly declared globalDictionaryconstant of type NSMutableDictionary seems to be accessible inside the class.
What is it that I am doing wrong here? Why does the above not work?
Code:
//
// ViewController.swift
// CoreLocationExample
//
//
import UIKit
import CoreLocation
import Foundation
let locationManager = CLLocationManager()
let globalDictionary = NSMutableDictionary()
class ViewController: UIViewController, CLLocationManagerDelegate {
// let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let dict = [
"name":"John"
]
globalDictionary.addEntries(from: dict)
print(globalDictionary)
}
}
Using Swift 3 on Xcode Version 8.3.1
Apple Docs suggest not to store your CLLocationManager in a local variable.
It means do not create local instance inside a method / function.
please declare like this.
class AppDelegate: UIResponder, UIApplicationDelegate {
//CLLocation Manager
let locationManager = CLLocationManager()
var locValue = CLLocationCoordinate2D()
}
CLLocation Manager or globalDictionary Inside the class.
use singleton class for this
import UIKit
import CoreLocation
public class LocationManager: NSObject,CLLocationManagerDelegate {
public static let sharedInstance = LocationManager()
public lazy var locationManager: CLLocationManager = CLLocationManager()
var globalDictionary = NSMutableDictionary()
public override init() {
super.init()
self.locationManager.requestAlwaysAuthorization()
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.startUpdatingLocation()
self.locationManager.delegate = self
let dict = [
"name":"John"
]
self.globalDictionary.addEntries(from: dict)
print(self.globalDictionary)
}
// MARK: - Location Manager Delegate
public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error)
}
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]){
let newLocation: CLLocation? = locations.last
let locationAge: TimeInterval? = -(newLocation?.timestamp.timeIntervalSinceNow)!
if Double(locationAge!) > 5.0 {
return
}
if Double((newLocation?.horizontalAccuracy)!) < 0 {
return
}
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
}
}
You can do it in the following way -
class LocationTracker {
static var locationManager: CLLocationManager? = LocationTracker.sharedLocationManager()
class func sharedLocationManager() -> CLLocationManager {
let lockQueue = DispatchQueue(label: "self")
lockQueue.sync {
if _locationManager == nil {
_locationManager = CLLocationManager()
_locationManager?.desiredAccuracy = kCLLocationAccuracyBestForNavigation
_locationManager?.allowsBackgroundLocationUpdates = true
_locationManager?.pausesLocationUpdatesAutomatically = false
}
}
return _locationManager!
}
}
And when you need to call it in your code, you can do the below -
var locationManager: CLLocationManager? = LocationTracker.sharedLocationManager()
you can then add other Location related methods in this class as well like for startt tracking, update location, stoptracking etc.

I'm trying to find present location, But i'm not getting present location

I'm trying to find present location coordinates,but my program not calling didUpdateLocations method. And Also i add NSLocationWhenInUseUsageDescription in info.plist. Any help please (i'm using Version 7.2 (7C68)). I'm Testing simulator only.
import UIKit
import CoreLocation
import MapKit
class ViewController: UIViewController, CLLocationManagerDelegate {
var location: CLLocationManager!
override func viewDidLoad() {
let location = CLLocationManager()
location.delegate = self
location.desiredAccuracy = kCLLocationAccuracyBest
location.startUpdatingLocation()
location.requestWhenInUseAuthorization()
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let cord = locations[0] as CLLocation
let lati = cord.coordinate.latitude
let long = cord.coordinate.longitude
print(lati,"",long)
}
}

CLLocationManager doesn't change coordinates?

I have two different classes, one of them, LocationService, is just for determining location. Problem is that I don't know why it doesn't update coordinates variable.
ViewController:
import UIKit
class ViewController: UIViewController {
var coords: (lat: Double, long: Double) = (0,0)
var tracking = LocationServices()
override func viewDidLoad() {
super.viewDidLoad()
tracking.startTracking()
tracking.getLocations()
coordinat = tracking.coordinates
retreiveWeatherForecast()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// retrieveWeatherForecast functions
And simple locationService class:
import UIKit
import CoreLocation
class LocationServices: NSObject, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
var coordinates: (lat: Double, long: Double) = (0,0)
func startTracking() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
locationManager.stopUpdatingLocation()
print(error)
}
func getLocations() {
#if os (ios)
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
//println("locations = \(locationManager)")
var latValue = locationManager.location.coordinate.latitude
var lonValue = locationManager.location.coordinate.longitude
coordinates = (latValue,lonValue)
println(latValue)
println(lonValue)
}
#endif
}
}
When I build it, it returns weather with default coordinates = (0,0).
Well, I accidentally made it work. As far as I understand problem was here: func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) locations must be of CLLocation type, not AnyObject.
I'm using Swift 2.0.

CLLocation Manager in Swift to get Location of User

I am trying to convert an old app in ObjC to Swift as a practice exercise and have ran in to some issues. The way I had it in the old app, it was establishing the CLLocation Manager and then I would use:
manager = [[CLLocationManager alloc]init];
manager.delegate = self;
manager.desiredAccuracy = kCLLocationAccuracyBest;
[manager startUpdatingLocation]
which would call automatically:
-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{
}
and from there I could extract all the information I needed. But in swift, there is no autocompletion of this method and I cannot figure out how to reproduce it. The documentation says that
startUpdatingLocation()
will still be called by the delegate, but it isn't happening.
This is what I have so far:
import UIKit
import corelocation
class ViewController: UIViewController,CLLocationManagerDelegate{
#IBOutlet var gpsResult : UILabel
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
gpsResult.text = "success"
}
}
Any help or pointers on where to look would be appreciated. Thanks.
EDIT: Updated from Suggestions, but still not working
EDIT2: Seems to be some bug not allowing the method to work properly in the ViewController
You are missing two things. First, you have to ask for permission using requestAlwaysAuthorization or requestWhenInUseAuthorization(). So your viewDidLoad() should be like this:
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
Second, edit your Info.plist as indicated here.
First add this two line in plist file
NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription
Then this is class working complete implement this
import UIKit
import CoreLocation
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager!
var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
initLocationManager();
return true
}
// Location Manager helper stuff
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.locationServicesEnabled
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
// Location Manager Delegate stuff
// If failed
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
locationManager.stopUpdatingLocation()
if (error) {
if (seenError == false) {
seenError = true
print(error)
}
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
if (locationFixAchieved == false) {
locationFixAchieved = true
var locationArray = locations as NSArray
var locationObj = locationArray.lastObject as CLLocation
var coord = locationObj.coordinate
println(coord.latitude)
println(coord.longitude)
}
}
// authorization status
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
var shouldIAllow = false
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Restricted Access to location"
case CLAuthorizationStatus.Denied:
locationStatus = "User denied access to location"
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Status not determined"
default:
locationStatus = "Allowed to location Access"
shouldIAllow = true
}
NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
if (shouldIAllow == true) {
NSLog("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
NSLog("Denied access: \(locationStatus)")
}
}
}
I'm not sure why, but it seems like startUpdatingLocation isn't presenting the user prompt on the iOS 7 simulator, but when I enabled it manually it worked as expected if I used the newer form of the delegate method:
var manager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
manager = CLLocationManager()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) { // Updated to current array syntax [AnyObject] rather than AnyObject[]
println("locations = \(locations)")
}
The format you're using has been deprecated since iOS 5 or 6, so apparently it's not supported at all by the swift bridging layers.
had the same issue. didUpdateLocations - was not working. Run your app. Go to the Settings page -> Privacy -> Location and turn off Location Services. didFailWithError will catch the error about absent Location Services. Then turn it on. Since that moment didUpdateLocations will catch locations.
Here is my very simple code that works:
first add Core Location framework in General/Linked Frameworks and Libraries
then add following into Info.plist:
<key>NSLocationWhenInUseUsageDescription</key>
<string>blablabla</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>blablabla</string>
this is my ViewController.swift file:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locations = \(locations)")
}
}
For Swift 3
import UIKit
import CoreLocation
class ViewController: UIViewController,CLLocationManagerDelegate {
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locations = \(locations)")
}
}
I hope there are two ways.
var locationManager: CLLocationManager = CLLocationManager()
var initialLocation :CLLocation?
var updatedUserLocation :CLLocation?
override func viewDidLoad() {
super.viewDidLoad() {
//MapView Location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
}
Implementing CLLocationManagerDelegate :
//CLLocationManager Delegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// This only works when user location is updated.
gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
//Error indicates GPS permission restricted
gpsProviderStatusLabel.changeStatusToOff(gpsProviderStatusLabel)
//Initial Location
initialLocation = locations.first
//Getting Updated Location
updatedUserLocation = locations.last
}
Checking CLLocationDelegate Authorization:
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
//This method does real time status monitoring.
switch status {
case .NotDetermined:
print(".NotDetermined")
break
case .AuthorizedAlways:
print(".AuthorizedAlways")
gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
break
case .Denied:
print(".Denied")
gpsProviderStatusLabel.changeStatusToOff(gpsProviderStatusLabel)
break
case .AuthorizedWhenInUse:
print(".AuthorizedWhenInUse")
gpsProviderStatusLabel.changeStatusToOn(gpsProviderStatusLabel)
break
case .Restricted:
print(".Restricted")
break
default:
print("Unhandled authorization status")
break
}
}
Note: changeStatusToOn or changeStatusToOff is a UILabel Extenion method which makes the Label text On/Off with Green/Red Colors.
don't forget to add
NSLocationWhenInUseUsageDescription or
NSLocationAlwaysUsageDescription
in your configuration file (target/Info/custom iOS target properties
Add bellow 2 property in info.plist
NSLocationWhenInUseUsageDescription : Location information is used for fraud prevention
Privacy - Location Usage Description : Location information is used for fraud prevention
If you want to get the user location updated by default, without clicking 'Simulate location' everytime, go to
YourProject-->Build Phases-->Link Binary with libraries-->Add corelocation.framework
The location gets updated automatically/by default when you run the app in the simulator. Tested and works in Swift 2 !
This will ask for permission and track if given permission else quit with an alert. Stops tracking on back button press.
info.plist
<key>NSLocationAlwaysUsageDescription</key>
<string>Allow tracking while completing a survey</string>
Class:
import UIKit
import CoreLocation
class LocationViewController: BaseViewController, CLLocationManagerDelegate {
// MARK: Constants
private static let enableLocationServices = [
"title" : "Location",
"message" : "Enable location services",
"buttonTitle" : "OK"
]
// MARK: Private variables
private var manager: CLLocationManager?
// MARK: UIViewCOntroller methods
#IBAction func backButtonPressed(sender : UIButton) {
stopTracking()
detatchLocationManager()
dismissViewControllerAnimated(true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
attachLocationManager()
}
// Mark: Location
func locationManager(manager: CLLocationManager,
didChangeAuthorizationStatus status: CLAuthorizationStatus)
{
if status == .AuthorizedAlways {
manager.startUpdatingLocation()
} else if status != .NotDetermined {
showEnableLocationServicesAlert()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
getDependencyService().getProject().appendLocationTrackingFile(location.timestamp, latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
}
}
// MARK: LocationViewController
private func attachLocationManager() {
manager = CLLocationManager()
manager?.delegate = self
manager?.desiredAccuracy = kCLLocationAccuracyBest
if CLLocationManager.authorizationStatus() != .AuthorizedAlways {
manager?.requestAlwaysAuthorization()
} else if CLLocationManager.locationServicesEnabled() {
startTracking()
}
}
private func detatchLocationManager() {
manager?.stopUpdatingLocation()
manager?.delegate = nil
manager = nil
}
private func startTracking() {
manager?.startUpdatingLocation()
}
private func stopTracking() {
manager?.stopUpdatingLocation()
}
private func showEnableLocationServicesAlert() {
getDependencyService().getUiHelper().showAlert(FrogFirstSurveyViewController.enableLocationServices, completion: {
self.dismissViewControllerAnimated(true, completion: nil)
})
}
}
Swift:
Add following in
import CoreLocation
class YourViewController: UIViewController
{
var locationManager:CLLocationManager!
}
//MARK:- Location Manager
extension YourViewController: CLLocationManagerDelegate {
func stratLocationManager()
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.checkUsersLocationServicesAuthorization()
locationManager.startUpdatingLocation()
}
func checkUsersLocationServicesAuthorization(){
/// Check if user has authorized Total Plus to use Location Services
if CLLocationManager.locationServicesEnabled()
{
switch CLLocationManager.authorizationStatus()
{
case .notDetermined:
// Request when-in-use authorization initially
// This is the first and the ONLY time you will be able to ask the user for permission
self.locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
break
case .restricted, .denied:
// Disable location features
PrintLogs("Location Access Not Available")
break
case .authorizedWhenInUse, .authorizedAlways:
// Enable features that require location services here.
PrintLogs("Location Access Available")
break
}
}
}
func locationManager(_ manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locations = \(locations)")
}
}
Just call the init(vc : UIViewController).
import Foundation
import CoreLocation
import UIKit
class LocManager : NSObject{
var permission : ((Bool?)->())?
private var locationManager : CLLocationManager!
init(_ vc : UIViewController) {
super.init()
self.locationManager = CLLocationManager()
self.locationManager.delegate = vc as? CLLocationManagerDelegate
setUpLocationManagerDelegate()
}
}
extension LocManager : CLLocationManagerDelegate {
fileprivate func setUpLocationManagerDelegate(){
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lat = locations.last?.coordinate.latitude, let long = locations.last?.coordinate.longitude{
print("\n\nThe current Lat/Long Is Here\n\n")
let coordinates = CLLocationCoordinate2D(latitude: lat, longitude: long)
}else{
print("Unable To Access Locaion")
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
switch status {
case .authorizedAlways,.authorizedWhenInUse:
print("Good to go and use location")
locationManager.startUpdatingLocation()
self.callPermisssionCompletion(val: true)
case .denied:
print("DENIED to go and use location")
self.callPermisssionCompletion(val: false)
case .restricted:
print("DENIED to go and use location")
self.callPermisssionCompletion(val: nil)
case .notDetermined:
print("DENIED to go and use location")
self.callPermisssionCompletion(val: nil)
default:
print("Unable to read location :\(status)")
}
}
fileprivate func callPermisssionCompletion(val : Bool?){
guard let comp = self.permission else {
print("\n\n Unable to locate completions \n\n")
return
}
if let val = val{
comp(val)
}
}
}

Resources