0

Hy, I am new to swift and I am doing work on nsurlsession. Here is my code

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

Thus from this code the data arrives from the websrvice but I want to do that first it takes two parameters from me and then show data? please help me. Sorry for my English. It's weak.

Vvk
  • 4,031
  • 29
  • 51
  • The answers below assume your web service is expecting JSON request. But that's not at all clear. There are many ways the request might need to be formatted (e.g. a `Content-Type` of `application/x-www-form-urlencoded` vs `application/json`). Can you tell us precisely in what format the server requires the request? – Rob Feb 08 '16 at 06:27
  • If your server is expecting an `application/x-www-form-urlencoded` request (e.g. you see stuff in the web service code that references `$_POST`, for example), see http://stackoverflow.com/a/33574126/1271826 or http://stackoverflow.com/a/31031859/1271826. – Rob Feb 08 '16 at 06:50

3 Answers3

2

You can have your parameters in dictionary and then convert it to NSData. Try out following

let request = NSURLRequest(URL: NSURL(string:"http://o16-labs.com/swapby/getcategoryinfo")!)
let params = ["key1" : "value1", "key2" : "value2"] as Dictionary<String, AnyObject>
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted)
Vishnu gondlekar
  • 3,896
  • 21
  • 35
  • I think you meant `NSMutableURLRequest`. He may want to specify `HTTPMethod` as `POST`, too, depending upon the server requirements. And, obviously, your answer assumes that he needs JSON request, which is not at all clear. – Rob Feb 08 '16 at 06:53
  • It's showing error at that point request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options:NSJSONWritingOptions.PrettyPrinted) the error is cannot assign value – Muhammad Murtaza Feb 08 '16 at 09:16
  • @MuhammadMurtaza - Yes, replace that `NSURLRequest` with `NSMutableURLRequest`. – Rob Feb 11 '16 at 17:46
1

Frame the parameters to dictionary format and set that parameters to HTTPBody.Below code helps you...

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()
Aruna kumari
  • 329
  • 1
  • 11
  • This code give error at this point request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err) The error is cannot assign property value – Muhammad Murtaza Feb 08 '16 at 09:04
  • @MuhammadMurtaza u got output ? Add catch block for error handling in swift otherwise it shows error like Extra argument 'error' in call. Compilation error in Swift 2.0 – Aruna kumari Feb 08 '16 at 09:27
0

This is an update from @Vishnu gondlekar answer:

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