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()
4
  • I think it's not clear what the problem is - could you be more specific? Commented Nov 20, 2014 at 10:16
  • Sorry for my language...I want to adjust a parameter <request.HTTPBody = params<what should do for Json 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 Commented Nov 20, 2014 at 10:52
  • The answer depends on usr and pwdCode types. string? Commented Nov 22, 2014 at 4:52
  • Possible duplicate of How to post a JSON with new Apple Swift Language Commented Aug 10, 2016 at 23:13

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

What does AFNetworking give you over NSURLSession? I used to use AFNetworking but NSURLSession seems remarkably similar to what it used to do.
@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 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
This was so helpful, I battled with this issue for a good amount of time, finally got it right thanks to this answer.
your link is not for swift code its objective c code.please provide afnetworking link for swift code
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": "[email protected]", "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)")
            }
    }
    

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.