Reputation: 3718
I have dictionary with String
's that are images url's. Compiler throws me an error "fatal error: unexpectedly found nil while unwrapping an Optional value" when I try to create NSURL
object from this String
s. I searched that problem and didn't find solution. Everybody said things like "your variable is nil". But my variable can't be nil and my code logs shows that too.
Here's my code:
var article: [String:String!]!
...
//viewDidLoad method
let imageURLString : String = article["image"]!
println(imageURLString) // log: http://domain.com/img/path.jpg
let imgURL : NSURL = NSURL.URLWithString(imageURLString) // error here
I receives "fatal error: unexpectedly found nil while unwrapping an Optional value"
Where is the problem? Hope somebody can help.
Upvotes: 0
Views: 3993
Reputation: 57168
NSURL's URLWithString can fail (and so return nil) if the URL is invalid. Try:
let imgURL: NSURL? = NSURL.URLWithString(imageURLString)
You can then test imgURL to see if it is nil or not before using it.
Upvotes: 7