gpt4 book ai didi

Swift:Corelocation 处理 didFailWithError 中的 NSError

转载 作者:行者123 更新时间:2023-11-28 09:04:03 27 4
gpt4 key购买 nike

我正在使用 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 中已经发展,但我被卡住了。

最佳答案

Swift 4 更新:错误现在作为 error: Error 传递给回调,可以转换为 CLError:

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
if let clErr = error as? CLError {
switch clErr.code {
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) { ... }

关于Swift:Corelocation 处理 didFailWithError 中的 NSError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31219025/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com