How to track set locationManager.delegate the right way? - ios

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)
}
}
}

Related

iOS - CLLocation Manager didUpdateLocations being called in one class but not another?

Hi I'm making a program that gets the users location and puts an according annotation on the map. I started by writing all of the code in the View Controller and it gets the location perfectly. Below is the working code in the view controller.
class MapViewController: UIViewController, CLLocationManagerDelegate {
var annotation = MKPointAnnotation()
var userLocation: CLLocation?
#IBOutlet weak var mapView: MKMapView!
var locationManager:CLLocationManager!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
annotation.coordinate = CLLocationCoordinate2D(latitude: (userLocation?.coordinate.latitude)!, longitude: (userLocation?.coordinate.longitude)!)
annotation.title = "You"
mapView.addAnnotation(annotation)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
However now when I try and recreate almost the exact same code in another swift file. didUpdateLocations never gets called. locationManager.startUpdatingLocation() does get called.
Below is my new swift file which I call from the View Controller. Is there any simple concept I'm missing here because I really don't see why this doesn't work.
import Foundation
import CoreLocation
class SendLocation: NSObject, CLLocationManagerDelegate {
var userLocation: CLLocation?
var locationManager:CLLocationManager!
func sendLocationPost() {
determineCurrentLocation()
}
func determineCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
print("WHY")
if CLLocationManager.locationServicesEnabled(){
locationManager.startUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
userLocation = locations[0] as CLLocation
print("user latitude = \(userLocation?.coordinate.latitude)")
print("user longitude = \(userLocation?.coordinate.longitude)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error \(error)")
}
}
I call it using :
let location = SendLocation()
location.sendLocationPost()`
in my View Controller
This happens because you are not keeping a reference to your SendLocation object.
Make SendLocation a property of your UIViewController.
For example, calling it from a static scope will not keep a reference.
WONT WORK:
static func sendLocation() {
let location = SendLocation()
location.sendLocationPost()
}
WILL WORK
let location = SendLocation()
func sendLocation() {
location.sendLocationPost()
}

iOS geolocation, Code works differently when initialization and declaration happen together

In iOS geolocation, the code works if the locationManager is declared and initialized separately, however it does not work if it is declared and initialized at the same time. Why is it so? The following is the working code sample:-
var locationManager : CLLocationManager!
func initLocManager() {
locationManager=CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.activityType = .automotiveNavigation
locationManager.distanceFilter = 10.0
}
func retrieveLocation(){
initLocManager()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
print("Long \(location.coordinate.longitude)")
print("Lati \(location.coordinate.latitude)")
}
}
whereas the following code does not work:-
var locationManager = CLLocationManager()
func initLocManager() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.activityType = .automotiveNavigation
locationManager.distanceFilter = 10.0
}
func retrieveLocation(){
initLocManager()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
print("Long \(location.coordinate.longitude)")
print("Lati \(location.coordinate.latitude)")
}
}
Another way:
Create new file with this code:
import UIKit
import CoreLocation
class LocationManager: CLLocationManager, CLLocationManagerDelegate {
static let shared = LocationManager()
public var currentLocation = CLLocation() {
didSet {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: LocationManager.LocationUpdatedNotification), object: self, userInfo: nil)
}
}
static let LocationUpdatedNotification: String = "LocationUpdate"
private override init() {
super.init()
self.delegate = self
self.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
self.activityType = .automotiveNavigation
self.distanceFilter = 10.0
self.requestAlwaysAuthorization()
self.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let lastLocation = locations.last {
currentLocation = lastLocation
}
}
}
In AppDelegate.swift
_ = LocationManager.shared // Add this line to func didFinishLaunchingWithOptions
Now you can get current user location using this code:
LocationManager.shared.currentLocation
Also you can subscribe for LocationUpdate notification anywhere in your project.

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)
}
}

Location manager didUpdateLocations not being called

For some reason didUpdateLocations is not being called, even when I set the delegate to the view controller. In info.plist I set the key Privacy - Location When In Use Usage Description to a description. So I'm not sure what I could be doing wrong?
import MapKit
import CoreLocation
class OptionsViewController: UIViewController, UITableViewDelegate, CLLocationManagerDelegate {
override func viewDidLoad() {
//Ask user for location
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
//Use users current location if no starting point set
if CLLocationManager.locationServicesEnabled() {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
override func viewDidAppear(_ animated: Bool) {
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error){
locationManager.stopUpdatingLocation()
print(error)
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("Did update location called?")
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
}
Problem is here:
override func viewDidAppear(_ animated: Bool) {
locationManager = CLLocationManager()
locationManager.requestWhenInUseAuthorization()
}
This method will be called after viewDidLoad, but you new created a locationManager later in viewDidAppear and not pointed its delegate to self. That's why the delegate(self)'s methods is not be called.
The improved but not the best way is:
class OptionsViewController: UIViewController, UITableViewDelegate, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
override func viewDidLoad() {
//Ask user for location
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//Use users current location if no starting point set
if CLLocationManager.locationServicesEnabled() {
if CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedWhenInUse
|| CLLocationManager.authorizationStatus() == CLAuthorizationStatus.authorizedAlways {
locationManager.startUpdatingLocation()
}
else{
locationManager.requestWhenInUseAuthorization()
}
}
else{
//Alert user to open location service, bra bra bra here...
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//... nothing need to do for location here
}
public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == CLAuthorizationStatus.authorizedWhenInUse
|| status == CLAuthorizationStatus.authorizedAlways {
locationManager.startUpdatingLocation()
}
else{
//other procedures when location service is not permitted.
}
}
//......
}

Shared instance of CLLocationManager

I was trying to create simple shared instance of CLLocationManager for my app.
There was no problem creating shared instance:
import UIKit
import CoreLocation
protocol LocationHandlerDelegate: class {
func locationHandlerDidUpdateLocation(location: CLLocation?)
func locationHandlerDidFailWithError(error: NSError)
}
class LocationHandler: NSObject, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
var location: CLLocation?
weak var delegate: LocationHandlerDelegate?
static let sharedInstance = LocationHandler()
override init() {
super.init()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
if CLLocationManager.authorizationStatus() == .NotDetermined {
locationManager.requestWhenInUseAuthorization()
}
}
// MARK: -
// MARK: - CLLocationManagerDelegate functions
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
delegate?.locationHandlerDidUpdateLocation(locations.last)
self.location = locations.last
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
delegate?.locationHandlerDidFailWithError(error)
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedAlways || status == .AuthorizedWhenInUse {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyKilometer
}
}
}
But for some reason when I call my shared instance from another class:
class TodayViewController: UIViewController, CLLocationManagerDelegate, LocationHandlerDelegate {
super.viewDidLoad() {
LocationHandler.sharedInstance.delegate = self
if #available(iOS 9.0, *) {
LocationHandler.sharedInstance.locationManager.requestLocation()
} else {
LocationHandler.sharedInstance.locationManager.startUpdatingLocation()
}
}
...
// MARK: - LocationHandlerDelegate function
func locationHandlerDidUpdateLocation(location: CLLocation?) {
if let location = location {
print("Current lcoation: \(location)")
}
else {
// ...
}
}
func locationHandlerDidFailWithError(error: NSError) {
print("Error finding lcoation: \(error.localizedDescription)")
}
}
None of CLLocationManagerDelegate functions in my LocationHandler are called.
But if in TodayViewController I write
LocationHandler.sharedInstance.locationManager.delegate = self
instead of
LocationHandler.sharedInstance.delegate = self
and I implement CLLocationManagerDelegate functions in my TodayViewController instead of LocationHandler then those delegate functions are called. So I guess there may be some problem with instancing? Or am I missing something else?

Resources