How to send form data in POST request in Swift 3 - post

I am trying to post form-data using webservice, userName & password, but in response it's showing an error stating "Could not connect to the server.".
Please help me to send form data in the POST request.
let dict:[String:String] = ["userName": userName as! String, "password": password as! String]
do {
let jsonData = try JSONSerialization.data(withJSONObject: dict, options: .prettyPrinted)
let url = URL(string: "(some url)")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.setValue("application/x-www-form-urlencoded charset=utf-8", forHTTPHeaderField: "Content-Type")
request.httpBody = jsonData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if error != nil {
print(error!.localizedDescription)
return
}
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
let resultValue:String = parseJSON["success"] as! String;
print("result: \(resultValue)")
print(parseJSON)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
} catch {
print(error.localizedDescription)
}
I've tried adding values in the request, may be some values are missing in the request formed. Please help!
Thats the POSTMAN response

my calling api class
class ApiService
{
static func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
return data.map { String($0) }.joined(separator: "&")
}
static func callPost(url:URL, params:[String:Any], finish: #escaping ((message:String, data:Data?)) -> Void)
{
var request = URLRequest(url: url)
request.httpMethod = "POST"
let postString = self.getPostString(params: params)
request.httpBody = postString.data(using: .utf8)
var result:(message:String, data:Data?) = (message: "Fail", data: nil)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if(error != nil)
{
result.message = "Fail Error not null : \(error.debugDescription)"
}
else
{
result.message = "Success"
result.data = data
}
finish(result)
}
task.resume()
}
}
and when use it
ApiService.callPost(url: url, params: params, finish: finishPost)
and the finish function
func finishPost (message:String, data:Data?) -> Void
{
do
{
if let jsonData = data
{
let parsedData = try JSONDecoder().decode(Response.self, from: jsonData)
print(parsedData)
}
}
catch
{
print("Parse Error: \(error)")
}
}

Related

How to Pass Key Value Parameter in JSON POST method in Swift?

This is API http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/
its parameter: "contactsList" : ["5987606147", "6179987671", "5082508888"]
its header: ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
In my code if i put breakpoint then filtertaggedUser() is calling but i am unable to go inside completionHandler the access is not going inside dataTask
Access going to else part why? the api is working.
i am trying to pass parameter key value in URL string like below
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
is this correct approch?
code for above API:
func filtertaggedUser() {
print("inside filter taggedusers")
let headers = ["deviceid": "584D97F-761A-4C24-8C4B-C145A8B8BD75", "userType": "personal", "key": "9609cc826b0d472faf9967370c095c21"]
let urlStr = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/?contactsList=" + "8908908900"
let request = NSMutableURLRequest(url: NSURL(string:urlStr)! as URL,cachePolicy: .useProtocolCachePolicy,timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
// access not coming here
let httpResponse = response as? HTTPURLResponse
if httpResponse!.statusCode == 200 {
print("filter taggedusers inside")
do {
print("filter taggedusers inside do")
let jsonObject = try JSONSerialization.jsonObject(with: data!, options: .mutableLeaves) as! [String :AnyObject]
print("filter taggedusers \(jsonObject)")
} catch { print(error.localizedDescription) }
} else { Constants.showAlertView(alertViewTitle: "", Message: "Something went wrong, Please try again", on: self) }
})
dataTask.resume()
}
OUTPUT:
POSTMAN OUTPUT
POSTMAN Body
why response is not coming, where i did mistake, please help me with the code.
We can call the Post request API like below,
func getPostString(params:[String:Any]) -> String
{
var data = [String]()
for(key, value) in params
{
data.append(key + "=\(value)")
}
print(data.map { String($0) }.joined(separator: "&"))
return data.map { String($0) }.joined(separator: "&")
}
func callPostApi(){
let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/filter/taggedusers/")
guard let requestUrl = url else { fatalError() }
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
request.setValue("personal", forHTTPHeaderField: "userType")
let parameters = getPostString(params: ["contactsList":["8908908900"]])
request.httpBody = parameters.data(using: .utf8)
// Perform HTTP Request
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
let httpResponse = response as? HTTPURLResponse
print(httpResponse!.statusCode)
// Check for Error
if let error = error {
print("Error took place \(error)")
return
}
// Convert HTTP Response Data to a String
if let data = data, let dataString = String(data: data, encoding: .utf8) {
print("Response data string:\n \(dataString)")
}
}
task.resume()
}
Output :
{"8908908900":{"userId":"9609cc826b0d472faf9967370c095c21","userName":"Satish Madhavarapu","profilePic":null,"oniTaag":true,"tagged":false,"userType":"personal"}}

How to get JSON response data from shared class to ViewController?

I'm not using Alamofire, so i want to use JSON post approach in SharedClass and i want to send my api name and all parameters to that function. Finally i want to get the response back. I tried but it's not working. If it's not correct please correct me or if any other options are available please suggest me.
My code in SharedClass
func postRequestFunction(apiName:String , parameters:String ) -> [String:Any] {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else { // check for fundamental networking error
print(error!)
// print("error=\(String(describing: error))")
print("localizedDescription : \(String(describing: error?.localizedDescription))")
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
print(returnRes)
} catch let error as NSError {
print(error)
}
}
task.resume()
return returnRes
}
In my view controller class my code is. Here i'm calling function
func getProjectDetails() {
let response = SharedClass.sharedInstance.postRequestFunction(apiName: "API Name", parameters: parameters)
print(response)
let res = response["Response"] as! [String:Any]
let status = res["status"] as! String
if status == "SUCCESS" {
//I will handle response here
} else {
let message = res["message"] as! String
//Call alert function
SharedClass.sharedInstance.alert(view: self, title: "", message: message)
}
}
Here is my solution:
class APIManager {
private init () {}
static let shared = APIManager()
func postRequestFunction(apiName: String , parameters: String, onCompletion: #escaping (_ success: Bool, _ error: Error?, _ result: [String: Any]?)->()) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
var returnRes:[String:Any] = [:]
let task = URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
onCompletion(false, error, nil)
} else {
guard let data = data else {
onCompletion(false, error, nil)
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode == 200 {
do {
returnRes = try JSONSerialization.jsonObject(with: data, options: []) as! [String : Any]
onCompletion(true, nil, returnRes)
} catch let error as NSError {
onCompletion(false, error, nil)
}
} else {
onCompletion(false, error, nil)
}
}
}
task.resume()
}
}
func getProjectDetails() {
/* Notes:
** onCompletion Block Parameters:
success - This indicates whether the API called successfully or not.
error - This indicates errors from either API calling failed, JSON parsing, or httpStatus is not 200.
result - This indicates the JSON parsed result.
** APIManager:
I have renamed your SharedClass to APIManager for better readibility.
** sharedInstance:
I have renamed sharedInstance to shared for better readibility.
*/
APIManager.shared.postRequestFunction(apiName: "API Name", parameters: "parameters") { (success, error, result) in
if success {
if let res = result?["Response"] as? [String: Any] {
if let status = res["status"] as? String {
if status == "SUCCESS" {
//You can handle response here.
} else {
let message = res["message"] as! String
//Call alert function.
}
}
}
} else {
print(error?.localizedDescription)
}
}
}
You forgot the asynchronous paradigm of Service, You can return your API response in Closure, as like below
func postRequestFunction(apiName:String , parameters:String, returnRes: #escaping ([String: Any]) -> () ) {
var localURL = "hostname/public/index.php/v/***?"
localURL = localURL.replacingOccurrences(of: "***", with: apiName)
var request = URLRequest(url: URL(string: localURL)!)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
print("shared URL : \(request)")
request.httpBody = parameters.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let data = data, error == nil else {
// check for fundamental networking error
return
}
if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors
print("statusCode should be 200, but is \(httpStatus.statusCode)")
print("response = \(String(describing: response))")
}
do {
if let response = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
returnRes(response)
}
} catch let error as NSError {
print(error)
}
}
task.resume()
}
And use like below
postRequestFunction(apiName: "yourUrl", parameters: "Param") { (response) in
print(response)
}

How to send array by POST method to server?

I am trying to send array as parameter to server but server is not receiving. Server have to receive two arrays that I am sending. But in server they are not appear ?? I dont know is it my mistake or mistake in the server ??
My array name is testAns and testQuest and I have to send it to parameters: answer and quest.
my Code:
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(testAns)&quest=\(testQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}
i don't know how to encode that array on your server side.
but temporary you can try this way and check your database.
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer[0]=131&answer[1]=123&quest[0]=123&quest[1]=233"
You can use the Alamofire that is very popular at this time that is advanced version of AFNetworking
Also, I am sharing the method that will help you to hit API, You have to pass only the dictionary object in this method and this will give you the response in two blocks and you can use them as per requirements.
1: unReachable()
2: handler(responseDict)
//MARK: *********** HIT POST SERVICE IN JSON FORM***********
func hitPostServiceJsonForm(_ params:Dictionary<String,Any>,unReachable:(() -> Void),handler:#escaping ((Dictionary<String,Any>?) -> Void)) {
if networkReachable() == false {
unReachable()
}
let BASE_URL = "http://mydoamain"
var request = URLRequest(url: URL(string: BASE_URL)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try! JSONSerialization.data(withJSONObject: params, options: .prettyPrinted)
print(BASE_URL)
Alamofire.request(request).responseJSON { response in
//print("Request: \(String(describing: response.request))") // original url request
//print("Response: \(String(describing: response.response))") // http url response
print("Result: \(response.result)") // response serialization result
switch response.result {
case .success:
if let jsonDict = response.result.value as? Dictionary<String,Any> {
print("Json Response: \(jsonDict)") // serialized json response
handler(jsonDict)
}
else{
handler(nil)
}
if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
print("Server Response: \(utf8Text)") // original server data as UTF8 string
}
break
case .failure(let error):
handler(nil)
print(error)
break
}
}
}
func networkReachable() -> Bool {
return (NetworkReachabilityManager()?.isReachable)!
}
convert the your array to json string then try to send it to server
func post_array(){
let userID = UserDefaults.standard.string(forKey: "userID")
let artID = UserDefaults.standard.string(forKey: "index")
let myUrl = URL(string: "http://www.someurls.kz/modules/CheckTestF.php");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"
var testAns = [Int]()
var testQuest = [Int]()
testAns = [131,123,23]
testQuest = [123,233,232]
var tempAns : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testAns, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempAns = string! as NSString
}catch let error as NSError{
print(error)
}
var tempQuest : NSString = ""
do {
let arrJson = try JSONSerialization.data(withJSONObject: testQuest, options: .prettyPrinted)
let string = NSString(data: arrJson, encoding: String.Encoding.utf8.rawValue)
tempQuest = string! as NSString
}catch let error as NSError{
print(error)
}
let postString = "uID=97B436E41&idUser=\(userID!)&art_id=\(artID!)&answer=\(tempAns)&quest=\(tempQuest)"
print(postString)
print(testAns,testQuest)
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(String(describing: error))")
return
}
do {
_ = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
}
catch {
print(error)
}
}
task.resume()
}

Send Nested JSON With POST Request iOS Swift 3

I want to send JSON to Server with POST request but i did not understand how i do this. I select friends from table view and show these friends in my Collection view. And the selected peoples shows in collection views and their email are sent in JSON to Create group. Here is my code written in Swift.
#IBAction func createGroupButton(_ sender: Any) {
let groupName = groupNameTextField.text
let adminEmail = UserDefaults.standard.value(forKey: "userEmail")
if groupName == "" {
alertMessage(msg: "Enter Group name")
}
else if base64String == nil {
alertMessage(msg: "Select Group Image")
}
else if emailArray.isEmpty {
alertMessage(msg: "Select atleast one person")
}
else {
if isNetAvailable {
var emailData: String?
print("email data \(emailArray)")
for i in emailArray {
emailData = "\"email\":\"\(i)\""
}
let postData = "\"name\":\"\(groupName!)\",\"adminemail\":\"\(adminEmail!)\",\"image\":\"\(base64String!)\",\"emailArray\":\"\(emailData!)\""
let postDat = "jsondata={\(postData)}"
print("Post Data \(postDat)")
let urlString = create_group
let url = URL(string: urlString)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.httpBody = postDat.data(using: String.Encoding.utf8)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request) { (data, response, error) in
if error != nil {
print("Something wrong with creating Group")
}
if data == nil {
print("Nil Data")
}
if response == nil {
print("Nil Response")
}
if response != nil {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("Response String is \(responseString)")
}
}
task.resume()
}
else {
alertMessage(msg: "Internet Not Available")
}
}
}
Here is my API
<?php
if($_SERVER["REQUEST_METHOD"] !="POST"){ exit; }
require_once 'dbcon.php';
if (!empty($_POST['jsondata']))
{
$configjson = $_POST['jsondata'];
$config = json_decode($configjson, true);
$groupname = $config['name'];
$adminemail = $config['adminemail'];
$image = $config['image'];
$queryemailcheck = "SELECT * FROM groups_name WHERE admin = '$adminemail' AND groupname = '$groupname'";
$selectquery = mysqli_query($connect, $queryemailcheck);
$totalemails= mysqli_num_rows($selectquery);
if($totalemails>0)
{
echo "Already exist";
}
else {
$queryinsert= "INSERT INTO groups_name(admin , groupname , pic ) VALUES('$adminemail' ,'$groupname' , '$image')";
if(mysqli_query($connect, $queryinsert)){
echo "Successfully Saved";
}else{
echo "Error: " ;
}
$members = $config['emailArray'];
foreach($members as $row ){
$email = $row['email'];
$queryinsert2= "INSERT INTO group_members(groupname , member , status ) VALUES('$groupname' ,'$email' , '0')";
if(mysqli_query($connect, $queryinsert2)){
echo "Successfully Saved";
}else{
echo "Error: " ;
}
}
}
}
else echo "post data is empty";
?>
You can use Alamofire library for handling your webservices. like
Alamofire.request(logoutUrl, method: .post, parameters: dict, encoding: JSONEncoding.default, headers:["Authorization":"Bearer \(accessToken)", "Accept":"application/json", "Content-Type":"application/json; charset=UTF-8"]).responseJSON { (response) in
let json:JSON = JSON(response.result.value)
let status = json["status"].stringValue
let statusCode = response.response?.statusCode
Create network handler class where you can hit webservices from all of your app.
func makeHttpPostRequest(uri:String, postBody:Dictionary<String, Any> ,Completion:#escaping (_ response: AnyObject, _ success: Bool) -> Void) {
let networkCheck = self.getNetworkStatus()
if networkCheck == false {
Completion("NO internet connection." as AnyObject,false)
return
}//end network check block
var urlRequest = self.makeHttpRequestWithUrl(url: uri)
urlRequest.httpMethod = "POST"
urlRequest.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.setValue("application/json", forHTTPHeaderField: "Accept")
//check and set authorization header
if (UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) != nil) {
let authToken = UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) as! String
urlRequest.setValue("Token token="+authToken, forHTTPHeaderField: "Authorization")
}
//let postData = [self.addDefultParameters(detailDict: postBody)]
let jsonData = try? JSONSerialization.data(withJSONObject: postBody)
urlRequest.httpBody = jsonData
//create connection
self.httpConnectionWithRequest(request: urlRequest, Completion: Completion)
}
func makeHttpRequestWithUrl(url: String) -> URLRequest {
let urlString = AppConstant.baseUrl+url
let networkUrlRequest = URLRequest.init(url: URL.init(string: urlString)!, cachePolicy: .reloadIgnoringCacheData, timeoutInterval: 50)
return networkUrlRequest
}
func httpConnectionWithRequest(request: URLRequest, Completion:#escaping (_ response: AnyObject, _ success: Bool) -> Void) {
let session = URLSession.shared
// make the request
let task = session.dataTask(with: request) {
(data, response, error) in
// check for any errors
guard error == nil else {
print("error is: " + String.init(format: "%#", error?.localizedDescription as! CVarArg))
Completion(error!.localizedDescription as String as AnyObject, false)
return
}
// make sure we got data
guard let responseData = data else {
print("Error: did not receive data")
Completion("didn't get response data" as String as AnyObject, false)
return
}
let responseString = String.init(data: responseData, encoding: .utf8)
// parse the result as JSON, since that's what the API provides
if let resp = response as? HTTPURLResponse{
if (UserDefaults.standard.object(forKey: AppConstant.KAppAuthenticationToken) != nil) {
if resp.statusCode == 401{
//auth token expired
self.makeRequestWithNewToken(request: request, Completion: Completion)
}
}
//check if response is Array or dictionary
var jsonArray:[Any]?
var jsonDict:[String:Any]?
// response is in array
do{
jsonArray = try JSONSerialization.jsonObject(with: responseData, options: [])as? [Any]
}catch{
print("response doesn't contain array")
}
//response is in dictionary
do{
jsonDict = try JSONSerialization.jsonObject(with: responseData, options: [])as? [String:Any]
}catch{
print("response doesn't contain dict")
}
//=====
// if resp.statusCode == 200{
if jsonArray != nil{
Completion(jsonArray! as AnyObject, true)
return
}
if jsonDict != nil{
Completion(jsonDict! as AnyObject, true)
return
}
Completion("didn't get response data" as String as AnyObject, false)
return
}
}
task.resume()
}
And through the completion handler you will get the fetched data.

How do I perform GET and POST requests in Swift?

I adapted this from Ray Wenderlich's iOS Apprentice tutorial part 4.
This code works as a GET request sent to my Strongloop API with a simple database model, however:
This works, but I don't know why it works, since it invokes no method that I can see to actually send the request.
I see no means to make it into a POST request.
My question is: How do I perform a POST request? Is it done in a completely different way?
Let me know if you need more information.
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func getFromDB() {
let url = urlWithSearchText("")
println("URL: '\(url)'")
if let jsonString = performGetRequestWithURL(url) {
println("Received JSON string '\(jsonString)'")
}
}
func urlWithSearchText(searchText: String) -> NSURL {
let escapedSearchText = searchText.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let urlString = String(format: "http://localhost:3000/api/Tests", escapedSearchText)
let url = NSURL(string: urlString)
return url!
}
func performGetRequestWithURL(url: NSURL) -> String? {
var error: NSError?
if let resultString = String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error) {
return resultString
} else if let error = error {
println("Download Error: \(error)")
} else {
println("Unknown Download Error")
}
return nil
}
Here is a picture of this working:
https://dl.dropboxusercontent.com/u/14464971/Images/Messages%20Image%281477993527%29.png
Swift 3 & above
GET
func getRequest() {
// request url
let url = URL(string: "https://jsonplaceholder.typicode.com/todos/1")! // change the url
// create URLSession with default configuration
let session = URLSession.shared
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: url) { data, response, error in
if let error = error {
print("GET Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode) else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// serialise the data object into Dictionary [String : Any]
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: Any] {
print(jsonResponse)
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print("JSON Parsing Error: \(error.localizedDescription)")
}
}
// resume the task
task.resume()
}
POST
func postRequest() {
// declare the parameter as a dictionary that contains string as key and value combination. considering inputs are valid
let parameters: [String: Any] = ["name": "abc", "password": "password#123"]
// create the url with URL
let url = URL(string: "http://myServerName.com/api")! //change the url
// create the session object
let session = URLSession.shared
// now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST
// add headers for the request
request.addValue("application/json", forHTTPHeaderField: "Content-Type") // change as per server requirements
request.addValue("application/json", forHTTPHeaderField: "Accept")
do {
// convert parameters to Data and assign dictionary to httpBody of request
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
} catch let error {
print(error.localizedDescription)
return
}
// create dataTask using the session object to send data to the server
let task = session.dataTask(with: request) { data, response, error in
if let error = error {
print("Post Request Error: \(error.localizedDescription)")
return
}
// ensure there is valid response code returned from this HTTP response
guard let httpResponse = response as? HTTPURLResponse,
(200...299).contains(httpResponse.statusCode)
else {
print("Invalid Response received from the server")
return
}
// ensure there is data returned
guard let responseData = data else {
print("nil Data received from the server")
return
}
do {
// create json object from data or use JSONDecoder to convert to Model stuct
if let jsonResponse = try JSONSerialization.jsonObject(with: responseData, options: .mutableContainers) as? [String: Any] {
print(jsonResponse)
// handle json response
} else {
print("data maybe corrupted or in wrong format")
throw URLError(.badServerResponse)
}
} catch let error {
print(error.localizedDescription)
}
}
task.resume()
}
Below are two POST methods. Depending on if you want it synchronous (everything else waits until the post method is completed) or asynchronous (POST method runs in background, other methods run in parallel).
Methods
// POST data to url
func postDataAsynchronous(url: String, bodyData: String, completionHandler: (responseString: String!, error: NSError!) -> ()) {
var URL: NSURL = NSURL(string: url)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST";
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()){
response, data, error in
var output: String!
if data != nil {
output = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
}
completionHandler(responseString: output, error: error)
}
}
// Obtain the data
func postDataSynchronous(url: String, bodyData: String, completionHandler: (responseString: String!, error: NSError!) -> ())
{
let URL: NSURL = NSURL(string: url)!
var request:NSMutableURLRequest = NSMutableURLRequest(URL:URL)
request.HTTPMethod = "POST"
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var response: NSURLResponse?
var error: NSError?
// Send data
let data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: &error)
var output: String! // Default to nil
if data != nil{
output = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
}
completionHandler(responseString: output, error: error)
}
Using them
You can then call (use) them like so:
postDataSynchronous(url, bodyData: bodyData) {
responseString, error in
if error != nil {
println("Error during post: \(error)")
return
}
else{
//Success
println(responseString)
userType = responseString // Set usertype based on server response
}
}
SWIFT 2.0
func postData(url: String, params: Dictionary<String, String>, completionHandler: (data: NSData?, response: NSURLResponse?, error: NSError?) -> ()) {
// Indicate download
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
let url = NSURL(string: url)!
// print("URL: \(url)")
let request = NSMutableURLRequest(URL: url)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
// Verify downloading data is allowed
do {
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
} catch let error as NSError {
print("Error in request post: \(error)")
request.HTTPBody = nil
} catch {
print("Catch all error: \(error)")
}
// Post the data
let task = session.dataTaskWithRequest(request) { data, response, error in
completionHandler(data: data, response: response, error: error)
// Stop download indication
UIApplication.sharedApplication().networkActivityIndicatorVisible = false // Stop download indication
}
task.resume()
}
guard let url = URL(string: "https://jsonplaceholder.typicode.com/users") else { return }
let session = URLSession.shared
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
print(data)
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
}
It's a get method.
This method invokes the http request.
String(contentsOfURL: url, encoding: NSUTF8StringEncoding, error: &error)
Because Swift String has no init signature like this.
This method would be written somewhere in the project, as extension of String
It would be something like this
extension String{
init(contentsOfURL: NSURL, encoding: NSUTF8StringEncoding, inout error: NSError){
// load data from url
self = //parse data to string
}
}
The String(contentsOfUrl:encoding:error) initializer makes a GET request under the hood and returns the content as a string with the specified encoding.
One way to make a request would be to create an NSURLConnection and use NSMutablrURLRequest set the HTTP method the post. With the NSMutableURLRequest, you can create a NSURLConnection and start it immediately with a delegate or you can call NSURLConnection.sendSynchronousRequest or NSURLConnection.sendAsynchronousRequest to send the request.
let parameters = ["username": "#Bipin_kumar", "tweet": "HelloWorld"]
guard let url = URL(string: "https://jsonplaceholder.typicode.com/posts") else { return }
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
request.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}.resume()
It's a post method.
GET Request
func getRequest(with url: URL, callback: #escaping (Any?) -> Swift.Void) -> Void {
let defaultConfigObject = URLSessionConfiguration.default
defaultConfigObject.timeoutIntervalForRequest = 30.0
defaultConfigObject.timeoutIntervalForResource = 60.0
let session = URLSession.init(configuration: defaultConfigObject, delegate: nil, delegateQueue: nil)
var urlRequest = URLRequest(url: url as URL)
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.httpMethod = "GET"
session.dataTask(with: urlRequest, completionHandler: { (data, response, error) in
guard let httpResponse: HTTPURLResponse = response as? HTTPURLResponse
else {
print("Error: did not receive data")
return
}
var response : (Any)? = nil
if httpResponse.statusCode == 200 {
print(httpResponse)
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
let responseData = try JSONSerialization.jsonObject(with: responseData, options: [JSONSerialization.ReadingOptions.allowFragments])
response = responseData
callback(response)
}
catch _ as NSError {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
callback(responseString)
return
}
}
else {
print(httpResponse)
guard error == nil else {
print("error calling GET on /todos/1")
print(error ?? "error")
callback(response!)
return
}
}
}).resume()
}
POST REQUEST
//MARK: post request
func postRequest(with url:URL, postBody:String, callback: #escaping (Any?) -> Void) -> Void {
let defaultConfigObject = URLSessionConfiguration.default
defaultConfigObject.timeoutIntervalForRequest = 30.0
defaultConfigObject.timeoutIntervalForResource = 60.0
let session = URLSession.init(configuration: defaultConfigObject, delegate: nil, delegateQueue: nil)
let params: String! = postBody
var urlRequest = URLRequest(url: url as URL)
urlRequest.httpMethod = "POST"
let data = params.data(using: String.Encoding(rawValue: String.Encoding.utf8.rawValue))
urlRequest.httpBody = data
session.dataTask(with: urlRequest, completionHandler: { (data, urlResponse, error) in
guard let httpResponse:HTTPURLResponse = urlResponse as? HTTPURLResponse
else{
print("did not get any data")
return
}
var response : (Any)? = nil
if httpResponse.statusCode == 200 {
guard let responseData = data else {
print("Error: did not receive data")
return
}
do {
guard let responseData = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
print("error trying to convert data to JSON")
return
}
response = responseData
callback(response)
} catch _ as NSError {
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
callback(responseString)
return
}
}
else {
guard error == nil else {
print("error calling GET on /todos/1")
print(error ?? "error")
callback(nil)
return
}
}
}).resume()
}
Always try to check the HTTPURLResponse code

Resources