32

Here some code:

var URL: NSURL = NSURL(string: "http://stackoverflow.com")
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = ?????? 
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) 
{
    (response, data, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

What should I write in request.HTTPBody if I want send POST query "key" = "value" ?

6
  • what about stackoverflow.com/questions/24068866/… ? Commented Jul 12, 2014 at 15:49
  • I've seen this. But I did not see there example with key=value. Just "some data". For php it looks like: $_POST['key'] = "value"; Commented Jul 12, 2014 at 15:52
  • 2
    As long as you are writing in Swift (which is iOS 7+) you might also consider using NSURLSession (also iOS 7+) rather than NSURLConnection. Commented Jul 12, 2014 at 20:04
  • Please can you tell why NSURLSession is preferred than NSURLConnection? Commented Jul 12, 2014 at 21:41
  • Guys sorry but can anyone tell me what does this line means (response, data, error) in println(NSString(data: data, encoding: NSUTF8StringEncoding)) Commented Oct 17, 2014 at 12:59

4 Answers 4

56

No different than in Objective-C, HTTPBody expects an NSData object:

var bodyData = "key1=value&key2=value&key3=value"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);

You'll have to setup the values & keys yourself in the string.

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

8 Comments

I think I do something wrong: on the server I have just index.php: if($_POST['test'] == "some") echo "Works"; else echo "Not works". In additional of my code in first post I've added as you wrote: var bodyData = "some=test". And I've got "Not works". Something wrong with swift code?
In the client you should be setting key=value, so the string should be test=some not some=test
It sounds strange, but problem was in URL address. I have index.php in folder /someFolder/ and URL was: "localhost/somefolder". When I changed it to "localhost/somefolder". It works. But with first URL I've too got answer just not correct. So strange.
how can I send through a base64 image? It is a long string and is cutting it off when sending to the server even though I am using post?
This doesn't property encode the data (escape/quote special chars and such).
|
2

Update to Swift 4.2

This code is based on pixel's answer, and is meant as an update for Swift 4.2

let bodyData = "key1=value&key2=value&key3=value"
request.httpBody = bodyData.data(using: .utf8)

1 Comment

It should be let bodyData = "key1=value&key2=value&key3=value"
2
class func postMethod (params: [String : AnyObject], apikey: String, completion: @escaping (Any) -> Void, failure:@escaping (Error) -> Void)
{
    if Utils().isConnectedToNetwork() == false
    {
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.1, execute: {
            Utils().HideLoader()
        })
        return
    }

    let strURL = Constants.BASE_URL + apikey
    let url = URL(string: strURL)
    print(params)
    print(strURL)

    var token = String()

    if((Constants.USERDEFAULTS .value(forKey: "token")) != nil){

        token = Constants.USERDEFAULTS.value(forKey: "token") as! String
    }
    else{
         token = ""
    }

    let headers = [
        "Authorization": "Bearer \(token)",
        "Accept": "application/json"
    ]


    let manager = Alamofire.SessionManager.default
    manager.session.configuration.timeoutIntervalForRequest = 120
    manager.request(url!, method: .post, parameters: params, headers: headers)
        .responseJSON
        {
            response in
            switch (response.result)
            {
            case .success:
                let jsonResponse = response.result.value as! NSDictionary
                print(jsonResponse)
                completion(jsonResponse)
                Utils().HideLoader()
            case .failure(let error):
                Utils().showAlert("Something went wrong")
                Utils().HideLoader()
                failure(error)
                break
        }
    }
}

1 Comment

Third party packages should only be referenced if requested by the original OP.
-1
 var post:NSString = "api=myposts&userid=\(uid)&page_no=0&limit_no=10"

    NSLog("PostData: %@",post);

    var url1:NSURL = NSURL(string: url)!

    var postData:NSData = post.dataUsingEncoding(NSASCIIStringEncoding)!

    var postLength:NSString = String( postData.length )

    var request:NSMutableURLRequest = NSMutableURLRequest(URL: url1)
    request.HTTPMethod = "POST"
    request.HTTPBody = postData
    request.setValue(postLength, forHTTPHeaderField: "Content-Length")
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")


    var reponseError: NSError?
    var response: NSURLResponse?

    var urlData: NSData? = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&reponseError)

    if ( urlData != nil ) {
        let res = response as NSHTTPURLResponse!;

        NSLog("Response code: %ld", res.statusCode);

        if (res.statusCode >= 200 && res.statusCode < 300)
        {
            var responseData:NSString  = NSString(data:urlData!, encoding:NSUTF8StringEncoding)!

            NSLog("Response ==> %@", responseData);

            var error: NSError?

            let jsonData:NSDictionary = NSJSONSerialization.JSONObjectWithData(urlData!, options:NSJSONReadingOptions.MutableContainers , error: &error) as NSDictionary


            let success:NSInteger = jsonData.valueForKey("error") as NSInteger

            //[jsonData[@"success"] integerValue];

            NSLog("Success: %ld", success);

            if(success == 0)
            {
                NSLog("Login SUCCESS");

                self.dataArr = jsonData.valueForKey("data") as NSMutableArray 
                self.table.reloadData()

            } else {

                NSLog("Login failed1");
            }

        } else {

            NSLog("Login failed2");

        }
    } else {

         NSLog("Login failed3");
    }

This will help you definitely

1 Comment

Adding " request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")" made everything to work for me. Thanks.

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.