[英]Can't get user's current location
我的應用程序有一個簡單的目標,即獲取當前坐標,並使用它們在mapview上添加注釋。
我已經嘗試了很多來自google結果的解決方案,但是仍然無法正常工作...。
調試區域從不顯示“ locationManager did UpdateLocation”,即我在函數中打印的消息。
似乎該應用程序從未運行過“ did UpdateLocation”功能,甚至沒有調用過startUpdatingLocation()嗎?
在info.plist中添加位置隱私字符串:完成。
打開Mac Pro上的GPS:完成。
Xcode版本:10.1
MacOS:10.13.6(高山脈)
let cloaction = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
MapView.delegate = self
MapView.showsScale = true
MapView.showsPointsOfInterest = true
MapView.showsUserLocation = true
cloaction.requestAlwaysAuthorization()
cloaction.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled() {
print("IN")
cloaction.delegate = self
cloaction.desiredAccuracy = kCLLocationAccuracyBest
cloaction.startUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager did UpdateLocation")
let location = CLLocationCoordinate2D(latitude: (locations.first?.coordinate.latitude)!, longitude: (locations.first?.coordinate.longitude)!)
currentLat = (locations.first?.coordinate.latitude)!
currentLon = (locations.first?.coordinate.longitude)!
let span = MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01)
MapView.setRegion(MKCoordinateRegion(center: CLLocationCoordinate2DMake(currentLat,currentLon), span: span), animated: true)
MapView.showsUserLocation = true
print(locations.first?.coordinate.latitude)
print(locations.first?.coordinate.longitude)
}
您import CoreLocation
嗎?
首先創建一個變量, let myLocation = CLLocation()
您可以創建一個函數並在viewDidLoad中調用mLocation,而不是在viewDidLoad中擁有太多功能:
func mLocation(){
cloaction.delegate = self
cloaction.desiredAccuracy = kCLLocationAccuracyBest
cloaction.requestWhenInUseAuthorization()
if CLLocationManager.locationServicesEnabled(){
cloaction.startUpdatingLocation()
}
}
這就是您需要的所有clocation
LocationManager也可以更新
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations:[CLLocation]){
let newLocation = locations[0]
print("\(myLocation.coordinate.latitude)")
print("\(myLocation.coordinate.longitude)")
}
實際上,原因很簡單:僅在更改位置時才調用didUpdateLocation
方法。 您的Mac在特定位置且不會移動,因此這就是它無法正常工作的原因。
是! 最后...謝謝您的回答,這確實需要在設備上運行,感謝小川浩介的建議,以及每個人的指南,我是一個新的學習者,並且第一次在這里提出問題,這很有趣,謝謝大家。 (但如果答案是評論,我不知道如何接受答案?有人教我該怎么做?)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.