Bartłomiej Semańczyk Bartłomiej Semańczyk - 4 months ago 14
Swift Question

Cannot assign UIImage from NSURL because of string encoding

This is my simple

UIImageView
extension:

extension UIImageView {

func setImageWithString(string: String?) {

if let string = string, let url = NSURL(string: string) {
sd_setImageWithURL(url)
}
}
}


And for the following string I cannot get inside condition:

"http://posbistro-prod.s3.amazonaws.com/location_images/images/116/2fa/ad-/medium/Bez tytułu.jpg"


How can I workaround this?

Answer

do like

func setImageWithString(stringbyName: String?) {

     let urlStr = stringbyName.stringByAddingPercentEncodingWithAllowedCharacters(. URLQueryAllowedCharacterSet())

    if let  url = NSURL(string: urlStr) {
        sd_setImageWithURL(url)
    }
}

or use like

   func setImageWithString(stringbyName: String?) {

     let urlStr = stringbyName.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)

    if let  url = NSURL(string: urlStr) {
        sd_setImageWithURL(url)
    }
}

for additional information see this link