CLLocationManager有时会返回(0,0)坐标

时间:2018-08-23 12:12:19

标签: ios iphone swift cllocationmanager

我正在使用CLLocationManager来获取用户坐标。然后,将其发送到我们的Web API以获取一些信息。但是最近,API开始返回由零坐标引起的错误。在错误报告中,我发现一小部分用户开始从CLLocationManager获取(0,0)坐标。关键是我们没有更改有关地理位置的任何信息。令我有些惊讶的是,到目前为止,该部件已经完美地工作了两年。

地理位置代码是标准的:

locationManager.requestWhenInUseAuthorization()

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
{
    //Started returning (0, 0) sometimes
}

我搜索了问题,但没有结果。有什么猜想吗?

2 个答案:

答案 0 :(得分:1)

嘿,我要检查一下准确度,有关该内容,请参阅Apple文档(@Discussion),该值可以指示您的位置是否有效

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    guard let location = locations.last, location.horizontalAccuracy >= 0 else {
        return

    }
}

Doku:

write your own components https://developer.apple.com/documentation/corelocation/cllocation/1423599-horizontalaccuracy

P.S .:我永远都不会访问带有“ locations [0]”之类的索引的位置,这往往会产生错误->像我一样保护最后一个位置,您应该会很好。

希望这会有所帮助。 (:

答案 1 :(得分:0)

嘿,@爱德华将此代码用于“位置”。添加还将密钥添加到info.plist

NSAppTransportSecurity, NSLocationAlwaysUsageDescription, NSLocationWhenInUseUsageDescription

//  AppDelegate.swift

 import UIKit


 @UIApplicationMain
 class AppDelegate: UIResponder, UIApplicationDelegate,CLLocationManagerDelegate {

var addressString : String!
var locationManager = CLLocationManager()
var lat : Double!
var long : Double!
var cordinates = CLLocationCoordinate2D()
var searchLocationCordinate = CLLocationCoordinate2D()
var currentLocation: CLLocation!


func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

locationManager.delegate = self
    locationManager.requestWhenInUseAuthorization()
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
    locationManager.startUpdatingLocation()

checkLocation()

}

 func checkLocation() {
    if CLLocationManager.authorizationStatus() != .authorizedWhenInUse
    {
        print("requestingautorization")
        locationManager.requestWhenInUseAuthorization()

    } else {
        print("startupdatinglocation")
    }
}




 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation:CLLocation = locations[0] as CLLocation
    cordinates = CLLocationCoordinate2D(latitude: userLocation.coordinate.latitude,longitude: userLocation.coordinate.longitude)
    print(cordinates)

}