Wimal Weerawansa
Wimal Weerawansa

Reputation: 157

Swift unwrapping optional giving error with data

My iOS application fetch data from server and render some images from that data using 'Kingfisher', the problem is whenever i add or replace new image on server application crashes due to this code below with error : "fatal error: unexpectedly found nil while unwrapping an Optional value"

let prfix:String = "MY_PREFIX_URL /\(org.image)"
celImage.kf_setImageWithURL((NSURL(string: prfix))!)

Please check the sceeenshot for more detailerror screenshot I don't undestand why I am getting this error, because you can see prfix got a value.

Upvotes: 0

Views: 130

Answers (2)

Kamaal ABOOTHALIB
Kamaal ABOOTHALIB

Reputation: 3548

I think its due to prefix contain with unnecessary characters, you can fix this with URLHostAllowedCharacterSet

You can fix prefix malformed url like this (swift 2.x).

let urlStr : NSString = prfix.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!

celImage.kf_setImageWithURL((NSURL(string: urlStr as String))!)

this will make sure the url contains only good string.

Upvotes: 1

Artheyn
Artheyn

Reputation: 1180

NSURL(string:) is a failable initialiser and can then return nil if your string parameter is not a valid URL, as you can read in the documentation of NSURL:

Initialize a NSURLComponents with a URL string. If the URLString is malformed, nil is returned.

You have to check your final URL integrity because apparently it is malformed...

Upvotes: 0

Related Questions