Retrieving json data from http request in swift - ios

I'm new to swift and thus the question. I want to wrap my http calls into a function of this signature.
func httpPost()-> Any
This code works but how can I wrap this code in the functio signature I want.
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let parameters = [
"client_id": "xxx",
"client_secret": "yyy"
] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {return}
do{
try validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])
}catch{
print(error)
}
//print(String(describing: data))
}
dataTask.resume()
I want to return the json object as Any here

You can't return a direct value in an asynchronous function until you block the thread which is a bad idea , so you want a completion
func httpPost(completion:#escaping(_ ret:Any?,err:Error?) -> Void)
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let parameters = [
"client_id": "xxx",
"client_secret": "yyy"
] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
var request = URLRequest(url: URL(string: "http://xxx.xxx")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {
completion(nil,error)
return
}
do{
try validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])
completion(json,nil)
}catch{
print(error)
completion(nil,error)
}
//print(String(describing: data))
}
dataTask.resume()
}
To call
httpPost { (json,error) in
print(json)
}
also it's better to cast the json as [Any] / [String:Any] for Array/ Dictionary response respectively

Related

How to add post api request in parameters while parsing in swift

This is my api request:
{
"billDetails": {
"billerId":"EPDCLOB00AN232",
"customerParams":[{"name":"Service Number","value":"116515M025033"}]
}
}
here is code:
func billerFetchService(){
let parameters = ["billDetails": {
"billerId" : "EPDCLOB00ANP01",
"customerParams" : [{"name":"Service Number","value":"116515M025007621"}]
}
] as [String : Any]
let url = URL(string: "https://app.com/Fetch/fetch")
var req = URLRequest(url: url!)
req.httpMethod = "POST"
req.addValue("application/json", forHTTPHeaderField: "Contet-Type")
req.addValue("application/json", forHTTPHeaderField: "Accept")
guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) else {return}
req.httpBody = httpBody
let session = URLSession.shared
session.dataTask(with: req, completionHandler: {(data, response, error) in
if response != nil {
// print(response)
}
if let data = data {
do{
var json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as! [String: Any]
print("fetching json \(json)")
}catch{
print("error")
}
}
}).resume()
}
if i add like this in parameters error
Consecutive statements on a line must be separated by ';'
Insert ';'
Expected expression
Where i did mistake, please help me in code
You need
let parameters = ["billDetails": [
"billerId" : "EPDCLOB00ANP01",
"customerParams" : [["name":"Service Number","value":"116515M025007621"]]]]
Please make your parameter as this
let parameters = ["billDetails":
[
"billerId": "EPDCLOB00ANP01",
"customerParams" : ["name":"Service Number","value":"116515M025007621"]
]
] as [String : Any]

Unable to post parameters in post request ios swift

I'm trying to send these parameters as a post request to the URL but the parameters are not getting sent. I don't know whether is URLSession configuration issue. Can anyone check and solve the issue?
import UIKit
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var str = String(data: jsonData!, encoding: .utf8)
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "Post"
request.httpBody = str!.data(using: .utf8)
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
Check with this:
func post method(){
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"]
let parameters = ["set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as! Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
}
guard let httpresponse = response as? HTTPURLResponse,
(200...299).contains(httpresponse.statusCode) else {
print ("server error")
return
}
if let mimeType = response?.mimeType,
mimeType == "application/json",
let data = data,
let dataString = String(data: data, encoding: .utf8) {
print ("got data: \(dataString)")
}
}
})
dataTask.resume()
}
I used an online service called RequestBin to inspect your request and data seem to be sent correctly. I only did minor modifications as already mentioned in the comment.
This was the resulting code:
let json: [String: Any] = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let jsonData = try! JSONSerialization.data(withJSONObject: json)
let url = URL(string: "http://requestbin.fullcontact.com/***")! // Was "using"
var request = URLRequest(url: url)
request.httpMethod = "POST" // Was "Post"
request.httpBody = jsonData // Was utf8 string representation
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
You can check inspected result using this service. You simply create a new URL and use it in your request. After you have successfully sent the request all you do is reload the page to inspect your request.
Note that these are "http" requests so you need to allow arbitrary loads.
You may set your request like following and change content type according to your need
import UIKit
let json: [String: Any]? = [
"set_id" : "20",
"user_id" : "30",
"type" : "contact",
"contact_name" : "shinto"
]
let url = URL(string: "****.php")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
if let parameters = json
{
self.makeParamterString(request: request, parameterDic: parameters)
}
let session = URLSession(configuration: .default)
let task = session.dataTask(with: request) {
(data, response, error) in
if let data = data {
if let postResponse = String(data: data, encoding: .utf8) {
print(postResponse)
}
}
}
task.resume()
static func makeParamterString(request:NSMutableURLRequest, parameterDic:[String:AnyObject])
{
let _ = NSCharacterSet(charactersIn:"=\"#%/<>?#\\^`{|}").inverted
var dataString = String()
for (key, value) in parameterDic {
dataString = (dataString as String) + ("&\(key.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)=\(value)")
}
dataString = dataString.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)!
request.httpBody = dataString.data(using: String.Encoding.utf8)
}

how to make post request with row http body using swift as postman request test?

request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
let httpbody = object.data(using: String.Encoding.utf8)
request.httpBody = httpbody
You can directly generate a code from postman itself. Also, for your reference, you can call post request with row body as given below.
let headers = [
"content-type": "application/json",
"cache-control": "no-cache"
]
let parameters = ["order": ["line_items": [
["variant_id": 18055889387589,
"quantity": 1]
]]] as [String : Any]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
if let data = postData {
let request = NSMutableURLRequest(url: NSURL(string: "http://")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = data as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error?.localizedDescription ?? "")
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse?.statusCode ?? 0)
let reponseData = String(data: data!, encoding: String.Encoding.utf8)
print("responseData: \(reponseData ?? "Blank Data")")
}
})
dataTask.resume()
}
Let me know if you have any query.
Thanks.

How to call Async task in Swift?

I'm new to Swift and hence the question, I'm trying to wrap http calls into a function to reuse, however since it takes a completion block, I'm not sure how to call it. Here's my code,
func httpPost(_ path: String, _ parameters: [String: Any], completion:#escaping(_ ret:Any?,_ err:Error?) -> Void){
let headers = [
"Content-Type": "application/json",
"cache-control": "no-cache"
]
let postData = try? JSONSerialization.data(withJSONObject: parameters, options: [])
var request = URLRequest(url: URL(string: path)! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let dataTask = session.dataTask(with: request) { (data, response, error) -> Void in
guard let data = data else {
completion(nil,error)
return
}
do{
try self.validate(response)
let json = try JSONSerialization.jsonObject(with: data, options: [])
completion(json,nil)
}catch{
print(error)
completion(nil,error)
}
}
dataTask.resume()
}
My question is how do I call this function?
I would assume that the Xcode itself would suggest how calling this method should be implemented. If you tried to type "httpPo...", you should see the autocompletion list:
double click on it:
I would assume that the path and parameters are easy to understand, it issue could be related to the completion closure; What you could do is to double click on it, therefore:
And that's pretty much it! All you have to do for now is to fill it:
httpPost("your path", [: ]) { (response, error) in
// ...
}

post parameter to sever using dictionary swift

I am trying to send data to the server using a dictionary but unfortunately the data is not saving to the database (fields were found to be blank) and I am getting the below response:
Optional(["status": true, "msg": successfull])
And also tried to show UIActivityIndicator to user until he got a response but couldn't find a way.
Code attempted:
let dict = [ "key_one": self.tf1.text!,"key_two":self.tf2.text!]
do {
let jsonData = try NSJSONSerialization.dataWithJSONObject(dict, options: .PrettyPrinted)
// create post request
let url = NSURL(string: "myAPIUrl.php?")!
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "POST"
// insert json data to the request
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.HTTPBody = jsonData
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){ data, response, error in
if error != nil{
print("Error -> \(error)")
return
}
do {
let result = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [String:AnyObject]
print("Response -> \(result)")
} catch {
print("Inside Error Section -> \(error)")
}
}
task.resume()
} catch {
print(error)
}
// write this in one fucantion
let Username:NSString = EmailTextField.text! as NSString
let password:NSString = PasswordTextField.text! as NSString
let headers = [
"content-type": "application/json",
"cache-control": "no-cache",
"postman-token": "121b2f04-d2a4-72b7-a93f-98e3383f9fa0"
]
let parameters = [
"username": "\(Username)",
"password": "\(password)"
]
if let postData = (try? JSONSerialization.data(withJSONObject: parameters, options: [])) {
var request = NSMutableURLRequest(url: URL(string: "YOUR_URL_HERE")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData
let session = URLSession.shared
let task = URLSession.shared.dataTask(with: request as URLRequest) {
(data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
DispatchQueue.main.async(execute: {
if let json = (try? JSONSerialization.jsonObject(with: data!, options: [])) as? NSDictionary
{
let success = json["status"] as? Int
let message = json["message"] as? String
// here you check your success code.
if (success == 1)
{
print(message)
let vc = UIActivityViewController(activityItems: [image], applicationActivities: [])
present(vc, animated: true)
}
else
{
// print(message)
}
}
})
}
}
task.resume()
}

Resources