I'm learning swift and I need to make a GET request, so this is my code:
var j = ["user": "[email protected]"]
var e: NSError?
let jsonData = NSJSONSerialization.dataWithJSONObject(j,options: NSJSONWritingOptions(0),error: &e)
var jsonString = NSString(data: jsonData!, encoding: NSUTF8StringEncoding)
var urlPath = "http://test.example.io/materials?query=\(jsonString)";
println(urlPath)
var url: NSURL = NSURL(string: urlPath)
var request: NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-Application-Id")
request.addValue("xxxxxxxxxxxxxxxxxxxx" , forHTTPHeaderField: "Teech-REST-API-Key")
request.addValue("application/json" , forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "GET"
println(request)
And this is my output debug
http://test.example.io/materials?query={"user":"[email protected]"}
<NSMutableURLRequest: 0x7f8ee3480320> { URL: (null), headers: {
"Content-Type" = "application/json";
"Teech-Application-Id" = xxxxxxxxxxxxxxxxxxxxxxxx;
"Teech-REST-API-Key" = xxxxxxxxxxxxxxxxxxxxxxxxx;
} }
Why the first print function return the correct url and inside the print request there is a null url, where is my mistake ? I've tried with a url without a json and it runs.
I done it, the solution is escaping the string.
var escapedSearchTerm = urlPath.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
var url: NSURL = NSURL(string: escapedSearchTerm!)