My simple map project does not show and shows my location in the simulator

I am using Xcode v7.2.1, Simulator v9.2.

I have a UIViewController that shows a map and should get my location and show it on the map:

import UIKit import MapKit class LocationVC: UIViewController, MKMapViewDelegate { @IBOutlet weak var map: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() map.delegate = self } override func viewDidAppear(animated: Bool) { if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { map.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } } 

I added NSLocationWhenInUseUsageDescription to NSLocationWhenInUseUsageDescription , as shown below:

enter image description here

I also selected Debug โ†’ Location โ†’ Custom Location ... and set the longitude and latitude of Helsinki, Finland, as shown below: enter image description here

When I launch my application, a map is displayed , but it does not get my location . What for? (I mean that I do not see the blue dot anywhere on the map).

===== UPDATE ====

I also tried this one when my application is running, however this does not help either.

+8
ios ios8 xcode7 ios-simulator mkmapview
source share
3 answers

you are asking for the location of the user, but actually doing nothing with the response. Become a location manager delegate and respond to authorization changes.

this code works for me on 7.2.1 (after selecting "Apple" in Debug -> Location):

 import UIKit import MapKit class ViewController: UIViewController, CLLocationManagerDelegate { @IBOutlet weak var map: MKMapView! let locationManager = CLLocationManager() override func viewDidLoad() { super.viewDidLoad() locationManager.delegate = self } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) if CLLocationManager.authorizationStatus() == .AuthorizedWhenInUse { map.showsUserLocation = true } else { locationManager.requestWhenInUseAuthorization() } } func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) { guard status == .AuthorizedWhenInUse else { print("not enabled"); return } map.showsUserLocation = true } } 
+7
source share

I agree with @Casey's answer, but sometimes you need to do a little more with the CLLocationManagerDelegate method.

 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let location = locations.first { //reset mapView center in case your custom location was wrong. map.centerCoordinate = location.coordinate //mannual call show annotations to avoid some bugs map.showAnnotations(map.annotations, animated: true) } } 
0
source share

you just need to add

 locationManager.delegate = self mapView.showsUserLocation = true 
0
source share

All Articles