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.
URL encoding is compulsory for building a URL from a string in case it contains special characters.
Why we need URL encoding
From this answer:
In the IOS SDK we have the following:
User:
URLUserAllowedCharacterSet
Password:
URLPasswordAllowedCharacterSet
Host:
URLHostAllowedCharacterSet
Path:
URLPathAllowedCharacterSet
Fragment:
URLFragmentAllowedCharacterSet
Query:
URLQueryAllowedCharacterSet
You can use
addingPercentEncoding(withAllowedCharacters:)
to encode a string correctly.One important note according to the apple docs for that method:
An example:
I hope this is helpful.
I think I have found my answer. Still will be checking for any side effects, comments are welcome:
This does not encode the complete URL but encodes only the invalid query characters (in eg url its '|'). Thus it can still be passed around as a string or a valid URL.
Please replace your line with:
Use
URLComponents
, it will handle escape characters automatically and encodes the url correct. no need to useaddingPercentEncoding