0

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?

ArunGJ
  • 2,685
  • 21
  • 27

2 Answers2

0

Couple of possibilities here.

  1. The copiedURL is not being properly converted to a NSURL
  2. The NSURL is not being converted to 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.

Refer to: Loading/Downloading image from URL on Swift for how to properly download images.

Community
  • 1
  • 1
FredLoh
  • 1,804
  • 18
  • 27
0

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.

Ashish Verma
  • 1,776
  • 1
  • 16
  • 27