Swift 4,Xcode 9:获取并显示用户的位置

时间:2018-05-26 11:29:17

标签: ios swift mapkit

我正在尝试获取并显示用户的位置,但模拟器只会加载我所在的国家/地区。我设置了所需的info.plist部分(隐私 - 使用时的位置和始终),将Main.storyoard中的mapView链接到委托(控制拖动到View Controller Icon),附加IBOutlet(检查它以确保它已正确连接)并在viewController.swift中编写此代码:

import UIKit
import CoreLocation
import MapKit

class ViewController: UIViewController, CLLocationManagerDelegate {
    @IBOutlet weak var mapView: MKMapView!
    var locationManager = CLLocationManager()

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        mapView.mapType = MKMapType.standard
        let location = locations[0]
        let myLocation: CLLocationCoordinate2D = CLLocationCoordinate2DMake(location.coordinate.latitude, location.coordinate.longitude)
        let span = MKCoordinateSpanMake(0.05, 0.05)
        let region = MKCoordinateRegion(center: myLocation, span: span)
        mapView.setRegion(region, animated: true)
        self.mapView.showsUserLocation = true
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.requestWhenInUseAuthorization()

        if CLLocationManager.locationServicesEnabled() {
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }
    }

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

}

我刚刚用MapKit弄湿了这个问题,这个问题一直困扰着我。非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

请使用iPhone设备获取当前位置。在模拟器中,您必须设置位置然后获取该位置。因此可以使用该设备轻松完成此操作。您的代码将与真实设备一起使用。

如果您想使用模拟器进行测试,请按照https://medium.com/@abhimuralidharan/location-simulation-in-xcode-ff7db9042710

进行操作