Skip to content

Instantly share code, notes, and snippets.

@onurgenes
Created December 20, 2021 07:49
Show Gist options
  • Save onurgenes/8e339de3103712ac836b97f57421b5cc to your computer and use it in GitHub Desktop.
Save onurgenes/8e339de3103712ac836b97f57421b5cc to your computer and use it in GitHub Desktop.
//
// LocationManager.swift
// NotesOnEarth
//
// Created by Onur Geneş on 11.02.2020.
// Copyright © 2020 Onur Geneş. All rights reserved.
//
import UIKit
import CoreLocation
final class LocationManager: NSObject, Locatable {
weak var delegate: LocatableOutputProtocol?
var locationManager: CLLocationManager
override init() {
locationManager = CLLocationManager()
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidEnterBackgroundActive(_:)), name: UIApplication.didEnterBackgroundNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForegroundActive(_:)), name: UIApplication.willEnterForegroundNotification, object: nil)
if CLLocationManager.locationServicesEnabled() {
requestPermission()
locationManager.delegate = self
} else {
// TODO: Show user warning
}
}
func getCurrentLocation() {
locationManager.startUpdatingLocation()
}
func startTrackSignificantChanges() {
locationManager.startMonitoringSignificantLocationChanges()
}
func requestPermission() {
locationManager.requestAlwaysAuthorization()
}
@objc private func applicationDidEnterBackgroundActive (_ notification: Notification) {
self.locationManager.startMonitoringSignificantLocationChanges()
}
@objc private func applicationWillEnterForegroundActive (_ notification: Notification) {
self.locationManager.startUpdatingLocation()
}
}
extension LocationManager: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let coordinates = locations.first?.coordinate {
self.delegate?.didGetCurrentLocation(latitude: coordinates.latitude, longitude: coordinates.longitude)
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
self.delegate?.failedGetCurrentLocation(error: error)
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
print("status changed")
if (status == .authorizedAlways || status == .authorizedWhenInUse) {
print("we got permission")
locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 200
} else {
print("NO PERMISSION FOR LOCATION")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment