AlexanderHart AlexanderHart - 5 months ago 24
Swift Question

Can't Use String Variable in NSURL?

I have a variable

copiedURL
which contains a URL
string
, 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
copiedURL
has a value because I used
print()
to debug and everything printed just fine.

Also, I also tried:

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


but that didn't solve it.

Answer

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.