Swift Alamofire migration parsing JSON - ios

On migrating to recent versions am finding it hard to get and print the fields of name, age, and dob from JSON using Alamofire 4 parsing in Swift 3.
JSON FORMAT
"SetValues": {
"data":
[
{
"Name": yyyyy ,
"Age": 13,
"DOB": "2017-06-08",
}
{
"Name": xxxx ,
"Age": 33,
"DOB": "2015-06-08",
}
]
}
I tried
Alamofire.request(url!,
method: .post,
parameters: nil,
encoding: JSONEncoding.default,
headers: headers)
.responseJSON{ response in
let datamsg = jsonmsg?["SetValues"] as? [String : Any]
let dataset = datamsg?["data"] as? [String : Any]
let setValues = datamsg?["data"]
print (setValues[0]["Name"] as Any)
}

The problem is in this line
let dataset = datamsg?["data"] as? [String : Any]
as seen from the JSON response string it should be like below
let dataset = datamsg?["data"] as? [[String : Any]]
let name = dataset?[0]["Name"] as? String

Related

Send JSON with array of objects as parameter in Alamofire with swift

I am very new with Swift and Alamofire, what I want to accomplish is to send a data structure, like this:
{
"name" : "Test name",
"intention" : "Purpose of practice test",
"id_frequency" : "1",
"member": [
{
"id_member" : "1",
"email" : "member1#gmail.com",
"id_member_type" : 1
},
{
"id_member" : "4",
"email" : "member2#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "7",
"email" : "member3#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "5",
"email" : "member4#gmail.com",
"id_member_type" : 3
},
{
"id_member" : "6",
"email" : "member5#gmail.com",
"id_member_type" : 3
}
]
}
The way I am proceeding to structure the desired json, is as follows:
var membersArray = [AnyObject]()
for i in 0..<members.count {
let json: [String: Any] = [
"id_member": members[i].idMember!,
"email": members[i].email!,
"id_member_type": "\(Int(members[i].idMemberType)!)",
]
membersArray.append(json as AnyObject)
}
let jsonMembers = JSON(membersArray)
let jsonObject: [String: Any] = [
"member" : jsonMembers,
"name": name!,
"intention": intention!,
"id_frequency": frequency!
]
let jsonUpdate = JSON(jsonObject)
With this structured json, lines above (jsonUpdate). I proceed to execute the webService.
WevServices.createRequest(requestInfo: jsonUpdate) { (result) in
print(result)
}
My webservice method, looks like this:
static func createRequest(requestInfo: JSON, completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["name" : "\(requestInfo["name"])", "intention" : "\(requestInfo["intention"])", "id_frequency" : "\(requestInfo["id_frequency"])", "member": requestInfo["member"]]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}
}
I'm get an error from the server that the send data would not be correct.
Note: My application use Lumen as backend.
The best way for doing what you need is :
func JSONToString(json: [String : String]) -> String?{
do {
let mdata = try JSONSerialization.data(withJSONObject: json, options: JSONSerialization.WritingOptions.prettyPrinted) // json to the data
let convertedString = String(data: mdata, encoding: String.Encoding.utf8) // the data will be converted to the string
print("the converted json to string is : \(convertedString!)") // <-- here is ur string
return convertedString!
} catch let myJSONError {
print(myJSONError)
}
return ""
}
and for alamofire request do this :
static func createRequest(requestInfo: [String :String], completion: #escaping (_ result: String) -> Void){
let url = URL(string: "http://ws.someURL.com/CreateRequest")
let parameters: [String : Any] = ["request" : JSONToString(json : requestInfo)!]
Alamofire.request(url!, method: .post, parameters: parameters, encoding: URLEncoding.httpBody).responseString { response in
print(response)
}

Request to Alamofire

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
...
...
...
}
}
}

Trying to send json object in alamofire but it's going in a json array

I want my json request to be like:
{
"business_id": 1,
"images": [{
"image": "iVBORw0KGgoAAAANSUhEUgAAAHgAAACCCAYAAACNbQytAAAACXBIWXMAABcRAAAXEQHKJvM/AAAIJklEQVR4nO2dsY/lRhnAf0tWVKDdLuWtgZoNCaKwsO5dClMgdJvmFWnuBaHX3p6UgoosdKmyoUFnQPdSnoV0G4oUBikvcmQKEnKpoEFv7x9I9iQkKjgKz0uWy+2u57OfPfN5ft3uep5H+3u2P3/zzczWkydPcIG0rD63OPzTjXXkavYbHvfPIom/v9GeNGB76A6cY9fi2Osb60V3vDR0BwC+NnQHApslCFZOEKycIFg5QbBygmDlBMHKCYKVEwQrx6VMlg03Bjz3+wOe2xovBRdJvBzq3GlZDXVqEeEWrZwgWDlBsHKCYOUEwcoZneAoyw+G7kOfjEZwlOW7UZY/BB5EWT4buj99MQrBUZa/AJzyZT3VsfmdetQLNlfrJ8DOuV/vACdRltvUgXmJasFRli+Aexf8+Rpw0l9vhkGl4HPP21tXHHo9yvLjPvo0FOoEP+N5exW3NQdd6gQDS/7/eduEe1qDLo2CJ8J2S41BlzrBq/n0IfCaoOkO9dWvCnWCAVbz6QJ4R9B030TeavBywL8Jq/l0Zp6rTYOtNbeiLF+aL8mz+GW7nvXLlkOzCxt3pEjirSbHmWfqKfZBF8D3zO3ea1Teotes5tMzRh50qRYMIehSLxjGHXSNQjDUQReylQFu+ZzpGo1gwwR4LGjnbaZrVILHGHRtm9GUvr+dD1fz6WHP5wTqoCvK8te4eBjxItZBl1dX8jb1kJp338w2rObTRZTlE64eTnyafTMMOfQ48qTpgV5mstKy2i2S+KzNZ7TIdO0L2gyGr8/grq6gCbKgyxt8FXw9LatF2w9pGXR5ga+CAW6lZTVr+yEtMl1e4JJg0ftpWlato9oWmS7ncUmwdMbBMi2rvbY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ObTiW0jEzgtsbxzNN0ldZN4+QxezadHyKaMXBcGXdIVfgbHS8EG6bLD0qBLusLPoHgr2DxLxYujSTJdZoUfr/BWMMBqPj1FttfDDnDi416EtngtGMDMtJCs03GN4beo2zjeCwZYzafSdTpEQZdPOLN3oZko1gizus7THFLvDGq71NHtKMsfmr2T1OGMYOwmbX/l/XI1n56ZJIhkcbRjI7mL/SicQsUtek0Iur6KKsEQgq6nUScYWgVdu9quYpWCDbaZrncQlN26jlrBlpmuO6v5dKZNLigWDI2CrsfUy1KofRdWLRguDbo+pR4fXvbaoZ5RLxieGXStn7enw/SoP1xKdGyadaZrofmW/DSjEWwCKKdKWvtgFLfoMRMEKycIVk4QrJwgWDlBsHKCYOV4+R5s5gsFGuClYLrZPm8UhFu0coJg5QTBygmClRMEKycIVk4QrJwgWDlBsHJcymT9BPhOw2OHnCTmVdnP/wA1krVeyFFLQAAAAABJRU5ErkJggg=="
}]
}
i.e it is going as an array, i want it as a json object.
I am sending my parameters as:
let parameter = ["business_id" : business.id , "images" : business.imagearray ] as [String : Any]
And here is the code through which i am sending my request:
Alamofire.request(url, method: HTTPMethod.post, parameters:parameter , encoding: JSONEncoding.default, headers: Request.headers())
Appending images to image arraay:
for img in imageArraaay {
var dic = Dictionary<String, String>() dic = ["image":imgg] as Dictionary }
let jsonData = try! JSONSerialization.data(withJSONObject: myNewDictionary, options: []) as AnyObject
business.imageArray = NSString(data: jsonData as! Data, encoding: String.Encoding.utf8.rawValue)!
imagePicker.dismiss(animated: true, completion: nil)
}
I know i am making some mistake, I am new to IOS so any help is highly appreciated.
Possibly This should Work for you:
let imageArray = ["iVBORw0KGgoAAAANSUhEUg12345","iVBORw0KGgoAAAANSUhEUgAAAHgAAACCCAYAAAC6789"] //Dummy content
print(imageArray)
var ImgParam = [[String:String]]()
for img in imageArray {
print(img)
ImgParam.append(["image":img])
}
print(ImgParam)
let parameter = ["business_id" : 1 , "images" : ImgParam ] as [String : Any]
print(parameter)
Here is the logic to append base64 data into imageAarray:
var encodedString = String()
let imageData : NSData = UIImageJPEGRepresentation(image, 0) as! NSData
encodedString = imageData.base64EncodedString(options: .lineLength64Characters)
var baseDataDictionary = Dictionary<String , String>()
baseDataDictionary.updateValue(encodedString, forKey: "image")
imagesList.append(baseDataDictionary) // imageList is array of dictionaries
Here how I pass parameters and fire request:
let parameter = ["business_id" : businessId , "images" : imageList] as [String : Any]
Alamofire.request(url, method:.post, parameters: parameter , encoding: URLEncoding.default, headers: Request.headers())

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 }

Converting Dictionary to Json to pass parameters in Alamofire

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.

Resources