当前用户位置 swift

Present user location swift

我是 Swift 的新手,我想在地图上显示用户位置,我添加了 MKMapView,并添加了一个出口,这是我的代码:

import UIKit
import Foundation
import MapKit
import CoreLocation

class ViewController: UIViewController ,CLLocationManagerDelegate{

    @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)
        map.setRegion(region, animated: true)
        self.map.showsUserLocation = true
    }

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

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

但是当我 运行 模拟器上的应用程序时,它向我显示了美国的其他一些位置。但我来自另一个离美国不近的地方。

因为模拟器使用虚假位置进行测试。您还可以更改该位置,请参见图片 (https://i.stack.imgur.com/2GN7x.png)。 如果您 运行 在实际设备上,它会显示您的当前位置。

你的代码没问题,那是因为你运行它在模拟器上,select调试-->模拟位置-->选择其他位置,你会在屏幕上看到那个位置