After checking how others try to do URL encoding in Cocoa (like How do I URL encode a string, Swift - encode URL, etc.) I still have no clue how to correctly URL encode in Cocoa if
- URLs come from externally therefore their structure (parts) not known ahead
- can be encoded or pure URL strings
- BONUS can be relative and local file URLs
- I do not want to encode blindly always all the characters but according to rfc3986 (rfc2396, rfc1738, rfc1808)
The catch 22:
stringByAddingPercentEscapesUsingEncoding:
converts lazily so the preferred method would be usingstringByAddingPercentEncodingWithAllowedCharacters:
for each url components one by one[NSURL URLWithString:]
,[NSURLComponents componentsWithString:]
and companions will fail if the incoming string is not (at least partially) encoded, but if I pass astringByAddingPercentEscapesUsingEncoding:
encoded string than the component splitting will fail (f.e. the encoded # will confuse the splitter and the fragment will be treated the part of a possible query section
How to URL encode correctly in this case without writing my own URL parser, encoder?