stringswiftswift2nscharacterset

How to use stringByAddingPercentEncodingWithAllowedCharacters() for a URL in Swift 2.0


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


Solution

  • For the given URL string the equivalent to

    let urlwithPercentEscapes = myurlstring.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
    

    is the character set URLQueryAllowedCharacterSet

    let urlwithPercentEscapes = myurlstring.stringByAddingPercentEncodingWithAllowedCharacters( NSCharacterSet.URLQueryAllowedCharacterSet())
    

    Swift 3:

    let urlwithPercentEscapes = myurlstring.addingPercentEncoding( withAllowedCharacters: .urlQueryAllowed)
    

    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.