Swift#3
If an image URL contains special character which doesn't load image on image view then we need to do more than UTF8 encoding. We usually decode string using Unicode methods but sometimes it is not sufficient to encode special character.
For an instance lets take below URL as an example here.
let imgURL = "http://www.example.fr/wp-content/uploads/2014/06/préliminaire.jpg"
Now, we will encode the image imgURL using basic String encoding.
let cString = imgURL.cString(using: String.Encoding.utf8)
let encodedStr = NSString(bytes: ((cString))!, length: ((cString?.count))!, encoding: String.Encoding.utf8.rawValue)!
Above code line will returns an encoded String but now we need String with the characters in Unicode General Category.
So we will use use below code to achieve it.
let controlCharStr = NSString(format: "%@", encodedStr.trimmingCharacters(in: CharacterSet.controlCharacters))
Now finally we need a character set containing the characters allowed in an URL's fragment component.
let urlStr = controlCharStr.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlFragmentAllowed)
Now you can finally load image on your image view. I' m using AFNetwork class to load image on image view.
yourImageView.af_setImage(withURL: URL.init(string: urlStr!)!)
Hope this will work for you. For any questions, please feel free to ask in comments.
Happy Coding !!!
0 Comment(s)