1

I am stuck with the below code. How do I set the param and in post method?

let params:[String:Any] = [
        "email" : usr,
        "userPwd" : pwdCode]

let url = NSURL(string:"http://inspect.dev.cbre.eu/SyncServices/api/jobmanagement/PlusContactAuthentication")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

request.HTTPBody = params<what should do for Json parameter>


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

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if error {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
}
task.resume()
surui
  • 1,522
  • 12
  • 17
dhaval shah
  • 4,499
  • 10
  • 29
  • 42
  • I think it's not clear what the problem is - could you be more specific? – Antonio Nov 20 '14 at 10:16
  • Sorry for my language...I want to adjust a parameter for post method ..but i dont know how to do that?If you can edit my code and show it to me than it ll be good – dhaval shah Nov 20 '14 at 10:52
  • The answer depends on `usr` and `pwdCode` types. string? – rintaro Nov 22 '14 at 04:52
  • Possible duplicate of [How to post a JSON with new Apple Swift Language](http://stackoverflow.com/questions/24566180/how-to-post-a-json-with-new-apple-swift-language) – Thales P Aug 10 '16 at 23:13

2 Answers2

5

if I understand the question correctly

var configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
var session = NSURLSession(configuration: configuration)
var usr = "dsdd"
var pwdCode = "dsds"
let params:[String: AnyObject] = [
    "email" : usr,
    "userPwd" : pwdCode ]

let url = NSURL(string:"http://localhost:8300")
let request = NSMutableURLRequest(URL: url!)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions.allZeros, error: &err)

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

    if let httpResponse = response as? NSHTTPURLResponse {
        if httpResponse.statusCode != 200 {
            println("response was not 200: \(response)")
            return
        }
    }
    if (error != nil) {
        println("error submitting request: \(error)")
        return
    }

    // handle the data of the successful response here
    var result = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary
    println(result)
}
task.resume()

I would suggest using AFNetworking. See for example, Posting JSON data using AFNetworking 2.0.

Community
  • 1
  • 1
surui
  • 1,522
  • 12
  • 17
  • What does AFNetworking give you over NSURLSession? I used to use AFNetworking but NSURLSession seems remarkably similar to what it used to do. – Adam Eberbach Mar 24 '15 at 05:28
  • @AdamEberbach, AFNetworking (2.x) is built on top of NSURLSession to provide some abstractions that make your life easier. For example, it may parse the data as JSON (the headers in the response usually say the type of data). There are many other things; you can start from this tutorial http://www.raywenderlich.com/59255/afnetworking-2-0-tutorial and then visit the docs to see further usage. However, I agree that sometimes you don't need to bring the big guns if you don't need them :) -Another thing worth noting - If you want to target iOS 6 you might find AFNetworking to be your best option – surui Mar 25 '15 at 11:19
  • This was so helpful, I battled with this issue for a good amount of time, finally got it right thanks to this answer. – Stefan Konno Oct 01 '15 at 07:08
  • your link is not for swift code its objective c code.please provide afnetworking link for swift code – Akash Raghani Jun 04 '16 at 05:45
0

This is how you can set parameters and send a POST request, easy approach using Alamofire.

  • Swift 2.2

    let URL = NSURL(string: "https://SOME_URL/web.send.json")!
    let mutableURLRequest = NSMutableURLRequest(URL: URL)
    mutableURLRequest.HTTPMethod = "POST"
    
    let parameters = ["api_key": "______", "email_details": ["fromname": "______", "subject": "this is test email subject", "from": "support@apple.com", "content": "<p> hi, this is a test email sent via Pepipost JSON API.</p>"], "recipients": ["_________"]]
    
    do {
        mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
    } catch {
        // No-op
    }
    
    mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
    
    Alamofire.request(mutableURLRequest)
        .responseJSON { response in
            print(response.request)  // original URL request
            print(response.response) // URL response
            print(response.data)     // server data
            print(response.result)   // result of response serialization
    
            if let JSON = response.result.value {
                print("JSON: \(JSON)")
            }
    }
    
Codetard
  • 2,441
  • 28
  • 34