简体   繁体   English

NSData contentsOfURL返回Nil吗?

[英]NSData contentsOfURL Returns Nil?

I have the following code 我有以下代码

import Foundation

let url = NSURL(string: copiedURL)
let data = NSData(contentsOfURL: url!)
print("\(data)")
let image2 = UIImage(data: data!)

When I build and run, I get the following error fatal error: unexpectedly found nil while unwrapping an Optional value referring to 当我生成并运行时,出现以下错误fatal error: unexpectedly found nil while unwrapping an Optional value引用fatal error: unexpectedly found nil while unwrapping an Optional value

let image2 = UIImage(data: data!)

I tried to modify my Info.plist with the following 我试图用以下内容修改我的Info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

But the error is still there. 但是错误仍然存​​在。 Is there any more possible solutions I can try? 我可以尝试其他解决方案吗?

Couple of possibilities here. 这里有几种可能性。

  1. The copiedURL is not being properly converted to a NSURL 复制的网址未正确转换为NSURL
  2. The NSURL is not being converted to NSData 未将NSURL转换为NSData
  3. The image is unable to load the data 图像无法加载数据

Try the following: 请尝试以下操作:

if let url = NSURL(string: copiedURL) {
    print(url)
    if let data = NSData(contentsOfURL: url) {
        print(data)
        let image2 = UIImage(data: data)
    }
}

It's almost never a good idea to force unwrap something (!), instead use guard or if let to unwrap and thus be able to handle the nil condition. 强制解包(!),而是使用guardif let解包,从而能够处理nil条件,这几乎不是一个好主意。

Refer to: Loading/Downloading image from URL on Swift for how to properly download images. 有关如何正确下载图像的信息,请参阅: 从Swift上的URL加载/下载图像

Try the following code: 尝试以下代码:

if let url = NSURL(string: copiedURL) {
   if let data = NSData(contentsOfURL: url) {
   print("\(data)")
   let image2 = UIImage(data: data)
   }
}

If copiedURL has valid image you will get it, otherwise atleast your app will not crash. 如果copiedURL具有有效的图像,您将获得它,否则,您的应用程序将不会崩溃。

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

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