我正在学习如何使用新的Swift语言(只有Swift,没有Objective-C)。为此,我想用 map(MKMapView
)做一个简单的视图。我想查找并更新用户的位置(例如在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
键,才能使定位服务正常工作。
感谢您的回答Zisoft。但是,要使用该功能,我必须将所有新位置“保存”在一种列表中?然后,是否
startUpdatingLocation()
足以更新位置?注意:呃...抱歉,但是我该怎么办?:s非常感谢!调用
startUpdatingLocation
一次后,didUpdateLocations
每次检测到位置更改都会被触发。您可以对位置进行任何操作,即将其存储在数组中以在地图视图上绘制路径。好,谢谢。以及如何将
NSLocationAlwaysUsageDescription
密钥包含在我的Info.plist中?在XCode中,单击Info.plist并添加新行。使用
NSLocationAlwaysUsageDescription
的关键和价值,你想要的文字呈现给用户(字符串)。好的谢谢 !没有价值吗?