{
"firstName": "AA",
"lastName": "BB,
"shortName": "CC",
"nric": "12/AAA(N)123456",
"gender": "F",
"dob": "1.1.2000",
"password": "admin123",
"photo": {
"image": "hello",
"thumb": "world"
}
}
Is there anyway how to add photo array in main array? I've done as follow
let photoArray = [
"image": imageBase64,
"thumb": imageBase64
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
but output is awful. Please let me how to do it.
Instead of making the param let make it var and do the following. You do need to specify the dictionary type as below
let photoArray : [String : AnyObject] = [
"pic" : "myPhoto"
]
var param : [String : AnyObject] = [
"name" : "UserName"
]
param["photo"] = photoArray
let photoArray = [[
"image": "a",
"thumb": "b"],[
"image": "a",
"thumb": "b"]
]
let param = [
"firstName": txtFirstName.text as! AnyObject,
"lastName": txtLastName.text as! AnyObject,
"shortName": txtShortName.text as! AnyObject,
"nric":"",
"gender": genderCode,
"dob":txtDOB.text as! AnyObject,
"photo": photoArray
]
Hope you want like this.
let photoArray:[String:UIImage] = [
"image": UIImage.init(named: "a.png")!,
"thumb": UIImage.init(named: "b.png")!
]
let param:[String:AnyObject] = [
"firstName": "AA",
"lastName": "BB",
"shortName": "CC",
"nric": "",
"gender": 0,
"dob": "DD",
"photo": photoArray
]
You can do it like this
Related
I am new ios development, I am trying add JsonObject to array and send to as a Parameter value to Alamofire, but When I try it, I give this error Cannot convert value of type '[[String : Any]]' to expected argument type '[String : Any]' What am I to do?
#State var attendeeData = [[String: Any]]()
let parameters: [String: Any] = [
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
]
let parameters: [String: Any] = [
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
]
attendeeData.append(parameters)
attendeeData.append(parameters2)
addAttendeeService(parameter: attendeeData)
private func addAttendeeService(parameter: [String: Any]){
DispatchQueue.global().async {
AF.request("http://178.18.200.116:96/api/SessionPerson/Add",method: .post,parameters: parameter, encoding: JSONEncoding.default).response{ response in
debugPrint(response)
}
Array Object: When I try do this sWift doesn't accept this format
let parameters: [String: Any] = [
{
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
},
{
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
}
]
Simply changed your { } into [] that will solve your issue.
let parameters: [String: Any] = [
[
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
],
[
"firstName": atd1FirstName,
"lastName": atd1LastName,
"email": atd1Email,
"telNo": atd1Phone,
"nationality": atd1Nationatility,
"licenseNumber": atd1LicenseNumber,
"companyName": atd1CompanyName,
"sessionID": 0,
"sessionDetailID": 0,
"url": ""
]
]
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I want to get data from Json and put it in the table and display it from the API via Alamofire through the 'Post' process that has parameters containing the page number
I want get "results" ..
{
"responseCode": 200,
"message": null,
"status": true,
"results": [
{
"id": 971,
"title": "ST201972362",
"cdate": "07/31/2019",
"summary": "test",
"address": "",
"timer": "77876203",
"lat": "31.515934",
"lng": "34.4494066",
"source": "2",
"CreatedOn": "2019-07-31T13:38:46.927",
"done_940": null
},
{
"id": 970,
"title": "ST201972356",
"cdate": "07/30/2019",
"summary": "ov",
"address": "",
"timer": "0",
"lat": "31.5159315",
"lng": "34.4493925",
"source": "2",
"CreatedOn": "2019-07-30T15:26:00.077",
"done_940": null
},
{
"id": 964,
"title": "ST201972341",
"cdate": "07/29/2019",
"summary": "تجربة بلاغ ",
"address": "",
"timer": "0",
"lat": "21.5066086",
"lng": "39.1758587",
"source": "2",
"CreatedOn": "2019-07-29T19:06:58.817",
"done_940": null
},
{
"id": 959,
"title": "ST201972820252314",
"cdate": "07/28/2019",
"summary": "اااااا",
"address": "",
"timer": "0",
"lat": "21.5066716",
"lng": "39.1758483",
"source": "1",
"CreatedOn": "2019-07-28T11:45:02.493",
"done_940": null
},
{
"id": 957,
"title": "ST201972312",
"cdate": "07/28/2019",
"summary": "تمتمتم",
"address": "",
"timer": "0",
"lat": "31.5397884",
"lng": "34.4544891",
"source": "2",
"CreatedOn": "2019-07-28T08:56:43.577",
"done_940": null
},
{
"id": 956,
"title": "ST201972312",
"cdate": "07/28/2019",
"summary": "لا تنام",
"address": "",
"timer": "0",
"lat": "31.5397238",
"lng": "34.4540829",
"source": "2",
"CreatedOn": "2019-07-28T08:56:00.15",
"done_940": null
},
{
"id": 955,
"title": "ST201972311",
"cdate": "07/28/2019",
"summary": "تجربه جديد",
"address": "",
"timer": "0",
"lat": "31.5395001",
"lng": "34.4542211",
"source": "2",
"CreatedOn": "2019-07-28T08:52:09.81",
"done_940": null
},
{
"id": 953,
"title": "ST201972309",
"cdate": "07/28/2019",
"summary": "يلا",
"address": "",
"timer": "0",
"lat": "31.5110196",
"lng": "34.4784933",
"source": "2",
"CreatedOn": "2019-07-28T05:30:29.647",
"done_940": null
},
{
"id": 952,
"title": "ST201972309",
"cdate": "07/28/2019",
"summary": "ماك ١",
"address": "",
"timer": "0",
"lat": "31.5110291",
"lng": "34.4785841",
"source": "2",
"CreatedOn": "2019-07-28T05:29:09.943",
"done_940": null
},
{
"id": 949,
"title": "ST201972307",
"cdate": "07/28/2019",
"summary": "مرحبا",
"address": "",
"timer": "0",
"lat": "31.5443154",
"lng": "34.4585304",
"source": "2",
"CreatedOn": "2019-07-28T00:20:42.753",
"done_940": null
}
],
"done_940": "2/811"
}
You can follow some steps:
Step 1: need to create model
struct ResultObject {
var responseCode: Int?
var message: String?
var status: Bool?
var result: [Result]
public init(response: [String: Any]) {
self.responseCode = response["responseCode"] as? Int
self.message = response["message"] as? String
self.status = response["status"] as? Bool
let results = response["result"] as! [[String: Any]]
self.result = []
for item in results {
let result = Result(result: item)
self.result.append(result)
}
}
struct Result {
var id: String?
var title: String?
var cdate: String?
var summary: String?
var address: String?
var timer: String?
var lat: String?
var lng: String?
var source: String?
var CreatedOn: String?
var done_940: String?
public init(result: [String: Any]) {
self.id = result["id"] as? String
self.title = result["title"] as? String
self.cdate = result["cdate"] as? String
self.summary = result["summary"] as? String
self.address = result["address"] as? String
self.timer = result["timer"] as? String
self.lat = result["lat"] as? String
self.lng = result["lng"] as? String
self.source = result["source"] as? String
self.CreatedOn = result["CreatedOn"] as? String
self.done_940 = result["done_940"] as? String
}
}
}
Step 2: You check response from Alamofile
if you get json then
let test = ResultObject(response: responseJson)
print(test)
incase you get response is type Response you must convert into json
let responseJSON = try? JSONSerialization.jsonObject(with: response.data, options: [])
if let responseJSON = responseJSON as? [String: Any] {
let test = ResultObject(response: responseJSON)
print(test)
}
Let me know when you have some other problems.
I'm new here. How to write and turn the code below into postString as I need to do submisson to API.
{
"service": 0,
"size": "string",
"orderReference": "string",
"dropOffHubId": "string",
"pickUpHubId": "string",
"courierId": "string",
"from": {
"address": {
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
}
},
"to": {
"name": "string",
"phone": "string",
"email": "string",
"address": {
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
}
}
}
Am I correct if I write it in this way, but how to put in the string after "from": { and also "address": { then go into "address1": "string", Then another one is "to": { "name": "string", then go inside
"address": {, then go inside "address1": "string",
let postString = [ "service": 0,
"size": "string",
"orderReference": "string",
"dropOffHubId": "string",
"pickUpHubId": "string",
"courierId": "string",
"from": "fromAddArr",
"to": "toAddArr"] as [String : Any]
var request = URLRequest(url:URL!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue(bearerToken!, forHTTPHeaderField: "Authorization")
request.httpBody = try! JSONSerialization.data(withJSONObject: postString, options:.prettyPrinted)
I only know to write in this way.
{
"refNo": "string",
"code": "string"
}
let postString = ["refNo": "string",
"code": "string"]
Try this one i think you want something like this : First take dictionary of address from current json and convert that dictionary into string :
let dictionary:[String:Any] = ["address": [
"address1": "string",
"address2": "string",
"city": "string",
"postcode": "string",
"state": "string",
"country": "string"
]
]
if let theJSONData = try? JSONSerialization.data( withJSONObject: dictionary, options: []) {
let theJSONText = String(data: theJSONData, encoding: .utf8)
print("JSON string = \(theJSONText!)") //you can use this string to create dictionary as you want
let dict = ["addres":theJSONText!]
print(dict)
}
You do not need to write that string by yourself. If you are using swift 3 and have a model class for that JSON string, you can use a third party lib here. This will convert your model into dictionary, array, json string and data etc. You just need to make your model child of ParsableModel or JSONParsable.
If you have problem in creating model class from JSON you can use this utility. This will generate model class for your JSON:
class RootClass {
var courierId: String?
var dropOffHubId: String?
var from: From?
var orderReference: String?
var pickUpHubId: String?
var service: NSNumber?
var size: String?
var to: To?
}
class To {
var address: Addres?
var email: String?
var name: String?
var phone: String?
}
class From {
var address: Addres?
}
class Addres {
var address1: String?
var address2: String?
var city: String?
var country: String?
var postcode: String?
var state: String?
}
If you are using Swift 4. It provides you classes to Encode and Decode your code from JSON to model and model to JSON. You can save your time by using this.
Convert [String:Any] dictionary array to [String:String] in Swift
I have an array of dictionary <String,Any> type. Now I want to convert to string because I want to show data in textField and text field not understand Any data type.
My data like this:
var myarr = [[String:Any]]()
[
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://google.com",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
and I want new Array Dictionary:
var myarr = [[String:String]]()
Map is your friend, maybe something like
let stringDictionaries: [[String: String]] = myarr.map { dictionary in
var dict: [String: String] = [:]
dictionary.forEach { (key, value) in dict[key] = "\(value)" }
return dict
}
Here is one solution that actually gives the correct results:
let myarr = [
[
"Area" : "",
"Good" : "-",
"Level" : 2,
"Link" : "<null>",
"Photo" : "-",
"Repair" : "-",
"Section" : "Others"
],
[
"Area" : "",
"Good" : "N",
"Level" : 2,
"Link" : "http://someurl",
"Photo" : 1,
"Repair" : "Y",
"Section" : "Grounds"
]
]
var newarr = [[String:String]]()
for dict in myarr {
var newdict = [String:String]()
for (key, value) in dict {
newdict[key] = "\(value)"
}
newarr.append(newdict)
}
print(newarr)
Output:
[["Level": "2", "Area": "", "Good": "-", "Link": "<null>", "Repair": "-", "Photo": "-", "Section": "Others"], ["Level": "2", "Area": "", "Good": "N", "Link": "http://someurl", "Repair": "Y", "Photo": "1", "Section": "Grounds"]]
You can create new dictionary using following code:
var newArray:[[String: String]] = []
for data in myarr {
var dict: [String: String] = [:]
for (key, value) in data {
let strData = String(describing: value)
dict[key] = strData
}
newArray.append(dict)
}
I have created a struct with a library and have initialised that struct in another struct. Now I want to use the resulting struct in a Table View. However, the struct currently doesn't work properly. I've tried to find out why, but seem to be stuck.
It looks like the issue is that the library doesn't get translated properly to the struct. For in instance, when I do a count on an instance of the struct, using the following code:
var personalDetailsStructExtra: [PersonalDetailsStruct] = []
personalDetailsStructExtra.count
It returns 0, while it should be 5 (See code below, there are 5 entries into the dictionary):
struct PersonalDetailsStructLibrary {
let library = [
[
"title": "Country",
"icon": "country.pdf",
"questions": ["Belgium", "France", "Germany", "Netherlands", "Sweden", "UK", "USA"]
],
[
"title": "Age",
"icon": "age.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
[
"title": "Gender",
"icon": "gender.pdf",
"questions": ["Male", "Female", "Other"]
],
[
"title": "Height",
"icon": "height.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
[
"title": "Weight",
"icon": "weight.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
] }
And
struct PersonalDetailsStruct {
var title: String?
var icon: UIImage?
var questions: [String] = []
init(index: Int) {
let personalDetailsStructLibrary = PersonalDetailsStructLibrary().library
let personalDetailsDictionary = personalDetailsStructLibrary[index]
title = personalDetailsDictionary["title"] as! String!
let iconNamePD = personalDetailsDictionary["icon"] as! String!
icon = UIImage(named: iconNamePD!)
questions += personalDetailsDictionary["artists"] as! [String]
} }
As you can see in the code I want use the struct to fill up a label (title), image (icon) and UITextView with UIPickerView (questions) in my table view.
Since it doesn't work, I'm looking for either:
A: Feedback on how to make this code work in a tableview
B: Whether I should use another method to populate the dynamic cells in my tableview
You have to initialize the personalDetailsStructExtra array, only then you would see the required count.
var personalDetailsStructExtra = [PersonalDetailsStruct]()
PersonalDetailsStructLibrary().library.count
let count = PersonalDetailsStructLibrary().library.count
for i in 0..<count {
personalDetailsStructExtra.append(PersonalDetailsStruct(index: i))
}
personalDetailsStructExtra.count // 5
A better option is to use the Library struct to construct and maintain all model objects.
struct PersonalDetailDataSource {
let library = [
[
"title": "Country",
"icon": "country.pdf",
"questions": ["Belgium", "France", "Germany", "Netherlands", "Sweden", "UK", "USA"]
],
[
"title": "Age",
"icon": "age.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
[
"title": "Gender",
"icon": "gender.pdf",
"questions": ["Male", "Female", "Other"]
],
[
"title": "Height",
"icon": "height.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
[
"title": "Weight",
"icon": "weight.pdf",
"questions": ["1", "2", "3", "4", "5", "6", "7"]
],
]
var personalDetails = [PersonalDetail]()
init() {
loadData()
}
mutating private func loadData() {
for i in 0..<library.count {
let personalDetailsDictionary = library[i]
let title = personalDetailsDictionary["title"] as! String!
let iconName = personalDetailsDictionary["icon"] as! String!
let questions = personalDetailsDictionary["questions"] as! [String]
personalDetails.append(PersonalDetail(title: title, iconName: iconName, questions: questions))
}
}
}
struct PersonalDetail {
var title: String?
var icon: UIImage?
var questions: [String] = []
init(title: String, iconName: String, questions: [String]) {
self.title = title
if let icon = UIImage(named: iconName) {
self.icon = icon
}
self.questions = questions
}
}
PersonalDetailDataSource().personalDetails.count // count: 5