I am using Swift 3.
I am getting the following response from a server and i need to parse and get values such as, Account No, Account Type, Address etc.
parsedData: (
{
key = "<null>";
offset = 1;
partition = 0;
topic = test;
value = {
"Account No" = 675;
"Account Type" = Saving;
Address = location;
User ID = 601;
User Name = Stella;
};
}
)
I have been trying to get value first, and then planning to get each value,
var temp: NSArray = parsedData["value"] as! NSArray
but this is giving error as cannot convert value of type String to expected argument type Int.'
How to retrieve values from the above mentioned array?
parsedData is an array which contains Dictionary at first index.
let dicData = parsedData[0] as! Dictionary
let valueDictionary = dicData["value"] as! Dictionary //dicData also contains dictionary for key `value`
let accountNumber = valueDictionary ["Account No"] //**Account number**
//////SECOND APPROACH IF YOU HAVE DICTIONARY IN RESPONSE
var valueDictionary : NSDictionary = parsedData["value"] as? NSDictionary
let accountNumber = valueDictionary ["Account No"] //**Account number**
You parse a dictionary as an array
var temp: NSDictionary = parsedData["value"] as? NSDictionary
Try this
let dicData = parsedData[0] as! Dictionary
var temp: NSDictionary = dicData["value"] as? NSDictionary
let accountNumber = temp.object(forKey: "Account No")
let accountType = temp.object(forKey: "Account Type")
let address = temp.object(forKey: "Address")
let userID = temp.object(forKey: "User ID")
let userName = temp.object(forKey: "User Name")
Related
this is my dictionary value
var dict: NSDictionary = NSDictionary()
dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary
print(dict as Any)
{
cityId = 1;
cityName = Dammam;
countryId = 1;
mobile = 123;
name = "My name";
}
now i have to update cityid = "2", mobile = "456", name = "othername"
and create same as above Dictionary with updated values.
help me with this.
Modify your code as below
var dict = pref.object(forKey: KEY_USER_LOGIN_INFO) as! Dictionary<String,Any>
dict["cityid"] = "2"
dict["mobile"] = "456"
dic["name"] = "other name"
you are forcefully unwraping the dictionary it is not recommended ..
You can not update value in NSDictionary, so you have to use NSMutableDictionary.
var dict: NSMutableDictionary = NSMutableDictionary()
dict = (pref.object(forKey: KEY_USER_LOGIN_INFO) as! NSDictionary).mutableCopy() as! NSMutableDictionary
dict["cityId"] = 2
dict["mobile"] = 456
dict["name"] = "othername"
print(dict)
I'm going to display some data from NSArray in the tableViewCell.
Here is my NSArray format
(
{
score = "480.0";
uid = 2;
},
{
score = "550.0";
uid = 1;
}
)
So, how to display for example score?
Here is m code, but it doesn't display it
var gamesRound: NSArray = []
let game = gamesRound[indexPath.row]
//let user = users[Int(game.userId - 1)]
cell.textLabel?.text = game as? String
//cell.detailTextLabel?.text = "\(String(Int(game.score))) PTS"
//print(user.fullname!)
return cell
Change your gamesRound variable to Array of Dictionary like this:
Put some value like this, in viewDidLoad (maybe):
var gamesRound = [[String: Any]]()
To render value on cells of a UITableView
gamesRound = [["score": "480.0", "uid" = 2], ["score": "550.0", "uid": 1]]
Some what like this:
let game = gamesRound[indexPath.row] as! [String: Any]
cell.textLabel?.text = "\(game["score"] as? Int ?? 0)"
cell.detailTextLabel?.text = "\(game["uid"] as? Int ?? 0)"
seems to me that you have an NSDictionary in each position of you NSArray.
So, use this code to get the position that you want:
let game = gamesRound[indexPath.row]
Now the game is an NSDictionary and you only need to extract the information using the key that you want:
let uid = game["uid"]
let score = game["score"]
I hope my example helps you.
Here you have the Array of dictionary so when you write let dict = gamesRound[indexPath.row] you will get the dictionary object and you can get the value by using the key because dictionary has the key value pair while the array has the indexing.
Also, you can Declare array like this
var gamesRound: Array<Dictionary<String,Any>> = []
So you can verify by printing the values step by step:
print(gamesRound)
let dict = gamesRound[indexPath.row] as! Dictionary<String,Any>
print(dict)
let score = dict["score"]
print(dict["score"])
cell.textLabel?.text = "\(score!)"
Try this code,
let gameRound : NSDictionary = yourArray[indexPath.row] as! NSDictionary
let strUid = gameRound["uid"]
cell.textLabel.text = strUid as? String
I want get the below json to my array for showing in UITableview
{
MyPets = (
{
breed = "";
breedvaccinationrecord = "";
"city_registration" = "";
"date_of_birth" = "";
"emergency_contacts" = "";
gender = m;
"pet_id" = 475;
"pet_name" = "IOS PET";
petinfo = "http://name/pet_images/";
"prop_name" = "";
"qr_tag" = 90909090;
species = Canine;
"vaccination_records" = "";
vaccinationrecord = "http://Name/vaccination_records/";
"vet_info" = "";
}
);
}
i am using below code to get values into array
if let dict = response.result.value {
print(response)
let petListArray = dict as! NSDictionary
self.petListArray = petListArray["MyPets"] as! [NSMutableArray]}
in cellForRowAtIndexPath i am using this line to display name in UILabel in TableCell
cell?.petName.text = self.petListArray[indexPath.row].valueForKey("pet_name") as? String
but it is crashing like
fatal error: NSArray element failed to match the Swift Array Element type
i am new to swift 2 please help me thanks in advance
First of all declare petListArray as Swift Array, do not use NSMutable... collection types in Swift at all.
By the way the naming ...ListArray is redundant, I recommend either petList or petArray or simply pets:
var pets = [[String:Any]]()
The root object is a dictionary and the value for key MyPets is an array, so cast
if let result = response.result.value as? [String:Any],
let myPets = result["MyPets"] as? [[String:Any]] {
self.pets = myPets
}
In cellForRow write
let pet = self.pets[indexPath.row]
cell?.petName.text = pet["pet_name"] as? String
It's highly recomenended to use a custom class or struct as model. That avoids a lot of type casting.
I have a variable content from a NSArray : let content = application["content"]!
When I print content, I have a String :
print(content) -> My content
But when I want to cast my variable to String : let content = application["content"]! as! String
I can't print my variable because it's null :
print(content) -> Could not cast value of type 'NSNull' (0x1a0507768) to 'NSString' (0x1a0511798).
Why ?
UPDATE :
My array when value is not casted :
{
"application_title" = "Marina Kaye";
"application_type" = discussions;
"application_type_name" = Discussions;
content = (
{
content = "Le nouvel album de Marina Kaye";
link = "?message_id=118";
},
{
content = "Son album est num\U00e9ro 1 des";
link = "?message_id=131";
},
{
content = "Le nouvel album s'appel";
link = "?message_id=126";
}
);
"content_title" = "Messages utiles";
"content_type" = "useful_messages";
}
My array when value is casted :
{
"application_title" = "Marina Kaye";
"application_type" = discussions;
"application_type_name" = Discussions;
content = "<null>";
"content_title" = "<null>";
"content_type" = "usefull_messages";
}
I can't cast content to NSArray and content_title to String.
MY CODE :
let applicationsArray = result["applications"]! as! NSArray
for application in applicationsArray {
let applicationTitle = application["application_title"]! as! String
let applicationType = application["application_type"]! as! String
let applicationTypeName = application["application_type_name"]! as! String
let content = application["content"]! as! NSArray
let contentTitle = application["content_title"]! as! String
let contentType = application["content_type"]! as! String
self.listApplications.append(Application(applicationTitle: applicationTitle, applicationType: applicationType, applicationTypeName: applicationTypeName, content: content, contentTitle: contentTitle, contentType: contentType))
}
As you are coding in Swift, you do not need the legacy NSArray and NSDictionary types. Instead, these are now Array and Dictionary, but you do not even have to care about that.
To declare an array, you usually specify the type in square brackets, such as [String]. For a dictionary, you need this for both key and value, separated by a colon, e.g. [String: AnyObject].
From your log output, you have a Dictionary of type [String: AnyObject] with 6 keys; all of them point to String objects, except the "content" one.
The "content" key apparently points to an array of dictionaries. This is written like this: [[String: AnyObject]]. Thus it is not surprising that casting this to String is not successful.
Here is how you can parse the application dictionary's "content":
if let content = application["content"] as? [[String: AnyObject]] {
for item in content {
let text = content["content"] as? String
let link = content["link"] as? String
// do something with this data
}
}
I would recommend defining a class or struct to capture the application object. Your code will be much clearer and easier to maintain.
I took a look at the SE question here [Avinash's answer] and the Apple resource here [bottom of page 18 and top of page 19] in my attempt to set an address for an ABRecord. I did my best to translate them from Objective-C, but apparently I made an mistake somewhere since on the line let dict = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 5, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks) I get the error Cannot assign to immutable value of type 'CFDictionaryValueCallBacks'.
Here's my code:
let information: ABRecord = ABPersonCreate().takeRetainedValue()
let address: ABMutableMultiValueRef = ABMultiValueCreateMutable(ABPropertyType(kABMultiDictionaryPropertyType)).takeUnretainedValue()
var keys = [CFStringRef]()
var values = [CFStringRef]()
keys.append(kABPersonAddressStreetKey)
keys.append(kABPersonAddressCityKey)
keys.append(kABPersonAddressStateKey)
keys.append(kABPersonAddressZIPKey)
keys.append(kABPersonAddressCountryKey)
keys.append(kABPersonAddressCountryCodeKey)
Note: country code left out
values.append(s["kABPersonAddressStreetKey"]!! as NSString)
values.append(s["kABPersonAddressCityKey"]!! as NSString)
values.append(s["kABPersonAddressStateKey"]!! as NSString)
values.append(s["kABPersonAddressZIPKey"]!! as NSString)
values.append(s["kABPersonAddressCountryKey"]!! as NSString)
values.append(s["kABPersonAddressCountryCodeKey"]!! as NSString)
let dict = CFDictionaryCreate(kCFAllocatorDefault, keys, values, 5, &kCFCopyStringDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks)
let scanned = ABUnknownPersonViewController()
let identifier = ABMultiValueIdentifier()
ABMultiValueAddValueAndLabel(address, dict, kABHomeLabel, &identifier)
ABRecordSetValue(information, kABPersonAddressProperty, address, nil)
I'm sure there's a much more concise way to do this, but here's the solution I've come up with.
var addressComponents = [String : String]()
if let value = s["kABPersonAddressStreetKey"] {
addressComponents[kABPersonAddressStreetKey as String] = value
}
if let value = s["kABPersonAddressCityKey"] {
addressComponents[kABPersonAddressCityKey as String] = value
}
if let value = s["kABPersonAddressStateKey"] {
addressComponents[kABPersonAddressStateKey as String] = value
}
if let value = s["kABPersonAddressZIPKey"] {
addressComponents[kABPersonAddressZIPKey as String] = value
}
if let value = s["kABPersonAddressCountryKey"] {
addressComponents[kABPersonAddressCountryKey as String] = value
}
if let value = s["kABPersonAddressCountryCodeKey"] {
addressComponents[kABPersonAddressCountryCodeKey as String] = value
}
let address: ABMutableMultiValue = ABMultiValueCreateMutable(ABPropertyType(kABMultiStringPropertyType)).takeRetainedValue()
ABMultiValueAddValueAndLabel(address, addressComponents, kABHomeLabel, nil)
ABRecordSetValue(information, kABPersonAddressProperty, address, nil)