Swift:在didFailWithError中处理NSError的Corelocation

时间:2014-07-01 11:52:34

标签: swift ios8 nserror didfailwitherror

我正在使用CoreLocation成功确定用户的位置。但是当我尝试使用CLLocationManagerDelegate方法时:

func locationManager(_ manager: CLLocationManager!, didFailWithError error: NSError!)

我遇到了错误术语的问题。

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    println("didFailWithError \(error)")

    if let err = error {
        if err.code == kCLErrorLocationUnknown {
            return
        }
    }
}

这会导致“使用未解析的标识符kCLErrorLocationUnknown”错误消息。我知道kCLErrors是枚举,并且它们已经在Swift中进化但我被卡住了。

3 个答案:

答案 0 :(得分:30)

Swift 4的更新:错误现在作为error: Error传递给回调,可以投放到CLError

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    if let clErr = error as? CLError {
        switch clErr {
        case CLError.locationUnknown:
            print("location unknown")
        case CLError.denied:
            print("denied")
        default:
            print("other Core Location error")
        }
    } else {
        print("other error:", error.localizedDescription)
    }
}

旧答案:核心位置错误代码定义为

enum CLError : Int {
    case LocationUnknown // location is currently unknown, but CL will keep trying
    case Denied // Access to location or ranging has been denied by the user
    // ...
}

并将枚举值与整数err.code进行比较,toRaw() 可以使用:

if err.code == CLError.LocationUnknown.toRaw() { ...

或者,您可以从错误代码中创建CLError并进行检查 对于可能的值:

if let clErr = CLError.fromRaw(err.code) {
    switch clErr {
    case .LocationUnknown:
        println("location unknown")
    case .Denied:
        println("denied")
    default:
        println("unknown Core Location error")
    }
} else {
    println("other error")
}

更新:在Xcode 6.1 beta 2中,已fromRaw()toRaw()方法 分别由init?(rawValue:)初始值设定项和rawValue属性替换:

if err.code == CLError.LocationUnknown.rawValue { ... }

if let clErr = CLError(rawValue: code) { ... }

答案 1 :(得分:7)

现在在Swift 3中:

cts:frequency()

答案 2 :(得分:1)

Swift 4.1:

func locationManager(_: CLLocationManager, didFailWithError error: Error) {
    let err = CLError.Code(rawValue: (error as NSError).code)!
    switch err {
    case .locationUnknown:
        break
    default:
        print(err)
    }
}