【发布时间】:2017-05-08 11:32:37
【问题描述】:
我正在使用 swift 开发一个应用程序我想获取用户的当前位置并希望在谷歌地图中显示所以我在我的课程中编写了我的代码我已经包含了所有的函数和方法(即添加和导入的框架核心)位置和更新的 plist,但有时我无法获取当前位置,但有时它会崩溃。
这是我尝试过的代码。
import CoreLocation
class HomeViewController: UIViewController, CLLocationManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.startUpdatingLocation()
let location: CLLocation? = locationManager.location
let coordinate: CLLocationCoordinate2D? = location?.coordinate ----> App crossed this line then it will crashed
print(coordinate!)
print(coordinate!.latitude)
print(coordinate!.longitude)
strForCurLatitude = "\(coordinate!.latitude)"
strForCurLongitude = "\(coordinate!.longitude)"}
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
if status == .authorizedWhenInUse {
print("User allowed us to access location")
}
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print("Error while get location \(error)")
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
locationManager.startUpdatingLocation()
let locationNew = locations.last
let coordinateNew: CLLocationCoordinate2D? = locationNew?.coordinate
strForCurLatitude = "\(coordinateNew!.latitude)"
strForCurLongitude = "\(coordinateNew!.longitude)"
strForLat=strForCurLatitude;
strForLong=strForCurLongitude;
print("User's Latitude is: \(Double(strForLat!)!)")
print("User's Longitude is: \(Double(strForLong!)!)")
self.locationManager.startUpdatingLocation()
}
【问题讨论】:
-
locationManager需要时间来更新位置,如果你在viewDidLoad尝试,那么你怎么能得到它?,在didUpdateLocations你得到当前位置 -
不要尝试在 viewDidLoad 方法中获取位置。他们已经给出了 didUpadteLocation 委托方法
-
那么请告诉我在哪里。
-
使用
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { -
好的,谢谢,我会试试这个。