我正在尝试获取并显示用户的位置,但模拟器只会加载我所在的国家/地区。我设置了所需的 info.plist 部分(隐私 - 使用时的位置和始终),链接 Main.storyoard 中的 mapView到委托(控制拖动到视图控制器图标),附加 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 弄湿了我的脚,这个问题已经让我退缩了很长一段时间。将不胜感激任何帮助。
请使用 iPhone 设备获取当前位置。在模拟器中,您必须设置位置然后获取该位置。因此可以使用该设备轻松完成此操作。您的代码将适用于真实设备。
如果你想用模拟器测试它,请遵循https://medium.com/@abhimuralidharan/location-simulation-in-xcode-ff7db9042710
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句