我正在学习如何使用新的 Swift 语言(只有 Swift,没有 Objective-C)。为此,我想用地图做一个简单的视图(MKMapView
)。我想查找并更新用户的位置(就像在 Apple 地图应用程序中一样)。
我尝试了这个,但什么也没发生:
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 或更高版本,则必须包含NSLocationAlwaysUsageDescription
or NSLocationWhenInUseUsageDescription
键入您的 Info.plist 以使定位服务正常工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)