ios - 没有互联网连接的位置

标签 ios swift geolocation swift2

我想在按下按钮时获取用户的位置,我找到了一种使用 CLLocationManager 的方法,该代码可以完美运行,直到设备没有网络连接,函数 func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 捕获错误

((NSError?) error = domain: "kCLErrorDomain" - code: 2 { _userInfo = nil })

如何在没有互联网连接的情况下获取设备位置?这是我使用的代码

import CoreLocation

class SesionViewController: UIViewController, CLLocationManagerDelegate {

    let locationManager =  CLLocationManager()

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
            if (error != nil) {
                print("Error:" + error!.localizedDescription)
                return
            }
            if placemarks!.count > 0 {
                let pm = placemarks![0] as CLPlacemark
                print(pm!.coordinate.latitude)
            }else {
                print("Error with data")
            }

        })
    }
func startButtonPress(sender:UIButton!){
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.locationManager.stopUpdatingLocation()
    }
}

编辑

我已经找到了解决方案,我只是不执行 CLGeocoder().reverseGeocodeLocation... 只是像这样用 locations var 捕获位置

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    print(manager.location!.coordinate.latitude)
}

最佳答案

来自关于 ClGeocoder 的 Apple 文档

The computer or device must have access to the network in order for the geocoder object to return detailed placemark information

CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { (placemarks, error) -> Void in
            if (error != nil) {
                print("Error:" + error!.localizedDescription)
                return
            }
            if placemarks!.count > 0 {
                let pm = placemarks![0] as CLPlacemark
                print(pm!.coordinate.latitude)
            }else {
                print("Error with data")
            }

        })

在没有互联网访问的情况下总是会报告错误。您的位置数据仍然可用(如果您的设备有 GPS 装置)

关于ios - 没有互联网连接的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33960274/

相关文章:

swift - Swift 代码有没有办法检测它是否在 Playground 上运行?

ios - 使用 google place api 添加价格级别很困难

ios - 使用 webView 在 iOS 中集成 Instagram 失败

javascript - 显示给定半径内数据库中的所有位置

javascript - Phonegap 地理定位不适用于移动设备

iphone:安全的 restfull 服务器“此服务器的证书无效

ios - 为什么我收到错误 "cannot assign value of type (class) to type UICollectionViewDelegate, UICollectionViewDataSource?"

javascript - 将 javascript 变量存储到 HTML 文本框中

ios - 在 SKMapView 中导航路线而不跟随它

ios - 仅使用 UIWebview 打开网站是否允许 safari 访问..如何检查