I'm very new to swift, so I will probably have a lot of faults in my code but what I'm trying to achieve is send a GET
request to a localhost server with paramters. More so I'm trying to achieve it given my function take two parameters baseURL:string,params:NSDictionary
. I am not sure how to combine those two into the actual URLRequest ? Here is what I have tried so far
func sendRequest(url:String,params:NSDictionary){
let urls: NSURL! = NSURL(string:url)
var request = NSMutableURLRequest(URL:urls)
request.HTTPMethod = "GET"
var data:NSData! = NSKeyedArchiver.archivedDataWithRootObject(params)
request.HTTPBody = data
println(request)
var session = NSURLSession.sharedSession()
var task = session.dataTaskWithRequest(request, completionHandler:loadedData)
task.resume()
}
}
func loadedData(data:NSData!,response:NSURLResponse!,err:NSError!){
if(err != nil){
println(err?.description)
}else{
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
println(jsonResult)
}
}
When building a
GET
request, there is no body to the request, but rather everything goes on the URL. To build a URL (and properly percent escaping it), you can also useURLComponents
.The only trick is that most web services need
+
character percent escaped (because they'll interpret that as a space character as dictated by theapplication/x-www-form-urlencoded
specification). ButURLComponents
will not percent escape it. Apple contends that+
is a valid character in a query and therefore shouldn't be escaped. Technically, they are correct, that it is allowed in a query of a URI, but it has a special meaning inapplication/x-www-form-urlencoded
requests and really should not be passed unescaped.Apple acknowledges that we have to percent escaping the
+
characters, but advises that we do it manually:This is an inelegant work-around, but it works, and is what Apple advises if your queries may include a
+
character and you have a server that interprets them as spaces.So, combining that with your
sendRequest
routine, you end up with something like:And you'd call it like:
Personally, I'd use
JSONDecoder
nowadays and return a customstruct
rather than a dictionary, but that's not really relevant here. Hopefully this illustrates the basic idea of how to percent encode the parameters into the URL of a GET request.See previous revision of this answer for Swift 2 and manual percent escaping renditions.
You can extend your
Dictionary
to only providestringFromHttpParameter
if both key and value conform toCustomStringConvertable
like thisthis is much cleaner and prevents accidental calls to
stringFromHttpParameters
on dictionaries that have no business calling that methodThis extension that @Rob suggested works for Swift 3.0.1
I wasn't able to compile the version he included in his post with Xcode 8.1 (8B62)
Use NSURLComponents to build your NSURL like this
I use:
Swift 3:
I used it to get the image name for
UIImagePickerController
infunc imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
: