How to parse NSMutableDictionary in Swift programming? - ios

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
}

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

How Parse JSON from API [duplicate]

This question already has answers here:
type 'Any' has no subscript members
(2 answers)
Closed 5 years ago.
i know to much ask like this. i already searching but not match with my problems.
oke i will try explain with my code
i have data API Like this
["profile": {
accountId = 58e470a0c50472851060d083;
androidDeviceId = "[\"3453247ddcf3f809\"]";
androidVersion = 21;
appId = (
"c46b4c10-62ce-11e6-bdd4-59e4df4b8410",
"fac915f0-fe2b-11e6-9dfb-55339bd7be35"
);
appVersion = "v5.1.0";
avatar = "https://account.8villages.com/uploads/images/5/1491366164_bnx1t0rudi.jpg";
birthDate = "12/03/1994";
"channel-group" = android;
communityId = 553e09b251906884443eff85;
coordinates = {
coordinates = (
"106.9602383333333",
"-6.249333333333334"
);
type = Point;
};
crop = "";
crops = "<null>";
customerId = 5369bd85cae84d0e03246a7c;
dateSubmitted = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
fullName = "Megi Fernanda";
gender = "Laki-laki";
homeAddress = Payakumbuah;
location = "Kota Payakumbuh";
moderation = {
at = {
iso = "2017-04-05T04:20:48.483Z";
timestamp = 1491366048;
};
by = auto;
status = moderated;
};
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
type = users;
university = "Politeknik Negeri Pertanian Payakumbuh";
}, "accessToken": {
key = "lH5aYvnp2JAZ6zoKQK4mpfsxCI0.";
secret = "yfZfTZbsaVIhKCbksGHQnPcPg9mKtoRAKyvjg_cgMeo.";
}]
i already can got fullName, Addres, Skill State etc
if let profile = json["profile"] as? NSDictionary {
let name = profile["fullName"]
let alamat = profile["Skill"]
}
but i don't know how to get atribut in totalConversation like question, storeItems, points
skill = "Budidaya pertanian";
state = "Sumatera Barat";
storeType = "";
subdistrict = "Payakumbuh Barat";
totalConversations = {
articles = 0;
forums = 0;
questions = 2;
responses = 0;
storeItems = 1;
};
i tried like
let profile = json["profile"]["totalConversation"] as? NSDictionary
error sign : Type 'any?' has no subscript members
You got that error because json["profile"] is Any type and it doesn't have any subscript. So you need to cast json["profile"] to a dictionary, [String: Any] is dictionary type in Swift.
if let profile = json["profile"] as? [String: Any] {
if let totalConversations = profile["totalConversations"] as? [String: Any] {
let questions = totalConversations["questions"] as? Int
}
}

How to declare an empty array of type 'CNLabeledValue' using Swift 3?

The code that used to work in iOS 9 was:
var valuesArray : [CNLabeledValue] = []
But I can't figure out how to do it in Swift 3.
This is the solution:
var phoneNumbers : [CNLabeledValue<CNPhoneNumber>] = []
As OOPer pointed out in this post:
CNLabeledValue's generic parameter is declared as <ValueType : NSCopying, NSSecureCoding>. So, in this case, you can choose any type which conforms to NSCopying and NSSecureCoding. NSString does and String does not.
something like this (with example to fill out phone number):
let phonesArray : [Phones] = phones!
var phonesToAdd = [CNLabeledValue]()
for phone in phonesArray
{
if let phoneT = phone.phoneType
{
if phoneT.lowercaseString == "mobile"
{
let mobilePhone = CNLabeledValue(label: "mobile",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(mobilePhone)
}
if phoneT.lowercaseString == "landline"
{
let landlinePhone = CNLabeledValue(label: "landline",value: CNPhoneNumber(stringValue: phone.phone))
phonesToAdd.append(landlinePhone)
}
}
}
contactData.phoneNumbers = phonesToAdd

Getting information from a NSDictionary

I named the result resultdict and the NSDictionary looks like this:
{
data = (
);
summary = {
"total_count" = 514;
};
}
How do I get the "514" from that? I am using swift.
Try this one
var totalCount = yourDict.valueForKeyPath("summary.total_count")
You can just do it like :
var totalCount = yourDict.objectForKey("summary").objectForKey("total_count")
convert it to string
var totalCount = yourDict.objectForKey("summary").objectForKey("total_count") as! String
If you use :
println(totalCount)
will result in
Optional(514)
Use that variable as you want

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