NSURLSession使用get发送参数 [英] NSURLSession send parameters with get
问题描述
我正在尝试从php解析信息,但是我需要发送一个字典参数,所以我尝试的东西...我看到教程,例子,但我被困,所以我回到开始:(它是什么这样做的好方法?)
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()
}
谢谢!
推荐答案
GET数据需要是url的查询字符串的一部分。某些方法将接受POST / PUT请求的参数字典,但如果您使用GET方法,这些方法将不会为您添加字典。
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.
如果您希望将词典中的GET参数保留在清晰度或一致性中,请考虑向您的项目添加如下所示的方法:
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 {
if let encodedValue = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet()) {
urlVars.append(k + "=" + encodedValue)
}
}
return urlVars.isEmpty ? "" : "?" + urlVars.joinWithSeparator("&")
}
此方法将采用一个字典的键/值对,并返回一个可以附加到您的网址的字符串。
This method will take a dictionary of key/value pairs and return a string you can append to your url.
例如,如果您的API请求允许多个请求方法(GET / POST / etc) )你只需要将这个查询字符串附加到你的基本api url中,以获取GET请求:
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)
}
如果您只是提出GET请求,则无需检查您将要使用哪种方法来发送数据。
If you're only making GET requests, there's no need to check for which method you'll be using to send your data.
这篇关于NSURLSession使用get发送参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!