Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
647 views
in Technique[技术] by (71.8m points)

ios8 - Swift: Corelocation handling NSError in didFailWithError

I'm using CoreLocation to successfully determine the user's location. However when i try to use the CLLocationManagerDelegate method:

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

I run into problems with the error term.

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

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

This results in a 'Use of unresolved identifier kCLErrorLocationUnknown' error message. I know that the kCLErrors are enums and that they have evolved in Swift but I'm stuck.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Update for Swift 4: The error is now passed to the callback as error: Error which can be cast to an 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)
    }
}

Older answer: The Core Location error codes are defined as

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
    // ...
}

and to compare the enumeration value with the integer err.code, toRaw() can be used:

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

Alternatively, you can create a CLError from the error code and check that for the possible values:

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")
}

UPDATE: In Xcode 6.1 beta 2, the fromRaw() and toRaw() methods have been replaced by an init?(rawValue:) initializer and a rawValue property, respectively:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...