Encoding a URL
In both the sendGetRequest
and sendPostRequest
examples, we used the stringByAddingPercentEscapesUsingEncoding()
function to make sure that we had a valid URL. While this function does make sure that we have a valid URL, it does not always return the URL that we expect. In Apple's documentation of this function, it notes the following issue, in Apple's documentation of this function, it notes that it may be difficult to use this function to clean up unescaped or partially escaped URL strings where sequences are unpredictable.
With this in mind, the following function is a much better way to convert a standard string to a valid URL:
private func urlEncode(s: String) -> String { return CFURLCreateStringByAddingPercentEscapes(nil, s, nil, "!*'\"();:@&=+$,/?%#[]", CFStringBuiltInEncodings.UTF8.rawValue) as! String }
Within this function, we use the CFURLCreateStringByAddingPercentEscapes()
function to replace the characters listed with the equivalent...