NSURLSession使用get发送参数

时间:2014-08-09 21:50:32

标签: json parsing dictionary swift

我正在尝试解析来自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()
}

谢谢!

6 个答案:

答案 0 :(得分:12)

GET数据需要是url查询字符串的一部分。有些方法会接受POST / PUT请求的参数字典,但是如果您使用GET方法,这些方法不会为您添加字典。

如果您希望将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 /等),您只需要将此查询字符串附加到您的基本api URL以获取GET请求:

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

如果您仅提出GET请求,则无需检查您用于发送数据的方法。

答案 1 :(得分:5)

@ paul-mengelt在目标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 : @""];
}

答案 2 :(得分:5)

有点疯狂,这里没有任何答案建议使用NSURLComponentsNSURLQueryItem个对象。这是最安全,最现代的方式。

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

答案 3 :(得分:2)

改编为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: "&")
}

答案 4 :(得分:1)

固定目标C函数

+(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 : @""];
}

答案 5 :(得分:0)

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"url_to_your_web_service.php/?key=%@",value]];

NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject];
NSURLSessionDataTask * dataTask = [defaultSession dataTaskWithURL:url
                                                completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                    if(error == nil){
                                                        NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                        NSLog(@"Data = %@",text);
                                                        }
                                                    }
                                                }
                                   ];
[dataTask resume];

在您的php中获取密钥的值:

$ value = $ _ GET ['key'];