Cant get current location in iPhone X Swift - ios

I am trying to get my current location. My GPS is working and getting current location in all iOS devices expect iPhone X?
Why I am not getting current location in iPhone X only?
I am using iPhone X simulator for testing.Is it simulator bug or do I have to make any change in my code?
Here is my code.
Hope you understand my problem. Thanks in advance.
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Description</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>we want to know where you are!</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>we want to get your location</string>
extension NotificationCenterViewController : CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
locationManager.requestLocation()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation: CLLocation = locations[0]
locationManager.stopUpdatingLocation()
let latitude = userLocation.coordinate.latitude
let longitude = userLocation.coordinate.longitude
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
// Why I am getting this error in only in iPhone X only.
print("error:: (error)")
}
}

Did you call locationManager.startLocationUpdates() function anywhere in your code?
If not, then add this line where you have allocated location manager or called it in didChangeAuthorization when you get .authorizedWhenInUse status.
It is required to call locationManager.startLocationUpdates() to get location updated data.

I have same problem, but solution was very easy, delete your app from simulator iPhone X and rewrite again.

Related

Updating location to server every X minutes iOS

I am trying to update location from app to firebase after every X minutes ( any value less than 15mins is good).
I have enabled background mode for location and in following method I try to upload to Firestore document.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
problem is in log I can see this method was called but in background no data is uploaded to firestore. In fact I works just after the app has entered in background sometimes but not at all after that.
Is there any workaround for this ?
Use this code with Timer inside it to call update in Firestore:
write this code when starting your map call:
locationManager.startUpdatingLocation()
locationManager.delegate = self
Avoid calling untill you don't want to stop location updating:
locationManager.stopUpdatingLocation()
Conform Delegate method:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = manager.location else {
return
}
self.clLocation = location
//Firestore condition here
}
Check if you have set to true for allowsBackgroundLocationUpdates in your location Manager
locationManager?.allowsBackgroundLocationUpdates = true
Only if there is any update in location you will get the location updated in background. Also check if you have mentioned any distanceFilter in your location manager. If so, based on that only you will get the location update every X meters
locationManager?.distanceFilter = CLLocationDistance(X)
Use this code
locationManager.startUpdatingLocation()
locationManager.allowsBackgroundLocationUpdates = true
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.delegate = self
Don't stop location updates in following delegate method.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])

How do I track in the background in iOS a user walking and calculate the distance traveled so far using Swift and Xcode?

How do I track in the background in iOS a user walking in Apple MapKit or Google Maps Platform for iOS and calculate the distance traveled so far using Swift and Xcode?
I have tried using MapKit. The problem I get is that when the iOS device is locked, Core Location stops tracking the device. When the device is unlocked and the app comes to the foreground, Core Location starts tracking again and draws a straight line from the last point tracked to the point tracked when the app comes to the foreground, thus skipping all the time that the device is locked. If Google Maps Platform works better for this purpose, I am willing to use it.
Following is the relevant code:
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.allowsBackgroundLocationUpdates = true
if #available(iOS 11.0, *) {
locationManager.showsBackgroundLocationIndicator = true
}
let status = CLLocationManager.authorizationStatus()
if status == .authorizedAlways || status == .authorizedWhenInUse || status == .restricted {
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
} else {
locationManager.requestAlwaysAuthorization()
}
}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedAlways || status == .authorizedWhenInUse || status == .restricted {
locationManager.startUpdatingLocation()
locationManager.startMonitoringSignificantLocationChanges()
} else {
locationManager.requestAlwaysAuthorization()
}
}
Did you add in your .plist,
Privacy - Location Always and When In Use Usage Description and
Privacy - Location When In Use Usage Description?
Then as you are probably conforming CLLocationManagerDelegate in the method didUpdateLocations you should be able to perform your code.
My mistake was that I was creating the line with the user location from the map instead of the user location passed to the didUpdateLocations method. The userLocation property on the map does not update in the background, whereas the userLocation property of CLLocationManager does update in the background.
Here is the corrected code, with a comment on the line that I corrected:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("didUpdateLocations", locations)
if let userLocation = locations.first, polyline != nil {
let userLocationMapPoint = MKMapPoint(userLocation.coordinate)
let lastUserLocationMapPoint = MKMapPoint(route.last!)
totalDistance += userLocationMapPoint.distance(to: lastUserLocationMapPoint)
mapView.removeOverlay(polyline)
route.append(userLocation.coordinate) // changed from route.append(mapView.userLocation.coordinate)
polyline = MKPolyline(coordinates: route, count: route.count)
mapView.addOverlay(polyline)
}
print("latitude:", mapView.userLocation.coordinate.latitude, "longitude:", mapView.userLocation.coordinate.longitude)
}

locationManager deprecated in Swift 3?

I have downloaded the last version of XCode to test my project in iOs 10 Beta. When I have opened it, XCode asked me if I wanted to convert my project to Swift 3. After doing that, one error appeared :
Cannot override 'locationManager' which has been marked unavailable:
APIs deprecated as of iOS 7 and earlier are unavailable in Swift
And my code is the following :
func locationManager(_ manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
locationManager.stopUpdatingLocation()
currentUserLocation = newLocation
}
Is there another "not deprecated" function to achieve the same result ?
Thanks!
This method replaced the one you're using:
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation]) {
}
Find out more here.

Xcode 7.1 iOS 9.1 CLLocationManager not always working?

When implementing a CLLocationManager I came across a problem. Sometimes, when launching the app in the iPhone Simulator, it just doesn't fetch the current locations. But when I restart the app or it then suddenly works after 1-3 restarts. Restarting Xcode works too... Here's my code:
private var lat = 0.0;
private var long = 0.0;
private var didFindLocation = false
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if (status == .AuthorizedAlways) || (status == .AuthorizedWhenInUse) {
didFindLocation = false
locationManager.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last! as CLLocation
self.lat = location.coordinate.latitude
self.long = location.coordinate.longitude
if !didFindLocation {
print("\(self.lat) - \(self.long)")
didFindLocation = true
locationManager.stopUpdatingLocation()
}
}
As you can see, I've created a bool didFindLocation that allows me to fetch the location only once. I've put some breakpoints to see what's going on, and when the location doesn't get fetched, func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) doesn't even get called.
Thanks
iOS Simulator do not contains sensors like accelerometer, gyrometer etc, so we should not expect to work them on simulators. Besides this, for fetching a location, perhaps, it is using your system's internet.
So for a fair result it is advisable to use a real device for such cases.
From coding perspective, you can check for locationServicesEnabled property of CCLocationManager to see if this service is enabled or not.
This can happen on a simulator, but do add this method so that you get an error message of why it´s not working even though it´s on a simulator
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print(error.localizedDescription)
}
When you check location in simulator then first you need to point your simulator at some location.
Why?
Because simulator is not real time device first you need to point it at some position or location.
How you can do it?
There are two ways to do it.
1) select the simulator -> Goto debug -> select location -> select apple location.
Your location method called
Noto : if you select custom location from menu and enter your custom location then you need to restart your simulator (some time multiple times)
2) Goto xcode -> run your project -> in debug panel you find one location icon -> click on it -> it display location name -> select any place name
Note : Not necessary it worked all the times.

not able to reliably update location ios 8

I've recently gotten into mobile programming. The code below is finicky; sometimes it works and sometimes it doesn't. I've tried suggestions I've found on here like restarting location services on the virtual iphone. It is not a info.plist issue: I have NSLocationWhenInUseUsageDescription set, and when I'm debugging I can see it has WhenInUse authorization. When I debug I get to the println statement in didFailWithError and it reads "The operation couldn’t be completed. (kCLErrorDomain error 0.)". I've put the code behind a button to try it out. Is the reliability of this a known issue? If I load the app onto a device will it go away? Any thoughts appreciated. Thanks.
EDIT
This is in ViewController.swift in a single view template application.
let manager = CLLocationManager()
#IBAction func getMyLocation (sender : AnyObject){
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
let status = CLLocationManager.authorizationStatus()
if status == CLAuthorizationStatus.NotDetermined
{
manager.requestWhenInUseAuthorization()
}
manager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
println("locations = \(locations)")
manager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
println(error)
manager.stopUpdatingLocation()
}
I download the the app developer kit from Apple, and when I run the app with this script on my iphone the location is reliably retrieved. Looks like it's just an iOS simulator issue.

Resources