Fred Lawrence Fred Lawrence -4 years ago 72
Swift Question

User location won't come up in simulator in Xcode

I'm new to app development and I'm trying to get the user location to come up in the simulator but I keep getting the Use of unresolved identifier error. I have looked at other questions, which are very specific to their own projects, and have tried to approach my own app in a similar way but to not avail. Any help, por favor? Here's my code, and a link to a screenshot of Xcode.

import UIKit
import MapKit
import CoreLocation

class SecondViewController: UIViewController, CLLocationManagerDelegate {

//Map
@IBOutlet weak var map: MKMapView!

let manager = CLLocationManager()
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{ let location = locations[0]

let span:MKCoordinateSpan = MKCoordinateSpanMake(0.01, 0.01)

let myLocation:CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)

let region:MKCoordinateRegion = MKCoordinateRegionMake(myLocation, span)


self.map.showsUserLocation = true

}

override func viewDidLoad()
{
super.viewDidLoad()
manager.delegate = self
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.requestWhenInUseAuthorization()
manager.startUpdatingLocation()

//This is where I get an error
map.setRegion(region, animated: true)**
}



Error: Use of unresolved identifier



screenshot

Answer Source

Your let region:MKCoordinateRegion is a local identifier inside your delegate method:

func locationManager(_:didUpdateLocations) {...}

This is why you are getting Use of unresolved identifier. Make this identifier accessible throughout the class, the error will be gone. Like:

class SecondViewController: UIViewController, CLLocationManagerDelegate {

    //Map
    @IBOutlet weak var map: MKMapView!
    var region = MKCoordinateRegion()
    .......
    .......
}

N.B: But this won't let you see anything in the map. Best way to see any output from your MapView is to put map.setRegion(region, animated: true) inside your delegate method:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations.first
    let span = MKCoordinateSpanMake(0.01, 0.01)
    let myLocation = CLLocationCoordinate2DMake((location?.coordinate.latitude)!, (location?.coordinate.longitude)!)
    region = MKCoordinateRegionMake(myLocation, span)
    map.setRegion(region, animated: true)
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download