Core Location not working in simulator Xcode 9.4.1 - ios

I have the following code:
import CoreLocation
class ViewController: UIViewController, NetworkingDelegate, CLLocationManagerDelegate {
let locationManager: CLLocationManager = CLLocationManager()
and then later:
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
and then I implement the delegate methods lower in the VC
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
for currentLocation in locations{
print("\(index)\(currentLocation)")
}
print("Did Location Delegate get called?")
let location: CLLocation = locations.first as! CLLocation
print(location)
self.lat = String(format: "%f", location.coordinate.latitude)
self.long = String(format: "%f", location.coordinate.longitude)
}
In build phases, "Link Binary With Libraries" has CoreLocation.framework selected.
The proper privacy in plist is present: Privacy - Location Usage Description as is Privacy - Location When In Use Usage Description.
The location is still not being gotten. I am using simulator in Xcode 9.4.1 targeting iOS 11. What am I missing here?

The problem is that func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) is years out of date. Update your code for modern Swift. Here's how the declaration should look:
https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager

Related

My Current Location Shows a Different Location, Google Maps - Xcode

I have implemented Google Maps but my Current Location is always USA. I am testing it on REAL device and i have location permissions added in info.plist. Google API key is also implemented in didFinishLaunchingWithOptions method of AppDelegate.
<key>NSLocationWhenInUseUsageDescription</key>
<string>By accessing your location, this app can help you navigate between different locations.</string>
Here is my code. I'm following this tutorial by raywenderlich.com. https://www.raywenderlich.com/7363101-google-maps-ios-sdk-tutorial-getting-started I have downloaded the material of this tutorial, used my API Key but still my current location is always USA. Tested on multiple real devices.
import UIKit
import GoogleMaps
import CoreLocation
class MapViewController: UIViewController {
#IBOutlet weak var mapView : GMSMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if CLLocationManager.locationServicesEnabled() {
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
locationManager.delegate = self
self.mapView.delegate = self
} else {
locationManager.requestWhenInUseAuthorization()
}
}
}
CLLocationManagerDelegate:-
extension MapViewController: CLLocationManagerDelegate {
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
guard status == .authorizedWhenInUse else { return }
locationManager.startUpdatingLocation()
self.mapView.isMyLocationEnabled = true
self.mapView.settings.myLocationButton = true
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
guard let location = locations.first else { return }
// the coordinates i get here are always from some city in USA.
mapView.camera = GMSCameraPosition(
target: location.coordinate,
zoom: 15,
bearing: 0,
viewingAngle: 0)
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error: \(error)")
}
}
Please check the settings below as screenshot :

fatal error: unexpectedly found nil while unwrapping an Optional value when getting Location?

I am developing an app using swift I want to fetch current location of the user and want to show in google map so I wrote my code in my class I have included all the functions and methods (i.e) added and imported frameworks core location and also updated plist but I can't able to fetch current location rotationally some time I get the location but some time it crashed.
Here is the code what I am tried.
import CoreLocation
class HomeViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
let location: CLLocation? = locationManager.location
let coordinate: CLLocationCoordinate2D? = location?.coordinate ----> App crossed this line then it will crashed
print(coordinate!)
print(coordinate!.latitude)
print(coordinate!.longitude)
strForCurLatitude = "\(coordinate!.latitude)"
strForCurLongitude = "\(coordinate!.longitude)"}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error while get location \(error)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.startUpdatingLocation()
let locationNew = locations.last
let coordinateNew: CLLocationCoordinate2D? = locationNew?.coordinate
strForCurLatitude = "\(coordinateNew!.latitude)"
strForCurLongitude = "\(coordinateNew!.longitude)"
strForLat=strForCurLatitude;
strForLong=strForCurLongitude;
print("User's Latitude is: \(Double(strForLat!)!)")
print("User's Longitude is: \(Double(strForLong!)!)")
self.locationManager.startUpdatingLocation()
}
Remove this from ViewDidLoad because you can not get location in viewDidLoad.
let location: CLLocation? = locationManager.location
let coordinate: CLLocationCoordinate2D? = location?.coordinate
print(coordinate!)
print(coordinate!.latitude)
print(coordinate!.longitude)
strForCurLatitude = "\(coordinate!.latitude)"
strForCurLongitude = "\(coordinate!.longitude)"
In CLLocationManager's following method best for getting location
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
}
make a reference to CLLocationManager as variable, like this:
class HomeViewController {
var locationManager = CLLocationManager()
viewDidLoad() {
super.viewDidLoad()
}
// rest of code
}
in this case Location Manager should works properly.

Swift 2 – Can't get user location with CLLocationManager

Here is my VC code:
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {
#IBOutlet weak var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
mapView.showsUserLocation = (status == .AuthorizedAlways)
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = manager.location!.coordinate
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
}
I have also added NSLocationWhenInUseUsageDescription in my plist file. And I have the CoreLocation and MapKit frameworks, any idea why this is not working? It doesn't show the user location on the map nor does it print out the user's coordinates. Haven't found anything online on on stack overflow.
This works for me
Swift 2 - (Xcode 7.2.1)
ViewController.swift
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
self.locationManager.stopUpdatingLocation()
let latestLocation = locations.last
let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)
print("Latitude: \(latitude)")
print("Longitude: \(longitude)")
}
}
info.plist
Add a new line
Information Property List: NSLocationWhenInUseUsageDescription
Type: String
Value: The application uses this information to show you your location
Try getting the location by getting the last object for the array locations in the method locationManager(_:,didUpdateLocations locations: [CLLocations]) .
Something like this:
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let locValue:CLLocationCoordinate2D = locations.last!
print("locations = \(locValue.latitude) \(locValue.longitude)")
}
you have to use these location access permission in your plist.
NSLocationAlwaysAndWhenInUseUsageDescription
NSLocationWhenInUseUsageDescription
you are not using always and in InUse permiossion
Note by Apple:
This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data

Current location is always at Cupertino in XCode 7 iOS

This following code is supposed to grab where I live and display it on the map. My current location however is always set to Cupertino California, I get how this is related to apple and xcode is supposed to be related to xcode HQ, however I am more inclined to test this in my current location, it is something to do with the simulator or perhaps my code? I am using no simulator as found in debug
class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate
{
#IBOutlet var mapView: MKMapView!
let locationManager = CLLocationManager()
override func viewDidLoad()
{
super.viewDidLoad()
self.locationManager.delegate = self
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.locationManager.requestWhenInUseAuthorization()
self.locationManager.startUpdatingLocation()
self.mapView.showsUserLocation = true
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
let location = locations.last
let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 1, longitudeDelta: 1))
self.mapView.setRegion(region, animated: true)
self.locationManager.stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
{
print("Errors: " + error.localizedDescription)
}
}
I don't think you can ask the simulator to use your real location, but you can simulate any location.
In the Debug menu of the simulator chose "Location" at the bottom. You can also do it from Xcode when you app is launched also in the Debug menu chose "Simulate Location".
In Xcode go to Product>Debug>SimulateLocation. There are some presets to choose from. You can also add your own custom GPX file to your project to make it more customizable.

Finding latitude and longitude in ios8

I want to find the latitude and longitude of location in ios8 and display it in the label. I have added the "NSLocationWhenInUseUsageDescription" property in info.plist. I have turned on the location settings for this particular app.But even then it is not updating the label.No logs are working too. My code is as follows:-
#IBAction func clicked(sender: UIButton) {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
let locat = locations[0] as! CLLocation
latitude.text = String(stringInterpolationSegment: locat.coordinate.latitude)
longitude.text = String(stringInterpolationSegment: locat.coordinate.longitude)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
Your locations:[AnyObject]! actually is an [CLLocation] just get its last object and use CLLocation's coordinate property.
Complete Solution
add CoreLocation.framework to BuildPhases -> Link Binary With Libraries
import CoreLocation to your class - probably ViewController.swift
add CLLocationManagerDelegate to your class decleration
Add NSLocationWhenInUseUsageDescription and NSLocationAlwaysUsageDescription to plist
init location manager:
locationManager = CLLocationManager()
locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
get User Location By:
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as! CLLocation
let long = userLocation.coordinate.longitude;
let lat = userLocation.coordinate.latitude;
//Do What ever you want with it
}
i.e Add in your plist file.,
NSLocationWhenInUseUsageDescription = Request permission to use location service when the apps is in background.
if you Are using Simulator then see you have to create one Location.GPX File To get Lat Long of Location.
Create new file Named As "Location.GPX"
-> Add your Static Lat Long for testing Purpose.
as given Below
<?xml version="1.0"?>
<gpx version="1.1" creator="Xcode">
<wpt lat="23.0271480" lon="72.5085160">
<name>Ahmedabad</name>
</wpt>
</gpx>
then
-> Go to Xcode -> Edit Scheme -> Select Location.GPX File and Rubn project Again..
One more thing to keep in mind along with solution given by Mehul is not toloose reference to your CLLocationManger() object.
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
It is asynchronus and if you loose reference to your lCLLocationManger() object then it won't get called and you will not get the location even after doing after everything right.

Resources