Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ios URL(string: ) not working always

let testurl = "http://akns-
images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-
180129200032-1024.lupita-nyongo-angela-bassett-black-panther-
premiere.ct.012918.jpg?fit=inside|900:auto"

if let url = URL(string: testurl){
    print("valid")
}else {
   print("invalid")
}

This prints as an invalid URL. But shows the image in web browser. I have seen lot of methods but it throws Apple warning to use stringByAddingPercentEncodingWithAllowedCharacters and this doesn't work always.

I would prefer a solution to clean-up the url without encoding the complete urlstring. Encoding it at initial step can be a friction when passing to external libraries which will re-encode the url and make it invalid.

like image 772
Ankish Jain Avatar asked Feb 02 '18 05:02

Ankish Jain


1 Answers

Use URLComponents, it will handle escape characters automatically and encodes the url correct. no need to use addingPercentEncoding

func computeURL() {
    let testurlStr = "http://akns-images.eonline.com/eol_images/Entire_Site/2018029/rs_1024x759-180129200032-1024.lupita-nyongo-angela-bassett-black-panther-premiere.ct.012918.jpg?fit=inside|900:auto"
    let components = transformURLString(testurlStr)

    if let url = components?.url {
        print("valid")
    } else {
        print("invalid")
    }
}

func transformURLString(_ string: String) -> URLComponents? {
    guard let urlPath = string.components(separatedBy: "?").first else {
        return nil
    }
    var components = URLComponents(string: urlPath)
    if let queryString = string.components(separatedBy: "?").last {
        components?.queryItems = []
        let queryItems = queryString.components(separatedBy: "&")
        for queryItem in queryItems {
            guard let itemName = queryItem.components(separatedBy: "=").first,
                  let itemValue = queryItem.components(separatedBy: "=").last else {
                    continue
            }
            components?.queryItems?.append(URLQueryItem(name: itemName, value: itemValue))
        }
    }
    return components!
}
like image 172
thorb65 Avatar answered Sep 22 '22 20:09

thorb65