简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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