How to send array by POST method to server? - ios

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()
}

Related

How to send form data in POST request in Swift 3

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)")
}
}

How to make NSURLSession POST request in Swift

Hi I am very beginner for Swift and I am trying to make NSURLSession "Post" request sending some parameter like my below code
According to my below code response not coming from server can some one help me please
BackGroundClass:-
import UIKit
protocol sampleProtocal{
func getResponse(result:NSDictionary)
func getErrorResponse(error:NSString)
}
class BackGroundClass: NSObject {
var delegate:sampleProtocal?
func callPostService(url:String,parameters:NSDictionary){
print("url is===>\(url)")
let request = NSMutableURLRequest(URL: NSURL(string:url)!)
let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
//Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])
let task = session.dataTaskWithRequest(request) { data, response, error in
guard data != nil else {
print("no data found: \(error)")
return
}
do {
if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
print("Response: \(json)")
self.mainResponse(json)
} else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
print("Error could not parse JSON: \(jsonStr)")
self.eroorResponse(jsonStr!)
}
} catch let parseError {
print(parseError)// Log the error thrown by `JSONObjectWithData`
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
self.eroorResponse(jsonStr!)
}
}
task.resume()
}
func mainResponse(result:NSDictionary){
delegate?.getResponse(result)
}
func eroorResponse(result:NSString){
delegate?.getErrorResponse(result)
}
}
ViewController:-
import UIKit
class ViewController: UIViewController,sampleProtocal {
override func viewDidLoad() {
super.viewDidLoad()
let delegate = BackGroundClass();
delegate.self;
let params = ["scancode":"KK03799-008", "UserName":"admin"] as Dictionary<String, String>
let backGround=BackGroundClass();
backGround.callPostService("url", parameters: params)
}
func getResponse(result: NSDictionary) {
print("Final response is\(result)");
}
func getErrorResponse(error: NSString) {
print("Final Eroor code is\(error)")
}
}
Swift 4 post example with json payload-
func postAction(_ sender: Any) {
let Url = String(format: "your url")
guard let serviceUrl = URL(string: Url) else { return }
let parameterDictionary = ["username" : "Test", "password" : "123456"]
var request = URLRequest(url: serviceUrl)
request.httpMethod = "POST"
request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameterDictionary, 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()
}
Try to run this function and print the response, it is in Swift 4.0.
Here, I have prepared codable structure:
struct LoginData: Codable {
var code: Int?
var message: String?
var status: String?
var token: String?
var data: DataSet?
}
struct DataSet: Codable {
var email : String?
var contactNo : String?
var firstName : String?
var lastName: String?
var dob : String?
var gender : String?
var address: String?
var city : String?
var state : String?
var country : String?
var zip : String?
var username: String?
}
If you get your response printed correctly then pass it to your viewController.
func loginWS(parameters:[String:String], completionHandler: #escaping (Any?) -> Swift.Void) {
guard let gitUrl = URL(string: BASE_URL+ACTION_URL) else { return }
print(gitUrl)
let request = NSMutableURLRequest(url: gitUrl)
// uncomment this and add auth token, if your project needs.
// let config = URLSessionConfiguration.default
// let authString = "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjoxMywiUGFzc3dvcmQiOiIkMmEkMTAkYVhpVm9wU3JSLjBPYmdMMUk2RU5zdU9LQzlFR0ZqNzEzay5ta1pDcENpMTI3MG1VLzR3SUsiLCJpYXQiOjE1MTczOTc5MjV9.JaSh3FvpAxFxbq8z_aZ_4OhrWO-ytBQNu6A-Fw4pZBY"
// config.httpAdditionalHeaders = ["Authorization" : authString]
let session = URLSession.shared
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [])
let task = session.dataTask(with: request as URLRequest) { data, response, error in
guard let data = data else { return }
do {
// let decoder = JSONDecoder()
// here replace LoginData with your codable structure.
let gitData = try JSONDecoder().decode(LoginData.self, from: data)
print("response data:", gitData)
completionHandler(gitData)
} catch let err {
print("Err", err)
}
}.resume()
}
Here is a sample complete solution compatible with Swift 4 and Swift 5.
Endpoint to create urls
struct Endpoint {
let path: String
let queryItems: [URLQueryItem]?
}
extension Endpoint {
var url: URL? {
var components = URLComponents()
components.scheme = "https"
components.host = "YOUR_HOST"
components.path = path
components.queryItems = queryItems
return components.url
}
}
User object model for request body
struct User: Encodable {
let name: String
let surname: String
let age: Int
// this is to customise init
init(name: String,
surname: String,
age: Int) {
self.name = name
self.surname = surname
self.age = age
}
enum CodingKeys: String, CodingKey {
case name, surname, age
}
}
UserResponse model for http response comes from API
struct UserResponse: Decodable {
let message: String
let userId: String?
enum CodingKeys: String, CodingKey {
case message, userId = "user_id" // API returns userId as "user_id"
}
}
APIClient make http requests for our api
protocol APIClientProtocol: Any {
func sendUser(_ user: User, completionBlock: #escaping (_ userResponse: UserResponse?, _ error: APIClient.Error?) -> Void)
}
class APIClient: APIClientProtocol {
fileprivate let defaultSession: URLSession = {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 10.0
configuration.timeoutIntervalForResource = 10.0
return URLSession(configuration: configuration, delegate: nil, delegateQueue: nil)
}()
public init() { }
public func uploadUser(_ user: User, completionBlock: #escaping (UserResponse?, APIClient.Error?) -> Void) {
guard let url = Endpoint(path: "/user/upload", queryItems: nil).url else {
completionBlock(nil, .brokenURL)
return
}
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = "POST"
urlRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json", forHTTPHeaderField: "Accept")
do {
let jsonData = try JSONEncoder().encode(user)
urlRequest.httpBody = jsonData
} catch {
completionBlock(nil, .serialization(error.localizedDescription))
return
}
let task = defaultSession.dataTask(with: urlRequest) { data, urlResponse, error in
if let error = error {
completionBlock(nil, .http(error.localizedDescription))
return
}
guard let httpResponse = urlResponse as? HTTPURLResponse else {
return
}
if httpResponse.statusCode == 200 {
guard let data = data else {
return
}
do {
let userResponse = try JSONDecoder().decode(UserResponse.self, from: data)
completionBlock(userResponse, nil)
} catch let error {
completionBlock(nil, .serialization(error.localizedDescription))
}
} else {
completionBlock(nil, .http("Status failed!"))
}
}
task.resume()
}
}
extension APIClient {
enum Error: Swift.Error, Equatable {
case brokenURL
case serialization(String)
case http(String)
}
}
Post Class
func post(params : Dictionary<String, String>, url : String) {
var request = NSMutableURLRequest(URL: NSURL(string: url))
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
}
else {
// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.
if let parseJSON = json {
// Okay, the parsedJSON is here, let's get the value for 'success' out of it
var success = parseJSON["success"] as? Int
println("Succes: \(success)")
}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
}
}
})
task.resume()
}
call This Method Like This
self.post(["username":"jameson", "password":"password"], url: "http://localhost:4567/login")
Hope It Helps :)
Http body is missing. Example - setting string paramets as body
let paramString = String(format:"param1=%#&param2=%#",param1,param2)
request.httpBody = paramString.data(using: String.Encoding.utf8)
here just try
request.httpBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
func getData(searchString:String,completion:#escaping(Any)->Void){
let url = "https://itunes.apple.com/search?term="+searchString
URLSession.shared.dataTask(with: URL.init(string: url)!){(data,response,err) in
if let responsedata = data{
DispatchQueue.main.async {
completion(responsedata)
}
}
}.resume()
}
Try this: (Swift 4.2)
public func submitDelivery(delivery:DeliveryModal,responseCode:String,completion:#escaping SubmitCompletionBlock){
let urlString = BaseURL.getURL(urlType: .submit(responseCode))
guard let url = URL(string: urlString) else { return }
var request : URLRequest = URLRequest(url: url)
request.httpMethod = HttpMethod.post.rawValue
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let encoder = JSONEncoder()
encoder.outputFormatting = .prettyPrinted
do {
let jsonData = try encoder.encode(delivery)
request.httpBody = jsonData
} catch {
print(error.localizedDescription)
completion(nil,nil,NSError.init())
}
let dataTask = URLSession.shared.dataTask(with: request) {
data,response,error in
guard let data = data else {
completion(nil,response,NSError.init())
return
}
do {
let data = try JSONDecoder().decode(DeliverySubmitResponseModal.self, from: data)
DispatchQueue.main.async {
completion(data,response,error)
}
} catch let error {
debugPrint(error.localizedDescription)
}
}
dataTask.resume()
}

Parse JSON response with Swift 3

I have JSON looking like this:
{"posts":
[
{
"id":"1","title":"title 1"
},
{
"id":"2","title":"title 2"
},
{
"id":"3","title":"title 3"
},
{
"id":"4","title":"title 4"
},
{
"id":"5","title":"title 5"
}
],
"text":"Some text",
"result":1
}
How can I parse that JSON with Swift 3?
I have this:
let url = URL(string: "http://domain.com/file.php")!
let request = URLRequest(url: url)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data else {
print("request failed \(error)")
return
}
do {
if let json = try JSONSerialization.jsonObject(with: data) as? [String: String], let result = json["result"] {
// Parse JSON
}
} catch let parseError {
print("parsing error: \(parseError)")
let responseString = String(data: data, encoding: .utf8)
print("raw response: \(responseString)")
}
}
task.resume()
}
Use this to parse your data:
let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String:Any]
let posts = json["posts"] as? [[String: Any]] ?? []
print(posts)
} catch let error as NSError {
print(error)
}
}).resume()
Use guard to check if you have data and that error is empty.
Swift 5.x version
let url = URL(string: "http://example.com/file.php")
URLSession.shared.dataTask(with:url!, completionHandler: {(data, response, error) in
guard let data = data, error == nil else { return }
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String:Any]
let posts = json?["posts"] as? [[String: Any]] ?? []
print(posts)
} catch {
print(error)
}
}).resume()
In swift 3.0 for GET method:
var request = URLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "GET"
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=\(String(describing: 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))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
In swift 3.0 for POST method:
var request = URLRequest(url: URL(string: "Your URL")!)
request.httpMethod = "POST"
let postString = "user_name=ABC" // Your parameter
request.httpBody = postString.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
print("error=\(String(describing: 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))")
}
let responseString = String(data: data, encoding: .utf8)
print("responseString = \(String(describing: responseString))")
}
task.resume()
Because your data structure of test json should be "[String: AnyObject]". The json key "posts" value is Array type.
DISTANCE--DIFFICULT API
========================>
class ViewController: UIViewController {
var get_data = NSMutableData()
var get_dest = NSArray()
var org_add = NSArray()
var row_arr = NSArray()
var ele_arr = NSArray()
var ele_dic = NSDictionary()
var dist_dic = NSDictionary()
var dur_dic = NSDictionary()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
getmethod()
}
func getmethod()
{
let url_str = URL(string: "https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&departure_time=1408046331&origins=37.407585,-122.145287&destinations=37.482890,-122.150235")
let url_req = URLRequest(url: url_str!)
let task = URLSession.shared.dataTask(with: url_req) { (data, response, error) in
if let my_data = data
{
print("my data is----->",my_data)
do
{
self.get_data.append(my_data)
let jsondata = try JSONSerialization.jsonObject(with: self.get_data as Data, options: [])as! NSDictionary
print("json data is--->",jsondata)
self.get_dest = jsondata.object(forKey: "destination_addresses")as! NSArray
let get_dest1:String = self.get_dest.object(at: 0) as! String
print("destination is--->",get_dest1)
self.org_add = jsondata.object(forKey: "origin_addresses")as! NSArray
let get_org:String = self.org_add.object(at: 0)as! String
print("original address is--->",get_org)
self.row_arr = jsondata.object(forKey: "rows")as! NSArray
let row_dic = self.row_arr.object(at: 0)as! NSDictionary
self.ele_arr = row_dic.object(forKey: "elements")as! NSArray
self.ele_dic = self.ele_arr.object(at: 0)as! NSDictionary
self.dist_dic = self.ele_dic.value(forKey: "distance")as! NSDictionary
print("distance text is--->",self.dist_dic.object(forKey: "text")as! String)
print("distance value is--->",self.dist_dic.object(forKey: "value")as! Int)
// self.ele_dic = self.ele_arr.object(at: 1)as! NSDictionary
self.dur_dic = self.ele_dic.value(forKey: "duration")as! NSDictionary
print("duration text--->",self.dur_dic.value(forKey: "text")as! String)
print("duration value--->",self.dur_dic.value(forKey: "value")as! Int)
print("status---->",self.ele_dic.object(forKey: "status")as! String)
}
catch
{
print("error is--->",error.localizedDescription)
}
}
};task.resume()
}

How to make rest api call with HTTP PUT method in swift

I have tried the below REST Api with PUT method.
Here is my code,
let url = NSURL(string: "http://sampleurl")
let request = NSMutableURLRequest(URL: url!)
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "PUT"
let session = NSURLSession(configuration:NSURLSessionConfiguration.defaultSessionConfiguration(), delegate: nil, delegateQueue: nil)
let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions(), error: nil)
let dataTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
//handle error
print("Parsed error: '\(error)'")
}
else {
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Parsed JSON: '\(jsonStr)'")
}
}
dataTask.resume()
It is not working. Please help me to find out where it is wrong.
This is a working code, I send your dictionary as a JSON formatted string to the server, and in the server, I parse the request and build another JSON object that contains the same values as the request, and send them back to the app. In the app, I parse the response and print the results:
let session = NSURLSession.sharedSession()
let url = "http://localhost:8080/yourServerGoesHere/putMethodTest"
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = "PUT"
let params:[String: AnyObject] = ["deviceId" : "device_1","mobileDeviceId" : "abcd","deviceType":"ios"]
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
let task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! NSHTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")
}
if let data = data {
do{
let jsonData = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
let deviceId = jsonData["deviceId"] as! String
let mobileDeviceId = jsonData["mobileDeviceId"] as! String
let deviceType = jsonData["deviceType"] as! String
print (" deviceId= \(deviceId), mobileDeviceId= \(mobileDeviceId), deviceType= \(deviceType)")
}catch _ {
print ("the response is not well JSON formatted")
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
}
If you want to try, this is the Java web service code:
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
#Path("/putMethodTest")
#PUT
#Consumes(MediaType.TEXT_PLAIN)
public Response putMethodTest(String requestString) {
JSONObject requestJSON = new JSONObject(requestString);
String deviceId = requestJSON.getString("deviceId");
String mobileDeviceId = requestJSON.getString("mobileDeviceId");
String deviceType = requestJSON.getString("deviceType");
JSONObject response = new JSONObject();
response.put("deviceId", deviceId);
response.put("mobileDeviceId", mobileDeviceId);
response.put("deviceType", deviceType);
return Response.ok().entity(response.toString()).build();
}
Define the put function like this :
//
// Put request
//
static func put(path: String, accessToken: Bool, data: Dictionary<String, AnyObject>, finish: (accessTokenX:String, data: JSON) -> ()) {
apiRequest("PUT", path: path, accessToken: accessToken, contentType: nil, data: data) { (accessTokenX:String, data: AnyObject) in
dispatch_async(dispatch_get_main_queue(), {
finish(accessTokenX:accessTokenX, data: JSON(data))
})
}
}
An example of use :
//
// Update informations of the profile
//
static func accountUpdate(profile: [String: AnyObject], finish: (accessTokenX:String, data: JSON) -> ()) {
let dataProfile = ["profile": profile]
API.put("/users/profile", accessToken: true, data: dataProfile) { accessTokenX, data in finish(accessTokenX:accessTokenX, data: data)
}
}
Try this!!!
http://jamesonquave.com/blog/making-a-post-request-in-swift/
func data_request()
{
let url:NSURL = NSURL(string: url_to_request)!
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
let paramString = "data=Hello"
request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
let task = session.dataTaskWithRequest(request) {
(
let data, let response, let error) in
guard let _:NSData = data, let _:NSURLResponse = response where error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print(dataString)
}
task.resume()
}

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