I am new to swift . I am trying to show user location with Pin . I added the permission in Info Plist to allow the user access . I am using the storyboard and I tried to edit the schema also added the default location but it did not fixed the problem . I am using CLLocationManagerDelegate with MapKit.
Here is my code for view controller ..
import UIKit
import MapKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet var mapView: MKMapView!
let manager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
manager.desiredAccuracy = kCLLocationAccuracyBest
manager.delegate = self
manager.requestWhenInUseAuthorization()
manager.stopUpdatingLocation()
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
manager.stopUpdatingLocation()
render(location)
}
}
func render(_ location: CLLocation) {
let coordinate = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let span = MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1)
let region = MKCoordinateRegion(center: coordinate, span: span)
mapView.setRegion(region, animated: true)
let pin = MKPointAnnotation()
pin.coordinate = coordinate
mapView.addAnnotation(pin)
}
}
Here is the screenshot of Info Plist
2
Answers
Try this way:
conform your ViewController class to CLLocationManagerDelegate and MKMapViewDelegate, declare your objects:
in viewDidLoad present mapView and add constraints:
in viewDidAppear call requestAlwaysAuthorization and requestWhenInUseAuthorization and map configuration
After that set didUpdateLocations
my info.plist Privacy authorizations
The result, I set Tokyo on my simulator options scheme
intere code with your DispatchQueue request in comments below: