I have this JSON:
{
"myData" : [
[
{
"text" : "lorem ipsum",
"id" : "myId"
}
]
]
}
And I want to get "text" and "id" values with SwiftyJSON.
My code:
Alamofire.request(url, method: .post, parameters: parameters, encoding: URLEncoding(destination: .httpBody), headers: headers).responseJSON { (response) in
switch response.result {
case .success(let value):
let json = JSON(value)
let id = json //json["myData"]["id"]... how get "id" ?
print(id)
}
It looks like you're accessing an array of arrays so you'll need to subscript out the elements you want like let id = json["myData"][0][0]["id"].
Related
Alamofire.request("https://test.com", method: .post, parameters: d, encoding: JSONEncoding.default)
.responseJSON { response in
print(response)
}
I am using the above method to send post request using Alamofire. Here "d" is the JSON variable. But an error comes saying extra arguement method in call. Why is it happening.
Try to send parameters like this:
let params: [String: Any] = [Key 1: value1, Key 2: value2]
This is the correct format.
Parameters in your case d must be of type : [String: Any]
let d: [Sting: Any] = [
"some key": some value,
"some key": some value,
]
Alamofire.request("url", method: .post, parameters: d)
.validate()
.responseJSON {
(response) in
}
I am trying to send following JSON data. I am using Alamofire 4.0.
How to pass Data to the server in form-data format?
{
"apikey" : "455feh54b",
"action": "ADD",
"address1" : "Mumbai",
"country" : "India"
"userInfo" : {
"user_detail" :[
{
"name" : "abc",
"age" : 15,
"location" : "Delhi"
},
{"name" : "pqr",
"age" : 20,
"location" : "Mumbai"
}
]
}
}
Here is how you can simply send it
let user_detail = ["name":name, "age":age, "location":location]
let userInfo = ["user_detail": user_detail]
let params = ["apikey":title,
"action":type,
"address":time,
"userInfo":String.JSONStringify(value: user_detail as AnyObject)]
Alamofire.request(url, method:.post, parameters: params, encoding: URLEncoding.default).validate().responseAuthJSON {
response in
switch response.result {
case .failure(let error):
print(error)
self.showAlert(title: "Saving note failed! Please, try again.", message: "")
case .success(let responseObject):
print("response is success: \(responseObject)")
}
}
As they've documented here.You can pass JSON data like following.
let parameters: Parameters = [
"foo": [1,2,3],
"bar": [
"baz": "qux"
]
]
// Both calls are equivalent
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)
Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))
// HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
let param : Parameters = [
"id":62393,
"userName": "Furkan",
"isActive":true,
]
let header : HTTPHeaders = [Value :"Key"]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in Body {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
to: urlStr,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
print(response as Any)
}
.uploadProgress { progress in // main queue by default
}
return
case .failure(let encodingError):
debugPrint(encodingError)
}
})
Please try this for post form data using Alamofire
let param : Parameters = [
"id":62393,
"userName": "Furkan",
"isActive":true,
]
let header : HTTPHeaders = [Value :"Key"]
Alamofire.upload(
multipartFormData: { multipartFormData in
for (key, value) in Body {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
}
},
to: urlStr,
headers: header,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseString { response in
print(response as Any)
}
.uploadProgress { progress in // main queue by default
}
return
case .failure(let encodingError):
debugPrint(encodingError)
}
})
Please try this for post form data using Alamofire
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 }
I have a dictionary with key as username and value as email. Which i would like to send to an api using Alamofire i have no clue how to approach this problem as i am suppose to send multiple users to the api to save at once.
Dictionary
var selectedMembers = [String: String]()
The data saved in this dictionary is appended in a different VC from a table view where we can choose how many users we want to append in the dictionary.
Now i need to convert this dictionary into json formate to send to the api through alamofire.
Json Formate
"users": [
{
"user_email": "abc#gmail.com",
"user_name": "abc"
},
{
"user_email": "abc2#gmail.com",
"user_name": "abc2"
}
]
Alamofire Code
let parameters: Parameters = [
"users" : [
[
"user_name" : "user_name goes here",
"user_email" : "user_email goes here"
]
]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
How i solved the Problem
i created a function that prints the the data how i want it and placed it in Alamofire parameters something like this.
var selectedMembers = [String: String]()
var smembers = [AnyObject]()
var selected = [String: String]()
if selectedMembers.isEmpty == false {
for (key, value) in selectedMembers {
selected = ["useremail": key, "catagory": value]
smembers.append(selected as AnyObject)
}
}
let jsonData = try? JSONSerialization.data(withJSONObject: smembers, options: JSONSerialization.WritingOptions())
let jsonString = NSString(data: jsonData!, encoding: String.Encoding.utf8.rawValue)
let parameters: Parameters = [
"users" : jsonString as AnyObject
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
You just need to make Array of dictionary(user) as of currently you are setting user's value as Dictionary instead of Array.
let parameters: Parameters = [
"users" : [
[
"user_name" : "abc",
"user_email" : "abc#gmail.com"
],
[
"user_name" : "abc2",
"user_email" : "abc2#gmail.com"
]
]
]
Alamofire.request("\(baseURL)", method: .post, parameters: parameters).responseJSON { response in
}
If your web API demands the post data to send in JSON format then below written method is a way to do this.
func calltheAPIToSendSelectedUser () {
let parameters: [String: Any] = [
"users" : [
[
{
"user_name" : "user1_name goes here",
"user_email" : "user1_email goes here"
},
{
"user_name" : "user2_name goes here",
"user_email" : "user2_email goes here"
},
{
"user_name" : "user3_name goes here",
"user_email" : "user3_email goes here"
},
]
]
]
var request = URLRequest(url: URL(string: "YourApiURL")!)
request.httpMethod = "POST"
request.httpBody = try! JSONSerialization.data(withJSONObject: parameters, options: [.prettyPrinted])
Alamofire.request(request).responseJSON { response in
}
}
Here's my solution that worked for invoking POST using Alamofire and passing in an array of dictionary values as the Parameters arg.
Notice the 'User' key which contains a dictionary of values.
let dict: NSMutableDictionary = [:]
dict["facebook_id"] = "1234559393"
dict["name"] = "TestName"
dict["email"] = "TestEmailID"
let params: Parameters = [
"user": dict
]
Alamofire.request("YOURURL", method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON(completionHandler: { (response) in
switch response.result {
case .success:
print("succeeded in making a Facebook Sign up REST API. Now going to update user profile"
break
case .failure(let error):
return
print(error)
}
})
Right at the point where you are adding items to the dictionary, is where you can check for nil values and avoid adding as needed, thus making it dynamic.
I am using alamofire and swiftyjson to get it. I need to get string "ubus_rpc_session", I tryed this way, but I get an array, I need to get string. Could you help me?
Alamofire.request(URL, method: .post, parameters: param, encoding: JSONEncoding.default).responseJSON { response in
switch response.result {
case .success(let value):
let json = JSON(value)
let token = json["result"].arrayValue.map({$0["ubus_rpc_session"].stringValue})
print(token)
{ "jsonrpc":"2.0",
"id":1,
"result":[
0,
{
"ubus_rpc_session":"07e111d317f7c701dc4dfde1b0d4862d",
"timeout":300,
"expires":300,
"acls":{
"access-group":{
"superuser":[
"read",
"write"
],
"unauthenticated":[
"read"
]
},
"ubus":{
"*":[
"*"
],
"session":[
"access",
"login"
]
},
"uci":{
"*":[
"read",
"write"
]
}
},
"data":{
"username":"root"
}
}
]
}
Try this
//Getting an array of string from a JSON Array(In their documents)
let arrayNames = json["users"].arrayValue.map({$0["name"].stringValue})
if let tempArray = json["result"].arrayValue {
for item in tempArray {
print(item)
if let title = item["ubus_rpc_session"].string {
println(title)
}
}
}
Or check this
let value = tempArray[1].dictionaryObject!
print(value["ubus_rpc_session"]!)