Tuesday, February 17, 2015

iOS Development - URL Encoding in SWIFT

When consuming web services from endpoints, many a times, the input data for the service is sent using GET methods. In other words, the data is part of the request URL.

For the URL to be valid, the data should be encoded, so that the combined end point URL, and the data part does not make the overall URL string invalid.

In the new apple programming language, SWIFT, this can be achieved as follows:

let endPointURL:String  = "https://mutationevent-qr-code-generator.p.mashape.com/generate.php";
let endUrl = endPointURL+"?content="+txtData.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())!;

The method : stringByAddingPerfentEncodingWithAllowedCharacters  takes in a set of allowed character set, and converts the owner string to an encoded form. In this case, txtData variable holds the text entered by the user in a text box. Without using the above encoding, if the user entered a text with spaces, the "endURL" will be an invalid URL, since spaces are NOT allowed in a URL.

However, with the above method, all spaces in txtData will be replaced with "%20", and so will any other special characters be encoded appropriately. This will result in an overall valid URL, which can then be used to dispatch a web request using NSURLSession()

No comments: