如何在Swift 2.0中收到错误讯息? [英] How do I get the error message in Swift 2.0?

查看:108
本文介绍了如何在Swift 2.0中收到错误讯息?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Swift 1.2中非常使用这种方法: NSURLConnection.sendSynchronousRequest(:_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _),但在iOS9中显然不推荐使用。它仍然工作,但现在它使用新的Swift 2.0错误处理,我不知道如果我将收到错误消息,如果失败,例如。如果时间用完了。



我知道我必须把它放在一个捕捉中,然后说在metho之前尝试,但是我不知道如何捕获错误消息。

  do {
let data = try NSURLConnection.sendSynchronousRequest(request,returnsResponse:nil)
返回数据
}
catch _ {
return nil
}



<在我使用NSError之前,我使用了它的描述属性,但现在我没有任何线索。

解决方案

使用自动错误变量,您可以将它转换为 NSError 如果您愿意:

  catch {
let nsError = error as NSError
print(nsError.localizedDescription)
}
pre>

I used this method very much in Swift 1.2: NSURLConnection.sendSynchronousRequest(:_:_:_) but this is apparently deprecated in iOS9. It still works however but now it uses the new Swift 2.0 Error Handling and I don't know how I will get the error message if it fails, ex. if time runs out.

I know I have to put it into a do-catch and then say try before the metho but I dont know how to catch the error message.

do {
    let data = try NSURLConnection.sendSynchronousRequest(request, returningResponse: nil)
    return data 
}
catch _ {
    return nil
}

Before I used NSError and then its description property, but now I have no clue.

解决方案

Use automatic error variable, and you can cast it to NSError if you wish:

catch {
    let nsError = error as NSError
    print(nsError.localizedDescription)
}

这篇关于如何在Swift 2.0中收到错误讯息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆