Search code examples
iosswiftnsdata

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

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?


Solution

  • 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.