2016-07-18 25 views
1

這是我簡單UIImageView擴展:無法從NSURL分配的UIImage因爲字符串編碼

extension UIImageView { 

    func setImageWithString(string: String?) { 

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

而對於下面的字符串,我不能內部條件得到:

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

我怎樣才能解決這個?

+0

您是否嘗試過用URL編碼率(stringByAddingPercentEscapesUsingEncoding)的東西嗎?看看這個以及http://stackoverflow.com/questions/26353388/stringbyaddingpercentescapesusingencodingnsutf8stringencoding-returns-optional – Miknash

+1

嘗試編碼您的網址,如:'let encodedPath = string.URLString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())' –

+0

@霍亞它的工作:) –

回答

3

不喜歡

func setImageWithString(stringbyName: String?) { 

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

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

或使用像

func setImageWithString(stringbyName: String?) { 

    let urlStr = stringbyName.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) 

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

更多的信息,請參閱本link

+0

@BartłomiejSemańczyk - 你可以更新一次plz –

+0

第二件作品,但不推薦使用...這是它的解決方法嗎? –

+1

@BartłomiejSemańczyk - 我添加第一個選擇的原因,我認爲你需要改變'URLQueryAllowedCharacterSet'或'URLHostAllowedCharacterSet'的類型,否則嘗試一旦你得到答案 –

相關問題