Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

My simple map project doesn't get & show my location in simulator

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

I have a UIViewController which shows a map & is supposed to get my location & show it on 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 have added the NSLocationWhenInUseUsageDescription in info.plist as shown below:

enter image description here

I have also selected the Debug -> Location -> Custom Location ... and set the longitude & latitude of Helsinki, Finland as shown below: enter image description here

When I run my app, the map is shown, however it doesn't get my location. Why? (I mean I don't see the blue point in anywhere of the map).

===== UPDATE ====

I also tried this when my app is running, however it doesn't help either.

like image 644
Leem.fin Avatar asked Mar 27 '16 17:03

Leem.fin


Video Answer


1 Answers

you are requesting the user's location, but not actually doing anything with the response. become the delegate of the location manager and respond to the authorization change.

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
    }
}
like image 153
Casey Avatar answered Oct 10 '22 23:10

Casey