Sending JSONObject in Alamofire - ios

How can I send a JSON format like this using Alamofire 4.2.0 :
This is part from my script :
{
"session":{
"email": "user1#gmail.com",
"password": "secret123"
}
}
Thank you !

You can just struct your data in Dictionary and use JSONEncoding.default as encoding to send your request.
let mydata: [String: [String: String]] = [
"session": [
"email": "user1#gmail.com",
"password": "secret123"
]
]
Alamofire.request(url, method: .post, parameter: mydata, encoding: JSONEncoding.default, headers: nil)

Related

How to pass array of Object parameter to Alamofire swift

I'm new In Swift anyone help me.
I want to pass array of object to Alamofire and I don't know how to do that
Here is the parameter that required:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJfaWQiOiI1ZWU4OGZiNzhiYTBkMjMyZDFmYWZkMzgiLCJpYXQiOjE1OTIyOTk2Njh9.AVuxiTZy10fV2ZMZcT-oHXSg6PdK3tfE",
"zipCodes": [
{
"zip_code": "55001",
"city": "Afton",
"state": "MN",
"county": "Washington"
}
]
}
And I do that
let parameters : [String : String] = ["token" : retrivedToken, "zipCodes" : [{
"zip_code": "55001",
"city": "Afton",
"state": "MN",
"county": "Washington"
}]
]
Simply just use your parameter to your request.
func sendRequestRequest() {
// JSON Body
let parameters: [String : Any] = [
"token": retrivedToken,
"zipCodes": [
"county": "Washington",
"state": "MN",
"zip_code": "55001",
"city": "Afton"
]
]
// Fetch Request
Alamofire.request("your API url", method: .post, parameters: parameters, encoding: JSONEncoding.default)
.validate(statusCode: 200..<300)
.responseJSON { response in
if (response.result.error == nil) {
print("HTTP Response Body: \(response.data)")
}
else {
print("HTTP Request failed: \(response.result.error)")
}
}
}
Dont forget, if you use Alamofire v5, use AF.request instead of Alamofire.request
let bodyParams: [String : Any] = [
"token": "\(retrivedToken)",
"zipCodes":[
"county": "Washington",
"state": "MN",
"zip_code": "55001",
"city": "Afton"
]
]
}
let urlString = "abc.com"
Alamofire.request(urlString, method: .post, parameters: bodyParams ,encoding: JSONEncoding.default, headers: nil).responseJSON {
response in
switch response.result {
case .success:
print(response)
break
case .failure(let error):
print(error)
}
}

send json array to alamofire

product:[{"id":1,"qty":5,"price":5000},{"id":2,"qty":10,"price":7500}]
user_id:12
lon:112
lat:-7
lokasi:ada
tanggal:12-05-2019
How send that all parameter with Alamofire? Here is my attempt:
let par : [String:Any] = [ "product": productItem,
"user_id": myID(),
"lon":data["longitude"] ?? "",
"lat": data["latitude"] ?? "",
"lokasi":data["location"] ?? "",
"tanggal": data["tanggal"] ?? ""
]
let header = [
"Accept":"application/json",
"Content-Type":"application/json"
]
Alamofire.request("URL", method: .post,parameters: par,encoding: JSONEncoding.default, headers: header).responseJSON
{ response in
}
I don't know what should I do?

Alamofire: send parameter

I want to post data as parameter like this:
{
"data":
[
{
"nik" : "lalaal"
}
]
}
How do I write to these parameters in Swift 3 using Alamofire?
i tried :
let parameter: Parameters = [
"data":[[
"nik" : self.nik,
"check_type" : "IN",
"tanggal" : "01-08-2017 18:22:00",
"long" : String(locationList[projectChoosen].long!),
"lat" : String(locationList[projectChoosen].lat!),
"id_loc" : locationList[projectChoosen].id_project,
"id_project" : nil,
"nama_project" : locationList[projectChoosen].nama_project,
"barcode" : "",
"foto": "",
"mime_type" : "image/jpeg"
]]
]
You can use below code.
let dicRequest: NSDictionary = ["userid" : "test", "password" : "test123"]
let postParams:NSDictionary = [
"data": dicRequest
]
let requestURL: String = String(format: "%#/Login", serverURL)
Alamofire.request(requestURL, method: .post, parameters: postParams as? [String : AnyObject], encoding: JSONEncoding.default, headers: [:])
.responseJSON { response in switch response.result {
case .success(let JSON):
print("response :-----> ",response)
case .failure(let error):
print("Request failed with error: \(error)")
}
}
You can create a Dictionary object first in this formate
{
"data":
[
{
"nik" : "lalaal"
}
]
}
After that you can convert this using NSJSONSerlisation to json string
And than post using Almofire.
let array: [[String: String]] = [["nik": "lalaal"]]
let data = try JSONSerialization.data(withJSONObject: array, options: JSONSerialization.WritingOptions.prettyPrinted)
let string = String(data: data, encoding: String.Encoding.utf8)
let postParam: [String: String] = ["data": string]
let _ = Alamofire.request(apiType.url!, method: apiType.type!,parameters: postParam, encoding: JSONEncoding.prettyPrinted, headers: nil).validate(statusCode: 200..<500).responseJSON { (response) in
}
Here is a sample request using Alamofire and posting a dictionary as parameters:
let dataArray: [[String: String]] = [["nik": "lalaal"]]
let param: [String: [Any]] = ["data": dataArray]
Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }
I use :
let dataIn: [String: String] = ["param1": "value1"]
let paramGo: [String: [String: String]] = ["data_title": dataIn]
Alamofire.request(url, method: .post, parameters: paramGo, encoding: JSONEncoding.default, headers: nil).responseJSON { response in }

alamofire extra argument in call

Facing this issue from past 2 days. I have updated the pod, updated pod version from 4.0.1 to 4.5.0 but the problem is still the same.
here is my code:
var params: Parameters = [:]
params = [
"id": fetchFromCoreData(keyVlue: "trsptrRegistrationId") as AnyObject,
"mobileNumber": fetchFromCoreData(keyVlue: "mobileNO") as AnyObject,
"isNotification": isnotifyTag as AnyObject
]
print(params)
let auth_token = fetchFromCoreData(keyVlue: "Auth_Token")
let headers = [
"authKey": auth_token
]
print(headers)
let URL: String = GlobalUrls.BASE_URL + GlobalUrls.notifySetting
print(URL)
Alamofire.request(URL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers)
can you please try this way
var param :Parameters
param = [
"id": "Any id",
"mobileNumber": "any mobile number",
"isNotification": "is notification"
]
print(param)
let auth_token = "your auth_token"
let headers = [
"authKey": auth_token
]
print(headers)
let base_url: String = "Here is my base URL"
print(base_url)
Alamofire.request(base_url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: headers).responseJSON(completionHandler: {(resObj) -> Void in
print(resObj)
if resObj.result.isSuccess
{
print("Sucess result")
}
if resObj.result.isFailure
{
let error : Error = resObj.result.error!
print("Fail result")
print(error.localizedDescription)
}
})

Construction was too complex to be solved in reasonable time

I have problem with Swift 3, I am trying to send a request to a server and get JSON, but I get:
Construction was too complex to be solved in reasonable time.
I tried every way, but it doesn't worked.
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let parameters = [
"{\n",
" \"jsonrpc\": \"2.0\",\n",
" \"id\": \"1\",\n",
" \"method\": \"call\",\n",
" \"params\": [\n",
" \"0000000000000000\",\n",
" \"session\",\n",
" \"login\",\n",
" {\n",
" \"username\": \"" + userName + "\",\n",
" \"password\": \"" + password + "\"\n",
" }\n",
" ]\n",
"}"
]
let joiner = ""
let joinedStrings = parameters.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1", method: .post, parameters: parameters).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
Now I tryed to creat dic and convert to Json, but after that, I get problem on request there I declare my parameters. they say: use of unresolved identifier dictFromJSON
var userName = "root"
var password = "admin01"
//var LOGIN_TOKEN = 0000000000000000
let jsonObject: [String: Any] =
["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]
do {
let jsonData = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
// here "jsonData" is the dictionary encoded in JSON data
let decoded = try JSONSerialization.jsonObject(with: jsonData, options: [])
// here "decoded" is of type `Any`, decoded from JSON data
// you can now cast it with the right type
if let dictFromJSON = decoded as? [String:String] {
// use dictFromJSON
}
} catch {
print(error.localizedDescription)
}
// All three of these calls are equivalent
Alamofire.request("http://192.168.1.1/ubus", method: .post, parameters: dictFromJSON).responseJSON { response in
print("Request: \(response.request)")
print("Response: \(response.response)")
UPDATED:
According to the document of Alamofire, (you can see here), you don't need to convert the parameters Dictionary to JSON.
For example,
let parameters: Parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
// All three of these calls are equivalent
Alamofire.request("https://httpbin.org/post", parameters: parameters)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.default)
Alamofire.request("https://httpbin.org/post", parameters: parameters, encoding: URLEncoding.httpBody)
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
OLD:
You should use Dictionay for the parameter actually.
Therefore, instead of declaring the parameter like you did, you should do like this:
let parameters = ["jsonrpc" : 2.0,
"id": 1,
"method": "call",
"params": [ "00000000000000",
"session",
"login",
[ "username": userName,
"password": password]],
]

Resources