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
Related
I am getting values from and Array[String:Any] type array in a for loop but it is getting crashed when going on first line in for loop .
Actually I have created an array (Array[String:Any]) Type and now I am getting all the values of this array to show on tableview but it is getting crash in for loop.
var ticketArray = [Any]()
var addTypeTicket = [String:Any]()
var imagesArray = [Any]()
var imagesFinal = [String:Any]()
let ticketDetails = ["ticketName":txtTicketName.text!,
"numberOfTicketOnSale":txtFldTotalQuantityofTicket.text!,
"ticketPrice":txtFldPriceofTicket.text!,
"messageForTicketBuyers":txtviewMessage.text!,
"ticketGroupName":txtFldGroupName.text!] as [String : Any]
ticketArray.append(ticketDetails)
print(ticketArray)
addTypeTicket["addTypeTicket"] = ticketArray
print(addTypeTicket)
viewShadowTicket.isHidden = true
viewForMainTicketAlert.isHidden = true
for alltickets in addTypeTicket {
let ticketName = (alltickets as AnyObject).object(forKey: "ticketName") as! String
let Quantity = (alltickets as AnyObject).object(forKey: "numberOfTicketOnSale") as! String
let ticketPrice = (alltickets as AnyObject).object(forKey: "ticketPrice") as! String
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: Quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
self.tableview.reloadData()
tableview.isHidden = false
I just want to get values in for loop .
If you are not using ticketArray anywhere else then there is not need to add data to that array. You can simply add data to addTypeTicket dictionary by:
addTypeTicket["addTypeTicket"] = ticketDetails
Then you can fetch the data like this:
if let addTypeTicketData = addTypeTicket["addTypeTicket"] as? [String: String] {
let ticketName = addTypeTicketData["ticketName"]
let quantity = addTypeTicketData["numberOfTicketOnSale"]
let ticketPrice = addTypeTicketData["ticketPrice"]
let arr = structTickets(ticketName: ticketName, numberOfTicketOnSale: quantity, ticketPrice: ticketPrice)
self.arrayTickets.append(arr)
}
And use arrayTickets for tableView's numberOfRowsInSection.
I am trying To add Array In My Dictionary.
How to add Details2 In ProductDetails of Details1 So I can Display On TableView Which Each row is Containing Collection View.
(((((self.completeDetailsArray[index] as! NSDictionary).mutableCopy()) as! NSMutableDictionary).value(forKey: "productDetails") as! NSArray).mutableCopy() as! NSMutableArray).addObjects( from: productArray )
I tried This One Which is not working
let productArray : NSArray = responseResult.value(forKey: "details2") as! NSArray
let oldProductDict : NSMutableDictionary = (self.completeDetailsArray[index] as! NSDictionary).mutableCopy() as! NSMutableDictionary
let oldProductArray : NSArray = oldProductDict.value(forKey: "productDetails") as! NSArray
let completeProductArray = oldProductArray.addingObjects(from: productArray as! [Any])
oldProductDict.setValue(completeProductArray, forKey: "productDetails")
self.completeDetailsArray.replaceObject(at: index, with: oldProductDict)
let oldProductDict2 : NSDictionary = self.completeDetailsArray[index] as! NSDictionary
print("oldProductDict2",oldProductDict2)
This is Working Is This Correct Solution Or I can Use Any Other Way
You can get each element of details1 like
var new = details1[0]
and now add
new["productDetails"] = details2
and add new into main array like
details[0] = new
The easy way to convert JSON to model class or struct using JSONExport
then you can make this like that
let details2:[ProductDetails] = [ProductDetails]()
details1.productDetails = details2
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")
In this I am getting data from server response after posting parameters and here I need to display it on table view and it should be displayed like shown below in the image 0 is the price for the particular shipping method
already i had written model class for server response data and here it is
struct ShippingMethod {
let carrierCode : String
let priceInclTax : Int
let priceExclTax : Int
let available : Any
let carrierTitle : String
let baseAmount : Int
let methodTitle : String
let amount : Int
let methodCode : String
let errorMessage : Any
init(dict : [String:Any]) {
self.carrierCode = dict["carrier_code"] as! String
self.priceInclTax = dict["price_incl_tax"]! as! Int
self.priceExclTax = dict["price_excl_tax"]! as! Int
self.available = dict["available"]!
self.carrierTitle = dict["carrier_title"] as! String
self.baseAmount = dict["base_amount"]! as! Int
self.methodTitle = dict["method_title"]! as! String
self.amount = dict["amount"]! as! Int
self.methodCode = dict["method_code"] as! String
self.errorMessage = (dict["error_message"] != nil)
}
}
by using this I had formed an array type like this by using code
var finalDict = [String: [String]]()
var responseData = [ShippingMethod]()
do
{
let array = try JSONSerialization.jsonObject(with: data, options: []) as? [[String : Any]]
for item in array! {
self.responseData.append(ShippingMethod.init(dict: item))
}
print(self.responseData)
}
catch let error
{
print("json error:", error)
}
print(self.responseData)
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [String]()
}
self.finalDict[carrierTitle]!.append(methodTitle)
}
print(self.finalDict)
the output of this finalDict is ["Flat Rate": ["Fixed"], "Best Way": ["Table Rate"]] in this carrier title key value pair should be displayed as section title and is Flat Rate and method title key value pair should be displayed as rows in section Fixed but the problem is I need amount key value pair with it also for corresponding method title can anyone help me how to get this ?
Why don't you create another struct for displaying row data:
struct CarrierInfo {
let name:String
let amount:Int
}
Change your finalDict to
var finalDict = [String: [CarrierInfo]]()
and create CarrierInfo instance and set it in finalDict
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
let amount = dict.amount
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [CarrierInfo]()
}
self.finalDict[carrierTitle]!.append(CarrierInfo(name: carrierTitle, amount: amount))
}
Likewise you can make other required changes. This would neatly wrap your row display data inside a structure.
PS: I have not tested the code in IDE so it may contain typos.
You can assign another dictionary with key as methodTitle and amount as value. i.e., ["fixed":"whatever_amount"]
OR
You can use finalDict differently, like ["Flat Rate": ["tilte":"Fixed","amount":"0"], "Best Way": ["title":"Table Rate","amount":"0"]]
If it is difficult for you to code this, you can revert back.
Edit
You can use the following code to create the array in the second solution I suggested above:
for item in self.responseData {
let dict = item
let carrierTitle = dict.carrierTitle
let methodTitle = dict.methodTitle
let amount = dict.amount
if self.finalDict[carrierTitle] == nil {
self.finalDict[carrierTitle] = [[String:String]]()
}
let innerDict = ["title":methodTitle,"amount":amount]
self.finalDict[carrierTitle]!.append(innerDict)
}
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.