I have dictionary in swift
var data = ["GenInfo":Dictionary<String,String>(),"LangInfo":Array<String>(),"EduInfo":Array<Dictionary<String,String>>(),"JobInfo":Array<Dictionary<String,String>>(),"SkillInfo":Array<Dictionary<String,String>>()]
Now I want to add values to this dictionary, How can I do that.
Suppose if I want to add these
"FirstName": "Varun",
"Email": "varun#gmail.com",
"State": "Rajasthan",
"Address": "Plot No. 00, Bhagwan Nagar 31,",
"Zip": "21354",
"Phone": "123456789",
"LastName": "Sharma"
value to the valueForKey "GenInfo"
Your where making a Dictionary (i.e. NSDictionary) whose not mutable after it's declaration (unlike NSMutableDictionary).
That said, you can either do like this :
var data : NSMutableDictionary = ["GenInfo":Dictionary<String,String>(),"LangInfo":Array<String>(),"EduInfo":Array<Dictionary<String,String>>(),"JobInfo":Array<Dictionary<String,String>>(),"SkillInfo":Array<Dictionary<String,String>>()]
data["GenInfo"] = ["FirstName": "Varun",
"Email": "varun#gmail.com",
"State": "Rajasthan",
"Address": "Plot No. 00, Bhagwan Nagar 31,",
"Zip": "21354",
"Phone": "123456789",
"LastName": "Sharma"
]
data["LangInfo"] = ["English", "French", "Italian"]
data["EduInfo"] = [["Degree": "MCA", "School": "University of Kota", "Year": "2013"], ["Degree": "Another degree", "School": "University of London", "Year": "2015"]]
// And so on...
Or like this :
var data = [String: AnyObject]()
data["GenInfo"] = [String: String]() // Dictionary<String,String>()
data["LangInfo"] = [String]() // Array<String>()
data["EduInfo"] = [[String: String]]() // Array<Dictionary<String,String>>()
data["JobInfo"] = [[String: String]]() // Array<Dictionary<String,String>>()
data["SkillInfo"] = [[String: String]]() // Array<Dictionary<String,String>>()
data["GenInfo"] = ["FirstName": "Varun",
"Email": "varun#gmail.com",
"State": "Rajasthan",
"Address": "Plot No. 00, Bhagwan Nagar 31,",
"Zip": "21354",
"Phone": "123456789",
"LastName": "Sharma"
]
data["LangInfo"] = ["English", "French", "Italian"]
data["EduInfo"] = [["Degree": "MCA", "School": "University of Kota", "Year": "2013"], ["Degree": "Another degree", "School": "University of London", "Year": "2015"]]
// And so on...
Like this
var data: NSMutableDictionary = ["GenInfo":Dictionary<String,String>(),"LangInfo":Array<String>(),"EduInfo":Array<Dictionary<String,String>>(),"JobInfo":Array<Dictionary<String,String>>(),"SkillInfo":Array<Dictionary<String,String>>()]
data["GenInfo"] = ["FirstName": "Varun",
"Email": "varun#gmail.com",
"State": "Rajasthan",
"Address": "Plot No. 00, Bhagwan Nagar 31,",
"Zip": "21354",
"Phone": "123456789",
"LastName": "Sharma"
]
Related
It appears there is still no way to import JSON or CSV files directly to a Firestore database. Many of the suggestions are for JavaScript-based apps that do not translate well to Swift. Does anyone have a good Swift solution for adding data to a Firestore database using JSON/CSV?
//example json
[
{
"name": "Stone Cove Marina Inc",
"email": "NOT IN SAMPLE",
"category": "Docks",
"category2": "Marinas",
"category3": "Dock Builders",
"address": "134 Salt Pond Rd",
"city": "Wakefield",
"state": "RI",
"zip": 2879,
"phone": "(401) 783-8990",
"website": "http://stonecovemarinari.com"
},
{
"name": "Bluehaven Homes",
"email": "NOT IN SAMPLE",
"category": "General Contractors",
"category2": "Home Builders",
"category3": "",
"address": "5701 Time Sq",
"city": "Amarillo",
"state": "TX",
"zip": 79119,
"phone": "(806) 452-2545",
"website": "http://www.bluehavenhomes.com/"
}
]
//here is the database structure
//collection is "businesses"; each "business" gets a document id; within each document id set the data
database.collection("businesses").document().setData(/*data here*/)
You can try
let str = """
[
{
"name": "Stone Cove Marina Inc",
"email": "NOT IN SAMPLE",
"category": "Docks",
"category2": "Marinas",
"category3": "Dock Builders",
"address": "134 Salt Pond Rd",
"city": "Wakefield",
"state": "RI",
"zip": 2879,
"phone": "(401) 783-8990",
"website": "http://stonecovemarinari.com"
},
{
"name": "Bluehaven Homes",
"email": "NOT IN SAMPLE",
"category": "General Contractors",
"category2": "Home Builders",
"category3": "",
"address": "5701 Time Sq",
"city": "Amarillo",
"state": "TX",
"zip": 79119,
"phone": "(806) 452-2545",
"website": "http://www.bluehavenhomes.com/"
}
]
"""
do {
let json = try JSONSerialization.jsonObject(with:str.data(using:.utf8)!, options: []) as! [[String: Any]]
for var i in 0...json.count - 1
{
database.collection("businesses").document().setData(json[i])
}
} catch {
print(error)
}
I am not getting how to POST this type of data into webservice
{
"customer_id":"",
"customer_message": " entered by user",
"discount_amount": "",
"ip_address":"1.0.10.22",
"billing_address": {
"first_name": "hello",
"last_name": "world",
"company": "",
"street_1": "45 W test",
"street_2": "",
"city": "London",
"state": "Texas",
"zip": "123456",
"country": "United States",
"country_iso2": "US",
"phone": "",
"email": "xyz#example.com"
},
"shipping_addresses": [
{
"first_name": "rest",
"last_name": "Mctest",
"company": "Test Address",
"street_1": "rest test",
"street_2": "",
"city": "test",
"state": "test",
"zip": "12345",
"country": "United States",
"country_iso2": "US",
"phone": "",
"email": "xyzer#example.com"
}
],
"products": [
{
"product_id": 5448,
"quantity": 2
}
]
I am not getting how to POST this type of data into webservice.
Please help me
i am doing this type of data now i have to post this type. Can anyone post this type.
let aParam = ["email": Email, "password":Password] as [String:Any]
You are taking parameters as [String: Any], where Any denotes each type of data types. Say String, Array and Dictionary.
For example,
let aParam: [String: Any] = ["customer_id": "",
"customer_message": "",
"billing_address": ["first_name" : "hello",
"last_name" : "world",
"company" : "",
"street_1" : "45 W test"],
"shipping_addresses": [
["first_name" : "hello",
"last_name" : "world",
"company" : "",
"street_1" : "45 W test"]
],
"products": [
["product_id" : 5448,
"quantity" : 2],
["product_id" : 5450,
"quantity" : 1]
]
]
And complex json structure would be handle with content-type as JSON, so:
You just need to update your header as:
let aHeader = ["Content-Type" : "application/json"]
Hope this will help
I am trying to create an order from iOS to woo commerce using Alamofire. I am searching for a proper solution.
After trying to create an order I get this error:
{
code = "woocommerce_rest_cannot_create";
data = {
status = 401;
};
message = "Sorry, you are not allowed to create resources.";
}
Code:
let parameters: [String: AnyObject] = [
"consumer_key":"*******" as AnyObject, // here is my user name
"consumer_secret":"*******" as AnyObject, // here is my secret key
"shipping_total": "120.00" as AnyObject,
"total": "6015.00" as AnyObject,
"customer_id": 0 as AnyObject,
"billing": [
"first_name": "Faizul",
"last_name": "karim",
"company": "somecompany",
"address_1": "someAddress",
"address_2": "someAddress",
"city": "Dhaka",
"state": "Dhaka",
"postcode": "1203",
"country": "bd",
"email": "faizulkarim28#gmail.com",
"phone": "001929838939"
] as AnyObject,
"shipping": [
"first_name": "Faizul",
"last_name": "karim",
"company": "somecompany",
"address_1": "someAddress",
"address_2": "someAddress",
"city": "Dhaka",
"state": "Dhaka",
"postcode": "1203",
"country": "bd",
] as AnyObject,
"line_items":[
"id": 388,
"name": "Mens Casual Blazer - 40",
"product_id": 55677,
"variation_id": 57619,
"quantity": 1,
"tax_class": "",
"subtotal": "5895.00",
"subtotal_tax": "0.00",
"total": "5895.00",
"total_tax": "0.00",
] as AnyObject
]
Alamofire.request("https://infinitymegamall.com/wp-json/wc/v2/orders",method: .post, parameters: parameters)
.responseJSON{ response in
if let json = response.result.value {
print(json)
}
}
Are you sure your API Keys have write permissions? If GET works, it's possible that the key allows read only. Double check the permissions in your Woocommerce API Settings.
I just want to create an API JSON Structure. The following are the post body keys and objects. Are there any methods like object with keys and values similar to Objective C in Swift 4?
{
"name": "switch 1",
"type": "Switch",
"gatewayId":515,
"serialKey": "98:07:2D:48:D3:56",
"noOfGangs": 4,
"equipments": [
{
"name": "light",
"type": "Light",
"port": "1"
},
{
"name": "television",
"type": "Television",
"port": "3"
}
]
}
You can create the dictionary literally by annotating the type and replace the curly braces with square brackets
let dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [[ "name": "light", "type": "Light", "port": "1" ], ["name": "television", "type": "Television", "port": "3" ]]]
Or build it:
var dict : [String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4]
var equipments = [[String:String]]()
equipments.append(["name": "light", "type": "Light", "port": "1" ])
equipments.append(["name": "television", "type": "Television", "port": "3" ])
dict["equipments"] = equipments
how to create Dictionary
var populatedDictionary = ["key1": "value1", "key2": "value2"]
this how to create Array
var shoppingList: [String] = ["Eggs", "Milk"]
you can create Dictionary by this type
var dictionary = [Int:String]()
dictionary.updateValue(value: "Hola", forKey: 1)
dictionary.updateValue(value: "Hello", forKey: 2)
dictionary.updateValue(value: "Aloha", forKey: 3)
// anather example
var dict = [ 1 : "abc", 2 : "cde"]
dict.updateValue("efg", forKey: 3)
print(dict)
your JSON
let dic :[String:Any] = ["name": "switch 1", "type": "Switch", "gatewayId":515, "serialKey": "98:07:2D:48:D3:56", "noOfGangs": 4, "equipments": [ [ "name": "light", "type": "Light", "port": "1" ],
[ "name": "television", "type": "Television", "port": "3" ] ] ]
Can someone help me out here? I am using Playground for this example, so you can put the whole code into your Playground and see the results.
I found out that when I remove this line:
"address_format": "{{recipient}}\n{{street}}\n{{postalcode}} {{city}}\n{{country}}",
it seems to work.
(The JSON is validated)
import UIKit
struct Country : Decodable {
enum CodingKeys: String, CodingKey {
case continent
case alpha2
case name
}
var name : String?
var continent : String?
var alpha2 : String?
}
let json = """
[
{
"continent": "Europe",
"alpha2": "AD",
"alpha3": "AND",
"country_code": "376",
"currency": "EUR",
"international_prefix": "00",
"ioc": "AND",
"latitude": "42 30 N",
"longitude": "1 30 E",
"name": "Andorra",
"names": [
"Andorre",
"Andorra",
"アンドラ"],
"translations": {
"en": "Andorre",
"it": "Andorra",
"de": "Andorra",
"fr": "Andorre",
"es": null,
"ja": "アンドラ",
"nl": "Andorra",
"ru": "Андорра"},
"national_destination_code_lengths": [2],
"national_number_lengths": [6,7,8,9],
"national_prefix": "None",
"number": "020",
"region": "Europe",
"subregion": "Southern Europe",
"un_locode": "AD",
"languages": ["ca"],
"nationality": "Andorran"},
{
"continent": "Asia",
"address_format": "{{recipient}}\n{{street}}\n{{postalcode}} {{city}}\n{{country}}",
"alpha2": "AE",
"alpha3": "ARE",
"country_code": "971",
"currency": "AED",
"international_prefix": "00",
"ioc": "UAE",
"latitude": "24 00 N",
"longitude": "54 00 E",
"name": "United Arab Emirates",
"names": [
"United Arab Emirates",
"Vereinigte Arabische Emirate",
"Émirats Arabes Unis",
"Emiratos Árabes Unidos",
"アラブ首長国連邦",
"Verenigde Arabische Emiraten"],
"translations": {
"en": "United Arab Emirates",
"it": "Emirati Arabi Uniti",
"de": "Vereinigte Arabische Emirate",
"fr": "Émirats Arabes Unis",
"es": "Emiratos Árabes Unidos",
"ja": "アラブ首長国連邦",
"nl": "Verenigde Arabische Emiraten",
"ru": "Объединенные Арабские Эмираты"},
"national_destination_code_lengths": [2],
"national_number_lengths": [7,8,9],
"national_prefix": "0",
"number": "784",
"region": "Asia",
"subregion": "Western Asia",
"un_locode": "AE",
"languages": ["ar"],
"nationality": "Emirian"}
]
""".data(using: .utf8)!
let decoder = JSONDecoder()
do {
let countries = try decoder.decode([Country].self, from: json)
print(countries)
} catch {
print("erro")
}
If you would print the actually error information
"Unescaped control character around character 722."
rather than meaningless literal string "erro"
the solution is obvious:
The linefeed characters \n must be escaped:
"address_format": "{{recipient}}\\n{{street}}\\n{{postalcode}} {{city}}\\n{{country}}",
You can fix the issue with
let json = """
[
...
]
""".replacingOccurrences(of: "}\n{", with: "}\\n{").data(using: .utf8)!