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

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

Related

Traverse nsdictionary in swift

I am new to swift.
I have my dictionary as
monthData =
{
"2018-08-10" = {
accuracy = 71;
attempted = 7;
correct = 5;
reward = Bronze;
};
"2018-08-12" = {
accuracy = 13;
attempted = 15;
correct = 2;
reward = "";
};
"2018-08-13" = {
accuracy = 33;
attempted = 15;
correct = 5;
reward = "";
};
"2018-08-14" = {
accuracy = 100;
attempted = 15;
correct = 15;
reward = Gold;
};
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
"2018-08-21" = {
accuracy = 26;
attempted = 15;
correct = 4;
reward = "";
};
"2018-08-23" = {
accuracy = 46;
attempted = 15;
correct = 7;
reward = "";
};
}
I want to get all the dates for which reward is Gold
Can anyone please help me do that?
What I have tried 'till now is:
for (key,value) in monthData{
let temp = monthData.value(forKey: key as! String) as! NSDictionary
for (key1,value1) in temp{
if((value1 as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
but it outputs the error Could not cast value of type '__NSCFNumber' to 'NSString'
The error occurs because when you are iterating the dictionary you force cast the Int values to String which is not possible
The (highly) recommended Swift way is to use the filter function. This is much more efficient than a loop.
In the closure $0.1 represents the value of the current dictionary ($0.0 would be the key). The result is an array of the date strings.
let data : [String:Any] = ["monthData" : ["2018-08-10": ["accuracy" : 71, "attempted" ... ]]]
if let monthData = data["monthData"] as? [String:[String:Any]] {
let goldData = monthData.filter { $0.1["reward"] as? String == "Gold" }
let allDates = Array(goldData.keys)
print(allDates)
}
The code safely unwraps all optionals.
However if there is only one Gold entry the first function is still more efficient than filter
if let monthData = data["monthData"] as? [String:[String : Any]] {
if let goldData = monthData.first( where: {$0.1["reward"] as? String == "Gold" }) {
let goldDate = goldData.key
print(goldDate)
}
}
In Swift avoid the ObjC runtime (value(forKey:)) and Foundation collection types (NSDictionary) as much as possible.
From the first for in loop, you are getting the NSDictionary in temp variable
"2018-08-16" = {
accuracy = 73;
attempted = 15;
correct = 11;
reward = Silver;
};
So, you should directly check .value(forKey:) on temp and get the value for reward.
You should try it like this
for (key,value) in monthData {
let temp = monthData.value(forKey: key as! String) as! NSDictionary
if(((temp.value(forKey: "reward")) as! String) == "Gold"){
print("keyFINAL \(key)")
}
}
Try and share results
EDIT
Please checkout the answer from vadian for in-depth explanation and pure swift approach to achieve the same.
Thanks

Swift Query Request crashing when value is null

Query results retrieved
"Adjusted_Lease_Value__c" = "0.0";
"Amount_Financed__c" = "23520.64";
"Assignment_Amount__c" = "19220.21";
"Category__c" = 4;
"Charge_Off_Amount__c" = "0.0";
"Committed_Funds__c" = "19220.21";
"Date_Assigned_Back_to_ACG__c" = "<null>"
How I'm retrieving them:
// Initial Access to Salesforce in order to query data
client.performLogin(accessUsername, password: accessPassword, fail:{ (fail) in
}) { (success) in
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
// This line fails
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as! String
// This works no problem
let AmountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as! String
}
When the query result is "null" it crashes the app. What should I do?
If it may nil then do not use forced conversion.
self.queryResult = self.client.query(getCasesSQL2)
for o: Any in self.queryResult.records() {
let test = (o as AnyObject).fieldValue("Date_Assigned_Back_to_ACG__c") as? String
let amountFinanced = ((o as AnyObject).fieldValue("Amount_Financed__c") as? String
}

How do I sort an NSDictionary by integer value?

I have a NSDictionary. When I print it, it looks like this:
{
3gZ0qtk0yMUEvtSmz2RW40Y7AC83 = 12;
USXhV0QYkpbSzAmXgfeteXHuoqg2 = 25;
UTPFBV5Q5IgTh17060c6WxNDQCO2 = 1;
fqsspZtskWVheqUQQtROepixsGB2 = 256;
}
I want to sort it so that it looks like this:
{
fqsspZtskWVheqUQQtROepixsGB2 = 256;
USXhV0QYkpbSzAmXgfeteXHuoqg2 = 25;
3gZ0qtk0yMUEvtSmz2RW40Y7AC83 = 12;
UTPFBV5Q5IgTh17060c6WxNDQCO2 = 1;
}
All of the methods I see needs a key name but I don't understand that. There is no key name. Sorry if this is duplicate but everything I try from other questions doesn't work. There's just too many ways out there and I get all kinds of errors and other problems so I want to know the best (latest), and most efficient way to sort NSDictionaries in this way.
Also it's coming from a firebase snapshot
example:
self.friendsDict = snapshot.value as! NSDictionary
try this -
let dict:NSMutableDictionary = [
"3gZ0qtk0yMUEvtSmz2RW40Y7AC83" : 12,
"USXhV0QYkpbSzAmXgfeteXHuoqg2" : 25,
"UTPFBV5Q5IgTh17060c6WxNDQCO2" : 1,
"fqsspZtskWVheqUQQtROepixsGB2" : 256
]
let sortedKeys2 = (dict as NSDictionary).keysSortedByValueUsingComparator
{
($1 as! NSNumber).compare($0 as! NSNumber)
}
OR
let dict = [
"3gZ0qtk0yMUEvtSmz2RW40Y7AC83" : 12,
"USXhV0QYkpbSzAmXgfeteXHuoqg2" : 25,
"UTPFBV5Q5IgTh17060c6WxNDQCO2" : 1,
"fqsspZtskWVheqUQQtROepixsGB2" : 256
]
var sortedKeys = Array(dict.keys).sort({dict[$0] > dict[$1]})
Since you said the solution from this link Swift sort dictionary by value didn't work, I am posting a working code on my side:
let dict:NSDictionary = [
"3gZ0qtk0yMUEvtSmz2RW40Y7AC83" : 12,
"USXhV0QYkpbSzAmXgfeteXHuoqg2" : 25,
"UTPFBV5Q5IgTh17060c6WxNDQCO2" : 1,
"fqsspZtskWVheqUQQtROepixsGB2" : 256
]
let d = dict as! [String:NSInteger]
for (k,v) in (Array(d).sort {$0.1 > $1.1}) {
print("\(k):\(v)")
}
Output:
fqsspZtskWVheqUQQtROepixsGB2:256
USXhV0QYkpbSzAmXgfeteXHuoqg2:25
3gZ0qtk0yMUEvtSmz2RW40Y7AC83:12
UTPFBV5Q5IgTh17060c6WxNDQCO2:1
Edit:
For above code to work, OP had to change:
self.friendsDict = snapshot.value as! NSDictionary
to:
self.friendsDict = snapshot.value as! [String:NSInteger]

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
}

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