Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
Here is the scenario I have.
On App Start for the first time I need the users location, to fetch a list of places closest to them.
If they Allow location access, i then want to use their location to present the list of places to them.
I make a call to update the list in didUpdateLocation, but the list is always empty even after allowing access the first time. When I open the app the second time the location is available and I have the coordinates and can proceed with showing the list which works.
I have also tried running the code to populate the list in theses 2 delegate methods :
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus){
// switch statements then
fectchPlacesAndPopulateList()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
print("locationManager")
Utils.creatErrorMessage(title: "aaa", message: "aaaa", vc: self)
let userLocation:CLLocation = locations[0] as! CLLocation
let lng = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
let coordinates = "\(lat),\(lng)"
print("update locations = \(coordinates)")
fectchPlacesAndPopulateList()
}
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
}
}
The signature of didUpdateLocations is wrong for Swift 3, note the leading underscore, the (non-optional) type of the manager and the return type
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
Related
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])
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]
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.
Using the following code, my currentLat and currentLong are not updating beyond the first location. locations never has more than 1 item, and it's always exactly the same.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let loc: CLLocation = locations[locations.count - 1]
currentLat = loc.coordinate.latitude
currentLong = loc.coordinate.longitude
}
All the searching I've been doing has only shown how to get it to work if it doesn't work at all, but this DOES work, but only once.
The way I expect this to work is to continuously update the GPS coordinates and fire this delegate off whenever the location is updated. Does the location keep updating the entire time? I thought it would due to the terminology of "startUpdatingLocation()" and there being a "stopUpdatingLocation()." Am I trying to use this incorrectly?
Like I said, it works for the first time, so it's loaded and started just fine, the permissions are allowed, the info.plist has the necessary entries.
When you want to update your location, you should stop existing update once it got new location. You can use stopUpdatingLocation() in your didUpdateLocations: method to do so.
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// This should match your CLLocationManager()
locManager.stopUpdatingLocation()
let loc: CLLocation = locations[locations.count - 1]
currentLat = loc.coordinate.latitude
currentLong = loc.coordinate.longitude
}
Then call your locManager.startUpdatingLocation() when you need new location.
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.