Send a POST Request to a URL using Swift

Samsul Hoque
3


Swift code that sends HTTP POST request and reads response body:

HTTPHelper.swift:

//  HTTPHelper.swift
//  Created by Samsul Hoque on 8/30/16.
//  Copyright © 2016 Sams . All rights reserved.
//

class HTTPHelper{
class func httpPostDataDic(postURL:NSURL,postString:NSString,completionHandler:(NSDictionary?, NSError?) -> Void ) -> NSURLSessionTask{
    var responseResultData: NSDictionary = NSDictionary()
    let request = NSMutableURLRequest(URL:postURL);
    request.HTTPMethod = "POST";// Compose a query string
    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
    print(request)

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in
        if error != nil
        {
            print("error=\(error)")
            completionHandler(nil, error)
            return
        }
       // You can print out response object
        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        //            print("responseString = \(responseString)")
        if let responseString = responseString {
            print("responseString = \(responseString)")
        }
        //Let's convert response sent from a server side script to a NSDictionary object:
        do {
            let myJSON =  try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
            responseResultData=myJSON!
            completionHandler(responseResultData, nil)
        } catch {
            print(error)
        }
    }
    task.resume()
    return task


  }

}

Call this HTTPHelper Post Function :

@IBAction func loginBTN(sender: AnyObject) {

    let myUrl = NSURL(string: "http://www.swiftdeveloperblog.com/http-post-example-script/")
    let postString = "firstName=James&lastName=Bond";

 HTTPHelperDu8.httpPostDataDic(myUrl!, postString: postString) {
        (responseResult, error) -> Void in

        if error != nil{

            print(error)
        }
        else{
            if let resutlData = responseResult{          //To get rid of optional
               print(resutlData)

                //your code

            }

        }



    }
Objective-c:here

Post a Comment

3Comments
Post a Comment