json – NSURLSession使用get发送参数

前端之家收集整理的这篇文章主要介绍了json – NSURLSession使用get发送参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试从PHP解析信息,但我需要发送一个字典参数,所以我尝试的东西…我看到教程,例子,但我被困,所以我回到开始:(这是什么好的方法为了这样做?)
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方法,这些方法将不会为您添加字典到您的URL.

如果您希望将“GET”参数保留在“字典”中以保持清晰度或一致性,请考虑将以下方法添加到您的项目中:

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("&")
}

方法将使用键/值对的字典,并返回可附加到您的网址的字符串.

例如,如果您的API请求允许多个请求方法(GET / POST / etc.),则只需要将此查询字符串附加到您的基本api网址以获取GET请求:

if (request.HTTPMethod == "GET") {
    urlPath += buildQueryString(fromDictionary:parm)
}

如果您只是提交GET请求,则无需检查您将要使用哪种方法来发送数据.

原文链接:https://www.f2er.com/js/150879.html

猜你在找的JavaScript相关文章