AlexanderHart AlexanderHart - 1 year ago 73
Swift Question

Can't Use String Variable in NSURL?

I have a variable

which contains a URL
, I am trying to use that string variable to display an image programmatically

let url = NSURL(string: copiedURL)
let data = NSData(contentsOfURL: url!)
let image2 = UIImage(data: data!)

When I build and run I get a EXC_BAD_INSTRUCTION error
fatal error: unexpectedly found nil while unwrapping an Optional value

I am certain that
has a value because I used
to debug and everything printed just fine.

Also, I also tried:

let url = NSURL(string: "\(copiedURL)")

but that didn't solve it.

Answer Source

NSURL(string:) is a failable initializer. In the case that the URL isn't valid, it will not initialize a new NSURL instance, but will instead return nil.

Check that your copiedURL is a valid URL.