JSON parsing and accessing data from Dictionary - ios

{
ac = 0;
storeLocation = "<null>";
storeSizeSqFt = 1000;
tinNumber = testdummy4y58;
wirelessInternet = 0;
}
for the above written response I have written code
func StoreInfo(notification : NSNotification){
if let result = notification.userInfo{
print(result)
if let particularStoreInfo = result["data"] as? NSDictionary{
print(particularStoreInfo)
if let temp = particularStoreInfo["store"] as? NSDictionary{
print(temp)
}
}
}
}
I have successfully traversed inside the dictionary but Now guide me how to save and access details inside Store Dictionary.

To access data from inside an NSDictionary, you can use this method, assuming temp in your question is the dictionary you want to retrieve information from.
temp.objectForKey("ac") // Key can be of type AnyObject
The above will retrieve the information saved under the key "ac".
To store data in an NSDictionary, you must use NSMutableDictionary instead, which contains the method setObject.
Example of saving information:
var value = "This is the string I will save in the dictionary"
var dictionary = NSMutableDictionary()
dictionary.setObject(value, forKey: "Name of the Key")
UPDATED: Changed setValue example to setObject. See #vadian's comment for details.

Related

create a dictonary with for loop in swift

I just want to create a dictionary with the help of for loop
sample code :
var counter: Int = 1;
var pageCountDict = [String:Any]();
for filterCount in counter..<6
{
if let count = "page_\(filterCount)_vtime" as? String
{
pageCountDict = [count: timeInterval_Int];
}
}
print(pageCountDict);
This print command give me only last value of forloop
I just want all the value of this variable pageCountDict in a dictonary
The way to assign to a dictionary is first use the subscript and assign the value to it:
pageCountDict[YourKey] = YourValue
Also, you can see many examples and explanations in Apple documentation regarding dictionaries.
With each loop, you are replacing the dictionary with one that contains only one element. What you want to do is this :
pageCountDict[count] = timeInterval_Int
Also, you shouldn't need the as? String part. This should be sufficient :
for filterCount in counter..<6
{
pageCountDict[count] = "page_\(filterCount)_vtime"
}
var pageCountDict = [String:Any]()
You can add values to this dictionary by merging previous contents and new data as follows...
let counter: Int = 1
var pageCountDict = [String:Any]()
for filterCount in counter..<6
{
let value = 9
let count = "page_\(filterCount)_vtime" //'if' is not needed as it is always true
pageCountDict.merge([count: timeInterval_Int], uniquingKeysWith:{ (key, value) -> Any in
//assign value for similar key
timeInterval_Int
})
}
print(pageCountDict)`

iterating an array to extract a value from firebase database in swift

might sound like a basic question--but I'm not seeing where I am going wrong..
I end up with either of these two scenarios:
I keep getting the error "Could not cast value of type __NSCFNumber to NSSTring". if I use extractedSku = skuList[i]!.value["sku"] as! String
If I remove as! String it saves it, but it isn't saved as a string. How do I get this to be saved as a string?
I have appended data from firebase into an array
skuArray = [AnyObject?]()
in viewDidLoad, I am iterating skuArray to extract the 'sku' and store into a variable.
var skuArray = [AnyObject?]()
var productDetailArray = [AnyObject?]()
data stored in Sku Array is:
[Optional(Snap (aRandomKey) {
active = 1;
sku = 888888;
})]
viewDidLoad:
let skuList = self.skuArray
for var i = 0; i < skuList.count ; ++i{
let extractedSku = skuList[i]!.value["sku"] as! String
// go into database and extract "products" details by sku
self.databaseRef.child("products/\(extractedSku)").observeEventType(.ChildAdded, withBlock: { (snapshot:FIRDataSnapshot) in
self.productDetailArray.append(snapshot)
})
Since the underlying type is NSNumber, use the stringValue property to get a String:
if let extractedSku = (skuList[i]?.value["sku"] as? NSNumber)?.stringValue {
// use extractedSku which is of type String
}

Getting the Key value for a complex nested dictionary/ array combination in Swift

I am trying to access the keys for the following Dictionary:
let dictionaryToUSe = ["Starter":["mealName":"hamburger","price":"20.00"],"MainCourse":["mealName":"hotdog","price":"30.00"] ]
let keysToUse = dictionaryToUSe.keys
print(keysToUse) // returns "LazyMapCollection<Dictionary<String, Dictionary<String, String>>, String>(_base: ["Starter": ["price": "20.00", "mealName": "hamburger"]], _transform: (Function))\n"
How do I access the "starter" string?
and how do I generate a list of the keys for the "dictionaryToUSe" Dictionary?
To get the list of the dictionary keys, generate an array from the LazyMapCollection:
let keysToUse = Array(dictionaryToUSe.keys)
Result:
["Starter", "MainCourse"]
But to access the values from the dictionary, use classic subscripting:
if let starter = dictionaryToUSe["Starter"] {
print(starter) // ["price": "20.00", "mealName": "hamburger"]
if let price = starter["price"] {
print(price) // "20.00"
}
// etc
}

setValue of JSON results (lat/lon coordinates as Double) to CoreData in Swift

Im very new with iOS/xCode development using Swift. I'm attempting to do the following:
Query a JSON result and save the values to CoreData that will include a lat/lon coordinate that needs to be saved as a Doubles. Here is my current snippet that will not allow me to save the lat/lon as Double even when the item/value is set to NSNumber:
CoreData settings:
Entity Attributes and type:
apCode: String
apId: String
apLat: Double
apLon: Double
apName: String
apUpdate: Date
func snippet:
let jsonResult = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
var items = [[String:AnyObject]()]
var item:AnyObject
for var i = 0; i < jsonResult[“jsonAirports"]!.count; i++ {
items.append([String:AnyObject]())
item = jsonResult[“jsonAirports"]![i] as NSDictionary
items[i]["AIRPORT"] = item["AIRPORT"] as? String
items[i]["APCODE"] = item["APCODE"] as? String
items[i]["APID"] = item["APID"] as? String
items[i]["LAT"] = item["LAT"] as? NSNumber
items[i]["LON"] = item["LON"] as? NSNumber
items[i]["IMG"] = item["IMG"] as? String
items[i]["UDATE"] = item["UDATE"] as? NSDate
//Save to CoreData
var addAirportItem = NSEntityDescription.insertNewObjectForEntityForName("Airports", inManagedObjectContext: context) as NSManagedObject
addAirportItem.setValue(items[i]["AIRPORT"], forKey: "apName")
addAirportItem.setValue(items[i]["APCODE"], forKey: "apCode")
addAirportItem.setValue(items[i]["APID"], forKey: "apID")
addAirportItem.setValue(items[i]["LAT"], forKey: "apLat")
addAirportItem.setValue(items[i]["LON"], forKey: "apLon")
addAirportItem.setValue(items[i]["IMG"], forKey: "apImg")
addAirportItem.setValue(NSDate(), forKey: "apUpdate")
context.save(nil)
}
My goal is to compare user's current location using CoreLocation and fetch the corresponding item from CoreData using the saved lat/lon coordinates.
How do I set the JSON results for lat/lon coordinates to be saved as Doubles in CoreData?
Any help is greatly appreciated
Octavious
I am not sure, but it looks like the issue is a datatype mismatch between the properties described in your CoreData model and the type of the value you are trying to set on the properties.
If your CoreData model, apLat and apLon are both String, but you are trying to set them with NSNumber in your snippet. If you change the type to Double in your model, I think your snippet would work.

How can I access the values in this NSDictionary in Swift?

I am trying to access the 'address' object (String) in a dictionary:
Chain.sharedInstance().getAddress("19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ"){ dictionary, error in
NSLog("%#", dictionary)
let value = dictionary["address"] as? String //returns nil
}
this is the data I receive:
results = (
{
address = 19b7ZG3KVXSmAJDX2WXzXhWejs5WS412EZ;
confirmed = {
balance = 0;
received = 20000000;
sent = 20000000;
};
total = {
balance = 0;
received = 20000000;
sent = 20000000;
};
}
); }
How do I access the values in this dictionary when I keep getting nil?
To clarify, the data you are posting is not JSON, but rather looks like JSONP. You aren't showing any code deserializing the the object, so I assume Chain.sharedInstance().getAddress is handling that aspect. If this is an instance of the Bitcoin API, you might look at their documentation. If it is their API, the documentation says the return is
A dictionary with a single "results" key, whose value is a array
containing a single Address Object as a dictionary.
If that is the case if would be
if let resultsArray = dictionary["results"] as NSArray {
if let dict = results[0] as NSDictionary {
//dict["address"] should have your address
}
}
Try:
if let dict = dictionary["results"] as NSDictionary
{
let value = dict["address"] as NSString
}
or:
if let dict = dictionary["results"] as NSArray
{
if let di = dict[0] as NSDictionary
{
let value = di["address"] as NSString
}
}

Resources