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.
Related
My App relies on checking user location upon start.
On iOS 16, when the user enables the Developer Mode on Privacy Settings they can simulate any location on the device using a GPX file.
The device actually changes the location of the device and most apps that I use actually think my location is the one on the GPX file.
Is there a way to make sure the location is the actual user location or a simulated one ?
Is there a public API to check if Developer Mode is enabled ?
Is there a way to tell the location comes from the GPX file ?
Even if the Developer mode is turned off it takes restarting the device to pick up the actual location again , so not sure if there is a different and better solution to this.
Thank you.
Apple provides sourceInformation on each CLLocation object returned. Checking the isSimulatedBySoftware parameter will give a boolean response.
Core Location sets isSimulatedBySoftware to true if the system generated the location using on-device software simulation. You can simulate locations by loading GPX files using the Xcode debugger. The default value is false.
The code below is a full functioning example that will turn the screen red if a simulated location is detected. I have confirmed that toggling simulated locations on/off in Xcode will make the screen turn from green to red and back again.
import UIKit
import CoreLocation
class ViewController: UIViewController {
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// setup location monitoring
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// list of locations that are simulated
let simulatedLocations = locations.filter { $0.sourceInformation?.isSimulatedBySoftware == true }
view.backgroundColor = simulatedLocations.count > 0 ? .red : .green
}
func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
guard manager.authorizationStatus == .authorizedAlways || manager.authorizationStatus == .authorizedWhenInUse else { return }
locationManager.startUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}
}
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.
Yeah ! My CoreLocation working now ! So i have a problem to store latitude and longitude and stopping locating.
I have a Sign In page (my MainVC)
before user sign in i need to get and store current device location and stop locating (now it's working with help of Alexander see under).
in my MainVC.swift i have this 2 global variables
var locationManager:CLLocationManager!
var myLocations = [CLLocation]()
in my viewDidLoad() i have this :
//Setup our Location Manager
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
For operate locationManager i have this 2 functions :
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locations = \(locations)")
errorMsgIfInternetNotAvailable.text = "GPS success"
myLocations.append(locations.last!)
locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
errorMsgIfInternetNotAvailable.text = "Error while updating location " + error.localizedDescription
}
When i build my app, all working, if not autorise my device to get GPS informations i have the locationManager function error working.
If i autorise it
in console, the location update every second and don't stop it with the .stopUpdatingLocation() command
First, it is always good to provide the build error output. It's hard enough to guess which error you're getting.
It seems like you defined, but not initialized myLocations property. You have to do it like this:
var myLocations = [CLLocation]()
Notice the brackets () in initialization.
And then you have to add object to your array:
myLocations.append(locations.last)
or, if you want to store only one object in your array, do it like:
myLocations = [locations.last]
my viewController looks like following
import CoreLocation
class MyViewController: UIViewController {
let locationManager = CLLocationManager()
override func viewDidAppear(animated: Bool) {
if #available(iOS 8.0, *) {
self.locationManager.requestWhenInUseAuthorization()
} else {
// Fallback on earlier versions
}
if (CLLocationManager.locationServicesEnabled()) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
let lon = locationManager.location!.coordinate.longitude
let lat = locationManager.location!.coordinate.latitude
print("lat = \(lat) and long = \(lon)")
}
}
}
// MARK: - CLLocationManagerDelegate
extension MyViewController : CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
print("\(error.localizedDescription)")
}
}
When I execute my program, it prompts a message like
Allow application to access your location while you use the app?
But the Don't Allow and Allow buttons are disabled.
Can someone guide me on where I am going wrong and what I should be doing.
I can manually allow my application to access location services by going to settings. But I would like to know why the buttons are disabled and what should I do to enable it.
note: I have added NSLocationWhenInUseUsageDescription to my info.plist file.
Thanks.
Dt: 29Oct2015
EDIT:
Uninstalled the app and installed again and tried. Now I am able to access the buttons.
Also, I noticed that sometimes the screen goes unresponsive i.e., screen cannot take any input from user. I noticed it today with a textbox. I am not able to get the cursor to the text box.
Is it something to do with IOS update? is anyone else experiencing this type of weird behaviour. Is there any workaround for the same?
Any help is highly appreciated.
Thanks.
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.