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

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

Related

am trying to print("_id") data which am getting from server

For the following swift code
self.cardDataArray = response.value(forKey: "card_list") as? NSArray
print(self.cardDataArray!)
i got this output from server(API)
(
{
"__v" = 0;
"_id" = 5978b5dadc336d0788a81c58;
"stu_number" = 1234567812345678;
"stu_status" = 1;
"created_at" = "2017-07-26T15:31:38.874Z";
"stu_id" = 5978b41ddc336d0788a81c57;
"stu_number" = 1234;
"default_status" = 0;
"default_type" = 3;
}
)
am trying to print "_id" from above code
but am getting error
Could not cast value of type '__NSSingleObjectArrayI' (0x1a9ae6ca0) to 'NSString'
here is the code which i tried to print
let studentID = self.cardDataArray?.value(forKey: "_id") as! NSString
print(studentID)
Your cardDataArray is a Dictionaries Array so you must first take this dictionary and access to the key you need in this case "_id", try with this code
if let studentDict = self.cardDataArray?[0] as? NSDictionary
{
print(studentDict.object(forKey: "_id") as? NSString)
}
Updated
for dictObj in self.cardDataArray {
print(dictObj.object(forKey: "_id") as? NSString)
}
Hope this helps

JSON parsing and accessing data from Dictionary

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

How to parse NSMutableDictionary in Swift programming?

In my apple watch interface controller "reply" object contains Json response in NSDictionary. Here is my response i need the "accountName" from this below response. How to parse it in Swift programming.
[Accounts: (
{
accountName = "ABCD";
idNumber = 114000093;
email = "xyz#gmail.com";
index = 0;
nickName = "Suites";
},
{
accountName = "EFGH";
idNumber = 114000094;
email = "abc#gmail.com";
index = 1;
nickName = "Sultan";
}
)]
I have tried like below:
WKInterfaceController.openParentApplication(["request" : "GetData"], reply: { (reply, error) -> Void in
println(reply)
self.accountNames = reply["Accounts"] as? NSMutableArray
println(self.accountNames)
This is very easy, you can try out by your own, and can google also, there are lots and lots of example available, you just need to brush up little bit.
Btw, You can try like this,
let accountArray : NSArray = reply.objectForKey("Accounts") as! NSArray
let accountDic : NSDictionary = accountArray.objectAtIndex(0) as! NSDictionary
let accountName : NSString = accountDic.valueForKey("accountName") as! NSString
Hope, this helps you.
Try this :
let accountInfos = (reply.valueForKey("Accounts") as [NSDictionary]).map {
YourModelClass(accountName: $0["accountName"] as String, idNumber: $0["idNumber"] as String ..... same for all other)
}
self.yourMutableArray.addObjectsFromArray(accountInfos)
let accountName = (yourMutableArray.objectAtIndex(0)as YourModelClass).accountName
println(accountName)
And your model class :
class YourModelClass : NSObject {
var accountName : String?
.
.
init(accountName:String, ......) {
self.accountName = accountName
}

Implementing AnyObject to NSString Issue

I'm trying to put AnyObject value to NSString and print it but unfortunatlly it is always crashing without showing the reason just EXC. After debugging I found it is crashing after currStr. So please where would be my issue?
var lastRefresh: AnyObject = self.currDic["Response"]!.objectForKey("Datasource")!
self.currStr = lastRefresh as NSString
println("Data: \(self.curreStr)")
My lastRefresh output:
{
Cookie = 0nss1w45xzuocyqgvrjcmr31;
Message = "\U0130\U015flem Ba\U015farl\U0131";
Response = {
Datasource = (
{
Content = "";
Date = "20.01.2015";
Time = "08:32:22";
Title = "Example1";
},
{
Content = "";
Date = "20.01.2015";
Time = "08:32:22";
Title = "Example2";
},
From your comments It's clear that, you need to convert the lastRefresh object to NSData for using it in NSXMLParser.
From your NSLog it looks like a Dictionary or Array. You can convert it to data using:
var yourData : NSData = NSJSONSerialization.dataWithJSONObject(lastRefresh, options: NSJSONWritingOptions.PrettyPrinted, error: nil)!

NSDictionary annidate in swift

I have this json result.
I would take the field "alert".
I try this:
var alert: NSString = jsonResult["features"]["properties"]["alert"]
but this is the error: does not have a member named 'subscript'.
I can not how to access a field in a nested dictionary
{
features = (
{
geometry = {
coordinates = (
"-97.95359999999999",
"37.2382",
5
);
type = Point;
};
id = usb000si7g;
properties = {
alert = green;
cdi = "5.8";
code = b000si7g;
detail = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/detail/usb000si7g.geojson";
dmin = "0.017";
felt = 1258;
gap = 38;
ids = ",usb000si7g,";
mag = "4.3";
magType = mwr;
mmi = "4.94";
net = us;
nst = "<null>";
place = "8km SE of Harper, Kansas";
rms = "0.51";
sig = 864;
sources = ",us,";
status = reviewed;
time = 1412272884590;
title = "M 4.3 - 8km SE of Harper, Kansas";
tsunami = "<null>";
type = earthquake;
types = ",cap,dyfi,general-link,geoserve,losspager,moment-tensor,nearby-cities,origin,phase-data,shakemap,tectonic-summary,";
tz = "-300";
updated = 1412614943519;
url = "http://earthquake.usgs.gov/earthquakes/eventpage/usb000si7g";
};
type = Feature;
}
);
metadata = {
api = "1.0.13";
count = 1;
generated = 1412617232000;
status = 200;
title = "USGS Significant Earthquakes, Past Week";
url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/significant_week.geojson";
};
type = FeatureCollection;
}
I don't know what to do. swift is changed every beta.
As #Kirsteins said is his answer, you have to do a lot of unwrapping, and it's recommended to use a JSON library.
If you still want to stick with hand made extraction, then I suggest you to made it programmatically, such as adding an extension to NSDictionary as follows:
extension NSDictionary {
func objectForTreeKeys<T>(keys:[String]) -> T? {
var dict: NSDictionary? = self
var retValue: T?
for key in keys {
var value: AnyObject? = dict?.objectForKey(key)
if let unwrapped = value as? NSDictionary {
dict = unwrapped
} else if let unwrapped = value as? T {
retValue = unwrapped
break
} else {
retValue = nil
break
}
}
return retValue
}
}
You pass an array of keys to the function, and it traverses all nested dictionaries until:
a value of type T is encountered
a value having type different than NSDictionary and T is found
a nil value is found
In the first case, it returns the value of T type - in the other cases it returns nil.
You can use it as follows:
let ret: String? = jsonResult.objectForTreeKeys(["features", "properties", "alert"])
As you can see, it's a generic method, and the return type is inferred from the type of the variable the result is assigned to - so it's necessary to explicitly define its type, which must be optional (String? in this specific case).

Resources