I try to make a running app, and I want to use the method startMonitoringSignificantLocationChanges, but I'm missing something because is not firing the didUpdateLocations that the documentation says it should.
I have successfully used the startUpdatingLocation method of the CLLocationManager class and I can totally can use it for my interests, but I'd like to understand why my implementation doesn't work.
So, I have this code:
let locationManager = CLLocationManager()
func determineMyCurrentLocation() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.allowsBackgroundLocationUpdates = true
print("authorization Status: \(CLLocationManager.authorizationStatus().rawValue)")
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation() //(1)
//(2)locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 20
//locationManager.start
//locationManager.startUpdatingHeading)(
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { print("yaaay!") }
If you comment (1) and uncomment 2 the func locationManager...etc is never fired.
Also, I have my info.plist with the proper keys set, "Privacy - Location When In Use Usage Description" and "Privacy - Location Always and When In Use Usage Description").
Any idea?
Thanks in advance.
EDITED: My question was imprecise. I put the locationManager property as a class member and I completed the properties in my info.plist
The startMonitoringSignificantLocationChanges requires always authorisation. That also means you should turn on "Background Modes" in Capabilities section and selection "Location Updates". You also require the Privacy - Location Always Usage Description Try these two and you should receive significant location change updates.
Related
I am working on app where I need exact current location. The current location works fine when I am outdoors in iOS app. But when I am inside a building the current location is inaccurate. Its 100 meter away from my exact location.
The setting for location manager are as follows:
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = 100
locationManager.allowsBackgroundLocationUpdates = true
And I am calling this function for location updates:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
self.updatedLocation = location
}
The current location works fine on Android devices in buildings.
One thing that I have observed that when I open the Apple Maps and Google Maps app the current
location is the same as I am getting in my app but they have a light blue circle showing that you could be anywhere around that area.
Is there anyway I could improve the current location when I am inside a building?
Any help would be appreciated.
First image is screenshot from iOS where current location is inaccurate and the second image is screenshot from Android device where the location is precise.
I have noticed this problem as well, especially with find my iphone, when i'm in a building the location of my phone is always 50-100 m away i didn't know why.
Currently I'm working on an app that require the exact location, so one thing you can do is check the horizontalAccuracy property on the CLLocation that you're being returned. If this is above a certain threshold then you could throw away the result and wait for a more accurate one. If it is a number of miles out then I would expect the accuracy figure to be quite large. It's most likely using a cell site to determine location rather than GPS, and the margin of error would be much greater.
Here it is an example from my own application:
func requestUserLocation(){
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.distanceFilter = kCLDistanceFilterNone
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
Then on didUpdateLocations function I'll do the check
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
manager.desiredAccuracy = 1000 // 1km accuracy
if locations.last!.horizontalAccuracy > manager.desiredAccuracy {
// This location is inaccurate. Throw it away and wait for the next call to the delegate.
print("i don't want this location")
return;
}
// This is where you do something with your location that's accurate enough.
guard let userLocation = locations.last else {
print("error getting user location")
return
}
}
I am using CLLocationManager in my iOS app to get user's current location.
I also need to calculate the speed of the user and I got that, it can be calculated using the delegate method "didUpdateLocations".
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location: CLLocation = locations.last!
var speed1 = location.speed
speedLabel.text = "\(speed1)"
}
I can get the update of user's current location but the speed value is not correct. Initially the value of speed is -1 then no change in the value even the location is updating correctly.
The initialization of my location manager is below
var locationManager = CLLocationManager()
locationManager.delegate = self;
locationManager.distanceFilter = kCLLocationAccuracyNearestTenMeters;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
What's wrong with it.
Advanced thanks..
Usually, when dealing with external events and accessories (location, hardware communications etc.) Apple will give you a -1 when the information you want is not computable or is somehow invalid. You cannot make any assumptions, you simply need to intercept that information (computation error of some kind) and deal with it as if the information was missing.
A negative value indicates an invalid speed
https://developer.apple.com/documentation/corelocation/cllocation/1423798-speed
How do I get the current location of my iOS device?
It seems that Apple has made changes that to how get location and I could not find an up-to-date post. I answered this question myself below:
I couldn't find an up-to-date solution to getting the current location so here's how I did it.
My source is apple's sample code on location tracking and smart watch called PotLocCoreLocationwithiPhoneandAppleWatch: https://github.com/robovm/apple-ios-samples/tree/master/PotLocCoreLocationwithiPhoneandAppleWatch
Here's what you have to do in your app.
Note that everything from steps 2-6 are in this gist: https://gist.github.com/JonMercer/75b3f45cda16ee5d1e0955b2492f66dd
In the project settings in xcode, click on the capabilities tab (it's the tab beside the general tab where you put in your bundle identifier). Then turn on Background Mode and enable Location updates. EDIT thanks to #Rob: And also add NSLocationWhenInUseUsageDescription to your plist. The value can be anything you like
Inside your view controller, extend the CLLocationManagerDelegate
class YourClass: UIViewController, CLLocationManagerDelegate {
Implement these two functions
/**
Increases that location count by the number of locations received by the
manager. Updates the batch count with the added locations.
*/
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//use the "locations" variable here
}
/// Log any errors to the console.
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("Error occured: \(error.localizedDescription).")
}
Create a let manager = CLLocationManager() variable
On viewDidLoad() set the following: manager.requestWhenInUseAuthorization(), manager.allowsBackgroundLocationUpdates = true, and manager.startUpdatingLocation()
In order to stop tracking do the following: manager.stopUpdatingLocation() and manager.allowsBackgroundLocationUpdates = false
I'm having some issues with CLLocationManager. This code used to work on iOS 8.2 but since upgrading to 8.3 it doesn't work. Here is the code for setting up the location manager which is called on startup.
let distanceThreshold:CLLocationDistance = 100.0
var currentLocation:CLLocationCoordinate2D?
override init() {
assert(locMan == nil)
super.init()
locMan = self
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
currentLocation = manager.location.coordinate
if UIApplication.sharedApplication().applicationState == .Background {
PlacesManager.fetchNearbyPlaces(LocationManager.getLocationManager().currentLocation!, radius: distanceThreshold, callback: placesCallback)
}
}
With this code didUpdateLocations is never called despite it being called before.
I have added the relevant entries to the Info.plist file:
I have tried it on both a device and the simulator and neither works. In fact it seems that it is no longer requesting location authorisation anymore if I delete the app and reinstall.
I know I'm missing something stupid but I can't workout what the hell it is.
I'd appreciate any help people can provide.
Cheers,
Gerard
Answer from Anna:
The CLLocationManager documentation says: "To configure and use a CLLocationManager object to deliver events...Create an instance of the CLLocationManager class and store a strong reference to it somewhere in your app. Keeping a strong reference to the location manager object is required until all tasks involving that object are complete. Because most location manager tasks run asynchronously, storing your location manager in a local variable is insufficient."
In addition to the accepted answer, if you are using the simulator. You have to select a location after the app is running (Debug->Location->apple for apple headquarters). I set the location and assumed that the next time I ran the app that didUpdateLocations would be called with what I had set previously, but that assumption was wrong.
Here is my code from a ViewController implementing CLLocationManagerDelegate:
func startLocationManager() {
let locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
println("I'm called")
locationManager.requestAlwaysAuthorization()
// locationManager.startMonitoringSignificantLocationChanges()
locationManager.startUpdatingLocation()
let status = CLLocationManager.authorizationStatus()
println(status.rawValue) // This print 0 which stands for kCLAuthorizationStatusNotDetermined
println(CLLocationManager.locationServicesEnabled()) // true
}
func locationManager(manager: CLLocationManager!,
didUpdateLocations locations: [AnyObject]!) {
println("nobody call me ever, and I'm sad")
}
For some reason, I never get the prompt / alter to autorise location updates. I have tried on my device iOS 8.1 and the simulartor. I followed the advices found here: requestAlwaysAuthorization not showing permission alert :
"Add Core Location framework to Project Settings / Targets / Capabilities / Background Modes set "Location Updates" and "Uses Bluetooth LE Accessories" Add key at Info.plist NSLocationAlwaysUsageDescription".
I have also tried to clean up and rebuild, nothing change. I feel clueless.
EDIT: This question seems related: iOS: App is not asking user's permission while installing the app. getting kCLAuthorizationStatusNotDetermined every time - Objective-c & Swift but the selected answer and its article doesn't expose anything new
Your CLLocationManager object is local object and thus will be deallocated immediately after it falls out of scope. Make it a class property and then asynchronous processes like requesting authorization and determining the location will have a chance to run.