Search code examples
swifturljpegnsurlxcode11

if let url = URL(string:"") always getting fail for .JPEG images


if let url = URL(string: "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"){} 

is always getting fail when the file extension is .jpeg . i have tried with .png it works fine only . URL(string:) is not giving url object when extension is .jpeg. please help.


Solution

  • You need to encode the urlString to handle the whitespaces. Use addingPercentEncoding(withAllowedCharacters:) method on the urlString, i.e.

    let str = "https://omsoftware.org/sorora/public/profile_images/kapil borkar_199.jpeg"
    
    if let urlString = str.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let url = URL(string: urlString) {
        //add your code here...
    }
    

    addingPercentEncoding(withAllowedCharacters:)

    Returns a new string made from the receiver by replacing all characters not in the specified set with percent-encoded characters.

    Refer this to know more about addingPercentEncoding(withAllowedCharacters:) method.