I was using this, in Swift 1.2
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
This now gives me a warning asking me to use
stringByAddingPercentEncodingWithAllowedCharacters
I need to use a NSCharacterSet as an argument, but there are so many and I cannot determine what one will give me the same outcome as the previously used method.
An example URL I want to use will be like this
http://www.mapquestapi.com/geocoding/v1/batch?key=YOUR_KEY_HERE&callback=renderBatch&location=Pottsville,PA&location=Red Lion&location=19036&location=1090 N Charlotte St, Lancaster, PA
The URL Character Set for encoding seems to contain sets the trim my URL. i.e,
The path component of a URL is the component immediately following the host component (if present). It ends wherever the query or fragment component begins. For example, in the URL http://www.example.com/index.php?key1=value1, the path component is /index.php.
However I don't want to trim any aspect of it.
When I used my String, for example myurlstring
it would fail.
But when used the following, then there were no issues. It encoded the string with some magic and I could get my URL data.
let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
As it
Returns a representation of the String using a given encoding to determine the percent escapes necessary to convert the String into a legal URL string
Thanks
In Swift 3.1, I am using something like the following:
It's safer than .urlQueryAllowed and the others, because it this will encode every characters other than A-Z, a-z and 0-9. This works better when the value you are encoding may use special characters like ?, &, =, + and spaces.
It will depend on your url. If your url is a path you can use the character set urlPathAllowed
Creating a Character Set for URL Encoding
You can create also your own url character set:
Another option is to use URLComponents to properly create your url
In my case where the last component was non latin characters I did the following in Swift 2.2:
For the given URL string the equivalent to
is the character set
URLQueryAllowedCharacterSet
Swift 3:
It encodes everything after the question mark in the URL string.
Since the method
stringByAddingPercentEncodingWithAllowedCharacters
can return nil, use optional bindings as suggested in the answer of Leo Dabus.Swift 4.0
Swift 3.0 (From grokswift)
Creating URLs from strings is a minefield for bugs. Just miss a single / or accidentally URL encode the ? in a query and your API call will fail and your app won’t have any data to display (or even crash if you didn’t anticipate that possibility). Since iOS 8 there’s a better way to build URLs using
NSURLComponents
andNSURLQueryItems
.Below is the code to access url using
guard
statement.Output: