我正在学习如何使用新的 Swift 语言(只有 Swift,没有 Objective-C)。为此,我想用 map (MKMapView
) 做一个简单的 View 。我想查找并更新用户的位置(例如在 Apple map 应用中)。
我试过了,但什么也没发生:
import MapKit
import CoreLocation
class MapView : UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var map: MKMapView!
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
if (CLLocationManager.locationServicesEnabled())
{
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
}
}
你能帮帮我吗?
最佳答案
您必须覆盖 CLLocationManager.didUpdateLocations
(CLLocationManagerDelegate 的一部分)才能在位置管理器检索当前位置时得到通知:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.last{
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.map.setRegion(region, animated: true)
}
}
注意:如果您的目标是 iOS 8 或更高版本,您必须在 Info.plist 中包含 NSLocationAlwaysUsageDescription
或 NSLocationWhenInUseUsageDescription
键以使位置服务正常工作。
关于ios - 在 Swift 的 MKMapView 中显示当前位置和更新位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25449469/