【发布时间】:2020-09-08 17:54:08
【问题描述】:
我尝试在用户启动应用时获取坐标。
我在独立文件中设置了 locationManager 代码:
UserLocation.swift:
import Foundation
import CoreLocation
class UserLocation: NSObject, CLLocationManagerDelegate {
var userCurrentLocation: CLLocationCoordinate2D?
let locationManager = CLLocationManager()
func locationSetup() {
locationManager.requestWhenInUseAuthorization()
if CLLocationManager.authorizationStatus() != CLAuthorizationStatus.authorizedWhenInUse {
print("authorization error")
return
}
locationManager.distanceFilter = 300
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
print("startUpdatingLocation")
if CLLocationManager.locationServicesEnabled() {
print("locationServicesEnabled")
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print("locationManager getting start")
if let location = locations.last {
self.userCurrentLocation = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
print("print location in locationManager: \(String(describing: userCurrentLocation?.latitude))")
locationManager.stopUpdatingLocation()
}
}
func locationManager(_ manager: CLLocationManager, didFinishDeferredUpdatesWithError error: Error?) {
print(error?.localizedDescription as Any)
return
}
}
然后,我像这样调用 AppDelegate.swift 的application(_::didFinishLaunchingWithOptions:) 中的函数:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
let getUserLocation = UserLocation()
getUserLocation.locationSetup()
}
但是,只有成功调用locationSetup()函数,从未调用过相关函数locationManager(_::didUpdateLocations:)。 print("locationManager getting start") 我把第一行放在locationManager(_::didUpdateLocations:) 里,从来没有打印出来
顺便说一句,在 info.plist 中,我已经设置了 Privacy - Location When In Use Usage Description 。
谁能帮帮我?
【问题讨论】:
标签: ios swift cllocationmanager