I'm trying to parse information from a php, but i need to send a dictionary parameter so i try things ... i saw tutorials,examples but i'm stuck so i went back to the start: (What it's the good way for do this?)
func asd(){
let urlPath = "http://xxxxx.php"
let url: NSURL = NSURL(string: urlPath)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "GET"
var parm = ["id_xxxx": "900"] as Dictionary
//I THINK MY PROBLEM IT'S HERE! i dont know how to link parm with session, i try is with session.uploadTaskWithRequest(<#request: NSURLRequest?#>, fromData: <#NSData?#>) but doesn't work
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithURL(url, completionHandler: {data, response, error -> Void in
println("Task completed")
if(error) {
// If there is an error in the web request, print it to the console
println(error.localizedDescription)
}
var err: NSError?
var jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as NSDictionary
if(err?) {
// If there is an error parsing JSON, print it to the console
println("JSON Error \(err!.localizedDescription)")
}
println(jsonResult.debugDescription)
let results: NSArray = jsonResult["x"] as NSArray
dispatch_async(dispatch_get_main_queue(), {
self.tableData = results
self.OfertaGridViewLista!.reloadData()
})
})
task.resume()
}
Thanks!
GET data needs to be part of the url's query string. Some methods will accept a dictionary of parameters for POST/PUT requests, but these methods will not add the dictionary to the url for you if you're using the GET method.
If you'd like to keep your GET parameters in a Dictionary for cleanliness or consistency, consider adding a method like the following to your project:
func buildQueryString(fromDictionary parameters: [String:String]) -> String {
var urlVars:[String] = []
for (k, value) in parameters {
let value = value as NSString
if let encodedValue = value.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed) {
urlVars.append(k + "=" + encodedValue)
}
}
return urlVars.isEmpty ? "" : "?" + urlVars.joined(separator: "&")
}
This method will take a dictionary of key/value pairs and return a string you can append to your url.
For example, if your API requests allow for multiple request methods (GET/POST/etc.) you'll only want to append this query string to your base api url for GET requests:
if (request.HTTPMethod == "GET") {
urlPath += buildQueryString(fromDictionary: parm)
}
If you're only making GET requests, there's no need to check for which method you'll be using to send your data.
Bit crazy that none of the answers here suggest using NSURLComponents
and NSURLQueryItem
objects. That is the safest and most modern way to do this.
var iTunesSearchURL = URLComponents(string: "https://itunes.apple.com/search")!
iTunesSearchURL.queryItems = [URLQueryItem(name: "term", value: trackName),
URLQueryItem(name: "entity", value: "song"),
URLQueryItem(name: "limit", value: "1")]
let finalURL = iTunesSearchURL.url
@paul-mengelt's answer in Objective C:
-(NSString *) buildQueryStringFromDictionary:(NSDictionary *)parameters {
NSString *urlVars = nil;
for (NSString *key in parameters) {
NSString *value = parameters[key];
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
urlVars = [NSString stringWithFormat:@"%@%@=%@", urlVars ? @"&": @"", key, value];
}
return [NSString stringWithFormat:@"%@%@", urlVars ? @"?" : @"", urlVars ? urlVars : @""];
}
Adapted for Swift 3
static func buildQueryString(fromDictionary parameters: [String:String]) -> String {
var urlVars:[String] = []
for (k,value) in parameters {
if let encodedValue = value.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) {
urlVars.append(k + "=" + encodedValue)
}
}
return urlVars.isEmpty ? "" : "?" + urlVars.joined(separator: "&")
}
fixed objective C function
+(NSString *)buildQueryStringFromDictionary:(NSDictionary *)parameters
{
NSString *urlVars = @"";
for (NSString *key in parameters)
{
NSString *value = parameters[key];
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
urlVars = [NSString stringWithFormat:@"%@%@%@=%@", urlVars, urlVars.length ? @"&": @"", key, value];
}
return [NSString stringWithFormat:@"%@%@", urlVars ? @"?" : @"", urlVars ? urlVars : @""];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With