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
ReplyDeleteEagles vs Bengals
Eagles vs Bengals live
nfl game pass
nfl live
live nfl
live nfl on cbs
Dolphins vs Ravens
Dolphins vs Ravens live
nfl game pass
nfl live
live nfl
live nfl on cbs
Bills vs Raiders
Bills vs Raiders live
nfl game pass
nfl live
live nfl
live nfl on cbs
49ers vs Bears
49ers vs Bears live
nfl game pass
nfl live
live nfl
live nfl on cbs
Giants vs Steelers
Giants vs Steelers live
nfl game pass
nfl live
live nfl
live nfl on cbs
Redskins VS Cardinals
ReplyDeleteRedskins VS Cardinals live
nfl game pass
nfl live
live nfl
live nfl on cbs
Buccaneers vs Chargers
Buccaneers vs Chargers live
nfl game pass
nfl live
live nfl
live nfl on cbs
Panthers vs Seahawks
Panthers vs Seahawks live
nfl game pass
nfl live
live nfl
live nfl on cbs
Nice Blog.
ReplyDeleteThe details that you share about Swift code that sends HTTP POST request.
I was looking for a swift app development company and got your blog. Thanks for sharing such a great blog.
Synsoft Global