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
let image2 = UIImage(data: data!)
I tried to modify my Info.plist
with the following
<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.
Refer to: Loading/Downloading image from URL on Swift for how to properly download images.