简体   繁体   English

如何在Swift中控制从NSData(contentsOfURL:url)返回的nil值?

[英]How to control a nil value returned from NSData(contentsOfURL: url) in Swift?

I want get data with a url in swift from php server. 我想从php服务器快速获取带有网址的数据。 But when i use NSData(contentsOfURL: url!) I get nil, and my app broke with error: 'fatal error: unexpectedly found nil while unwrapping an Optional value'. 但是,当我使用NSData(contentsOfURL:url!)时,得到零,并且我的应用程序因错误而中断:“致命错误:在展开可选值时意外发现零”。 This is because my server Service is Temporarily Unavailable 这是因为我的服务器服务暂时不可用

My code is: 我的代码是:

  let strURL: String = "http://domain.com/myphpfile.php?username="+userTF.text!+"&pass="+passTF.text!
    let url = NSURL(string: strURL)
    let dataURL = NSData(contentsOfURL: url!)  //Here return nil

How can I control when my link returning nil I show a message but my app not close? 如何控制我的链接何时返回nil我显示一条消息但我的应用程序未关闭?

Thanks! 谢谢!

Avoid using forced-unwrapped values with ! 避免与!一起使用强制展开的值! , safely unwrap with if let instead: ,安全地拆开包装if let改为:

if let url = NSURL(string: strURL), let data = NSData(contentsOfURL: url) {
    // use `data` here
} else {
    print("something went wrong")
}

Hint: don't use NSData contentsOfURL anyway, use something like NSURLSession instead. 提示:无论如何都不要使用NSData contentsOfURL ,而应使用NSURLSession东西。 This is because contentsOfURL blocks the main thread while working which freezes the UI and could result in the app being killed by iOS. 这是因为contentsOfURL在工作时会阻塞主线程,这会冻结UI,并可能导致该应用被iOS杀死。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM