使用参数进行nsurlsession请求

时间:2016-02-08 05:49:45

标签: ios swift nsurlsession

Hy,我是swift的新手,我正在为nsurlsession工作。 这是我的代码

  func webRequestToServer() {
            let request = NSURLRequest(URL: NSURL(string:"some url")!)
            let urlSession = NSURLSession.sharedSession()
            let task = urlSession.dataTaskWithRequest(request, completionHandler: {
                (data, response, error) -> Void in
                if let error = error {
                    print(error)
                    return }
                // Parse JSON data
                if let data = data {

                    let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
                    print(dataString)
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in

                    })
                } }) 
            task.resume()
        }

因此,从这个代码中,数据来自websrvice,但是我想首先从我那里获取两个参数,然后显示数据?请帮我。对不起我的英语不好。它很弱。

3 个答案:

答案 0 :(得分:2)

您可以将参数放在字典中,然后将其转换为NSData。试试下面的

ant

答案 1 :(得分:1)

将参数框架化为字典格式并将参数设置为HTTPBody.Below代码可以帮助您...

let myUrl = NSURL(string: "http://o16-labs.com/swapby/getcategoryinfo");
    let request = NSMutableURLRequest(URL:myUrl!);
    request.HTTPMethod = "POST";
    // Compose a query string
    let postString = "firstName=James&lastName=Bond";

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil
        {
            print("error=\(error)")
            return
        }

        // You can print out response object
        print("response = \(response)")

        // Print out response body
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")

        //Let’s convert response sent from a server side script to a NSDictionary object:

        do {
            if let jsonResult = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
                print(jsonResult)
            }
        } catch let error as NSError {
            print(error.localizedDescription)
        }

    }

    task.resume()

答案 2 :(得分:0)

这是@Vishnu gondlekar答案的更新:

let params = ["key1": "value1", "key2": "value2"] as [String: Any]
var urlRequest = URLRequest(url: url)
urlRequest.httpBody = try? JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)