[英]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. 这里有几种可能性。
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. 强制解包(!),而是使用
guard
或if 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.