I need to send a request to the server like this
[{
"Case":"add",
"Table":"user",
"Field":["Email","Password"],
"Value":["a","a"],
"Duplicate":["Email"],
"SecureEncrpt":"Password",
"SecureDecrpt":"Password"
}]
and I'm using alamofire for the network process, and im using request structure like this
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as AnyObject
let parameters = loginparas as! Parameters
How can I get exactly like that format?
let loginparas = [
"Case": "add",
"Table":"user",
"Field":["Email","Password"],
"Value":[details,pass],
"Duplicate":["Email"],
"SecureEncrpt":"",
"SecureDecrpt":""
] as [String:Any]
Alamofire.request( url , method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers ).responseJSON { response in
if response.result.isSuccess {
guard let json = response.result.value as? NSArray else { return }
for j in json {
let jsonValur = j as? [String:Any]
let case = jsonValue["Case"] as? String
...
...
...
}
}
}
Related
I am creating array of dictionaries and then passing that in paramDictionary and sending to server but I get responseStatus code 422. I am using Alamofire 5.
Here is the structure of param which I have to send and it successfully working on postman but in app it is always fails
{"check_in": [{"check_in_at":"2020-02-26 03:23:44", "gps_coordinates":"3.1697998046875,101.61672197976593"},
{"check_in_at":"2020-02-26 03:23:45","gps_coordinates":"3.1697998046875,101.61672197976593"}]}
Here is my code
func postCheckInApi(viewController: UIViewController,
completion:#escaping (_ result:SuccessErrorData)->(),
errorHandler:#escaping (_ result:Error,_ statusCode:Int?)->()//error handler
) {
let url = KCheckin
let geoArr = Constant.getSearchLocationHistory() ?? [GeoTaggingEntity]()
var arr = [[String: String]]()
for i in geoArr{
let dict: [String : String] = ["gps_coordinates" : i.gps_coordinates ?? "", "check_in_at" : i.check_in_at]
arr.append(dict)
}
let parameterDictionary = ["check_in": arr] as [String : Any]
print(parameterDictionary)
let headers: HTTPHeaders = [
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": Constant.getBearerToken() ?? ""
]
AF.request(url, method: .post, parameters: parameterDictionary, headers: headers).responseData { response in
switch response.result{
case.success(let data):
do{
let jsonData = try JSONDecoder().decode(SuccessErrorData.self, from: data)
print("Success")
completion(jsonData)
}
catch{
//viewController.navigationController?.popToRootViewController(animated: true)
}
case .failure(let error):
print(error)
}
}
}
You can not add Array as parameter object to your paramDictionary. You need to covert your Array to json string and then add it to you paramDictionary.
For that use below Collection extension to convert your Array to Json String
extension Collection {
func json() -> String? {
guard let data = try? JSONSerialization.data(withJSONObject: self, options: []) else {
return nil
}
return String(data: data, encoding: String.Encoding.utf8)
}
}
How To Use
let jsonStr = yourArray.json()
add this jsonStr to your paramDictionary
I am trying to send POST HTTP request with body using Alamofire and would appreciate any help.
My body:
{"data":{"gym":{"country":"USA","city":"San Diego","id":1}}}
Should I do something like this?
let parameters: [String: Any] = [ "data": [
"gym": [
"country":"USA",
"city":"San Diego",
"id":1
]]]
Alamofire.request(URL, method: .post, parameters: parameters, headers: headers())
.responseJSON { response in
print(response)
}
If you wish to send the parameters in json format use encoding as JSONEncoding. So add parameter for encoding in request as follows:
Alamofire.request(URL, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers())
.responseJSON { response in
print(response)
}
Hope it helps...
Try this method to convert your json string to dictionary
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
let str = "{\"data\":{\"gym\":{\"country\":\"USA\",\"city\":\"San Diego\",\"id\":1}}}"
let dict = convertToDictionary(text: str)
and send dictionary as a param in your request.
Alamofire.request(URL, method: .post, parameters: dict, headers: headers())
.responseJSON { response in
print(response)
}
ref : How to convert a JSON string to a dictionary?
What I think is that you should try and prepare your dictionary in the this format:
var gym = [String:Any]()
gym["country"] = "USA"
gym["city"] = "San"
var data = [[String:Any]]()
data.append(gym)
var metaData = [String:Any]()
metaData["data"] = data
Your parameters is wrong...
let parameters: [String: Any] = { "data":
{
"gym": {
"country":"USA",
"city":"San Diego",
"id":1
}
}
}
Alamofire.request(<YOUR-URL>,
method: .post,
parameters: parameters,
encoding: URLEncoding(destination: .queryString),
headers: <YOUR-HEADER>
).validate().responseString { response in
switch response.result {
case .success:
debugPrint("Good to go.")
debugPrint(response)
case .failure:
let errMsg = String(data: response.data!, encoding: String.Encoding.utf8)!
debugPrint(errMsg)
debugPrint(response)
}
}
Hope this help. BTW, in Alamofire 5, debugPrint(response) can print out response.data directly.
You can use the httpBody property of URLRequest along with Alamofire Session request:
var req = try? URLRequest(url: url, method: method, headers: headers)
req?.httpBody = someJson
Alamofire.Session(configuration: .default).request(req!).validate().response { response in
// Handle the response
}
Postman api url added below.
Present code :
let baseUrl = "abc.com/search/"
let param = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
let headers = [
"Content-Type": "application/json"
]
Alamofire.SessionManager.default.request("\(baseUrl)field", method: .post,parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
print(response.request ?? "no request") // original URL request
if(response.response?.statusCode != nil){
print("done")
if self.checkResponse(response.response!.statusCode){
let json = JSON(data: response.data!)
//print("at_LeadStop json \(json)")
return completionHandler(json, false)
} else {
return completionHandler(JSON.null, true)
}
} else {
print("gone")
return completionHandler(JSON.null, true)
}}
I don't know how to add body request through this code. Please help me to slove this problem.
You are mixing two things here, page,size and sortBy is you need to pass with the url string as query string. Now your body is request is JSON Array and you can post array with Alamofire only using URLRequest. So try like this.
let baseUrl = "abc.com/search/"
let queryStringParam = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
//Make first url from this queryStringParam using URLComponents
var urlComponent = URLComponents(string: baseUrl)!
let queryItems = queryStringParam.map { URLQueryItem(name: $0.key, value: $0.value) }
urlComponent.queryItems = queryItems
//Now make `URLRequest` and set body and headers with it
let param = [
[
"fieldName" : "abc",
"fieldValue":"xyz"
],
[
"fieldName" : "123",
"fieldValue":"789"
]
]
let headers = [ "Content-Type": "application/json" ]
var request = URLRequest(url: urlComponent.url!)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: param)
request.allHTTPHeaderFields = headers
//Now use this URLRequest with Alamofire to make request
Alamofire.request(request).responseJSON { response in
//Your code
}
Try this: Using Custom Encoding
struct JSONStringArrayEncoding: ParameterEncoding {
private let array: [[String : Any]]
init(array: [[String : Any]]) {
self.array = array
}
func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
var urlRequest = try urlRequest.asURLRequest()
let data = try JSONSerialization.data(withJSONObject: array, options: [])
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil {
urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
}
urlRequest.httpBody = data
return urlRequest
}
}
Calling
let values = [
[
"fieldName" : "abc",
"fieldValue":"xyz"
],
[
"fieldName" : "123",
"fieldValue":"789"
]
]
let param = [
"page":"1",
"size":"5",
"sortBy":"profile_locality"
]
let parameterEncoding = JSONStringArrayEncoding.init(array: values)
Alamofire.request("url", method: .post, parameters: param, encoding:parameterEncoding ).validate().response { (responseObject) in
// do your work
}
I don't know why my code doesn't work, my result is always nil.
I integrated alamofire and swiftyjson this is my code:
let urlString = "myurl"
let params: Parameters = [
"accessProvider": AccessProvider,
"inputToken": AccessToken
]
Alamofire.request(urlString, method: .post, parameters: params, encoding: URLEncoding.httpBody)
.responseJSON { response in
if let responseObject = response.result.value {
print("JSON: \(responseObject)")
let json = JSON(responseObject)
let path: [JSONSubscriptType] = ["user","id"]
let name = json[path].string
print("AAAAA")
print(name)
}
}
I can read the first part of user but the second one with id is always nil.
this is the response json:
{
"responseCode": 0,
"responseDescription": "OK",
"user": "{"id":"MAIL",
"nickname":"MYNAME",
"level":"U",
"status":"A",
"sex":null,
"ageGroup":null,
"address":null,
"latitude":null,
"longitude":null,
"creation_timestamp":"2017-05-10 18:40:21",
"notification":"1",
"last_login":"2017-05-11 18:32:07",
"mobilePreference":null,
"sport":null,
"spot":null,
"token":"LONGTOKENID"}"
}
Thank you vadian,
i solved the question with your indication,
if anyone have the same problem you can solve like this:
//Initialize the first json:
let json = JSON(responseObject)
//Extract the second Json to String
let path: [JSONSubscriptType] = ["user"]
let name = json[path].string
//Initialize the second json from string
if let dataFromString = name?.data(using: .utf8, allowLossyConversion: false)
let jsonuser = JSON(data: dataFromString)
//Access to the data
Thank you all,
Have nice day.
I'm using Alamofire for my Rest (POST) request and getting JSON response seamlessly. But i can access only response body. I want to get response headers. Isn't it possible when using Alamofire?
Here is my code snippet:
#IBAction func loginButtonPressed(sender: UIButton) {
let baseUrl = Globals.ApiConstants.baseUrl
let endPoint = Globals.ApiConstants.EndPoints.authorize
let parameters = [
"apikey": "api_key_is_here",
"apipass": "api_pass_is_here",
"agent": "agent_is_here"
]
Alamofire.request(.POST, baseUrl + endPoint, parameters: parameters).responseJSON {
(request, response, data, error) in let json = JSON(data!)
if let result = json["result"].bool {
self.lblResult.text = "result: \(result)"
}
}
}
As response is of NSHTTPURLResponse type, you should be able to get the headers as followed:
response.allHeaderFields
Here is how to access the response headers in Swift 3:
Alamofire.request(.GET, requestUrl, parameters:parameters, headers: headers)
.responseJSON { response in
if let headers = response.response?.allHeaderFields as? [String: String]{
let header = headers["token"]
// ...
}
}
This code gets response header in Swift 4.2
Alamofire.request(pageUrlStr, method: .post, parameters: Parameter, encoding: URLEncoding.httpBody, headers: nil).responseJSON
{ response in
//to get JSON return value
if let ALLheader = response.response?.allHeaderFields {
if let header = ALLheader as? [String : Any] {
if let cookies = header["Set-Cookie"] as? String {
UserDefaults.standard.set(cookies, forKey: "Cookie")
}
}
}
}