i'm trying to fill a tableview with a Json response this is the Json that i'm reading from the callback
{
"Categories": {
"Beer": [
{
"id": "3",
"nombre": "Bud ligth",
"precio": "10",
"categoriaid": "3",
"url": "false"
}
],
"Whiskey": [
{
"id": "2",
"nombre": "Red label",
"precio": "100",
"categoriaid": "2",
"url": "false"
}
]
}
}
and this is my code but it breaks the app any ideas on how can i make change my code in order to make it fill the tableview with its correspondent section and rows in each sections
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
for(NSString *categories in cat){
Categorias *categorias = [[Categorias alloc]initWithNombre:categories];
NSDictionary *listTagDict = [cat objectForKey:categories];
for (NSString *prod in listTagDict) {
NSArray *rows = [listTagDict objectForKey:prod];
for (NSDictionary *rowDict in rows) {
NSString* pID = [rowDict objectForKey:#"id"];
NSString* pNombre = [rowDict objectForKey:#"nombre"];
NSString* pPrecio = [rowDict objectForKey:#"precio"];
NSString* pUrl = [rowDict objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[categorias addRow:productos];
}
}
}
here are my two object clases the .m part
#implementation Productos
-(id)initWithNombre:(NSString *)name productoID:(NSString *)pId precio:(NSString*)prec iconUrl:(NSString*)url{
self = [super init];
if (self) {
self.nombre = name;
self.productoID = pId;
self.precio = prec;
self.iconUrl = url;
}
return self;
}
#end
#interface Categorias(){
NSMutableArray *rows;
}
#end
#implementation Categorias
-(id)initWithNombre:(NSString *)name{
self = [super init];
if (self) {
self.nombre = name;
}
return self;
}
-(void)addRow:(Productos *)row {
[rows addObject: row];
}
-(NSArray *)rowData {
return [NSArray arrayWithArray: rows];
}
#end
you are parsing the json response in wrong way,
try this,
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:self.menuInfo options:NSJSONReadingMutableContainers error:nil];
NSDictionary *cat = [json objectForKey:#"Categories"];
NSMutableArray *categoryArray = [NSMutableArray new];
for(NSString *key in [cat allKeys]){
Categorias *category = [[Categorias alloc]initWithNombre:key];
NSArray *listTagDict = [cat objectForKey:key];
for (NSDictionary *prod in listTagDict) {
NSString* pID = [prod objectForKey:#"id"];
NSString* pNombre = [prod objectForKey:#"nombre"];
NSString* pPrecio = [prod objectForKey:#"precio"];
NSString* pUrl = [prod objectForKey:#"url"];
Productos* productos = [[Productos alloc]initWithNombre:pNombre productoID:pID precio:pPrecio iconUrl:pUrl];
[category addRow:productos];
}
[categoryArray addObject:category];
}
use categoryArray to populate tableview.
in this, categoryArray count will be section count, and each section contains rows with rowData array of each category.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [categoryArray count];
}
-(NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
return category.nombre;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
Category *category = [categoryArray objectAtIndex:section];
NSArray *rows = [category rowData];
return [rows count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell" forIndexPath:indexPath]; return cell;
Category *category = [categoryArray objectAtIndex:indexPath.section];
NSArray *rows = [category rowData];
Product *product = [rows objectAtIndex:indexPath.row];
//populate cell with product
}
Related
I have used the below code to convert the JSON data(from SOAP service) to NSDictionary.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
}
Output
2017-04-04 13:03:51.085 SoapService[18444:588594] (
{
firstName = "1 Jhon";
lastName = Macay;
},
{
firstName = "2 William";
lastName = Proter;
},
{
firstName = "3 Joe";
lastName = Root;
},
{
firstName = "4 Brendon";
lastName = Haejoy;
},
{
firstName = "5 Jhon";
lastName = Snow;
},
{
firstName = "6 Theon";
lastName = Greyjoy;
}
)
Do I need to convert this to any other? or how could I bind the above output in UITableView?
To work with table view you need array
Checkout this simple table view tutorial
It should be like this
Declare jsonArray in your .h file
#property (strong, nonatomic) NSMutableArray *jsonArray;
Add below line viewDidLoad
self.jsonArray = [[NSMutableArray alloc]init];
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",son);
[self.jsonArray addObject:[[json objectForKey:#"firstname"]stringByAppendingString:[json objectForKey:#"lastname"]];
[tableViewName reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.jsonArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"cell"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
}
cell.textLabel.text = [self.jsonArray objectAtIndex:indexPath.row];
return cell;
}
take one NSMutuableArray and add dictionary to this array like
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject: json];
//Than Reload Tableview
Note: Declare array Globally to access in your class
tableview display data like
cell.label.text = [[array objectAtIndex:indexPath.row]valueForKey:#"firstName"];
Store json data into Global Declare NSArray.
-(void)retriveFromSYSoapTool:(NSMutableArray *)_data{
NSLog(#"data: %#",_data);
NSArray *value = [_data valueForKey:#"GetDemoDataResult"];
NSError *error;
NSData *objData = [value[0] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objData options:NSJSONReadingMutableContainers error:&error];
NSLog(#"%#",json);
DataArray = [NSArray arrayWithObjects:json, nil];
[tableView reloadData];
}
Here DataArray is Globally Declare NSArray Object;
Now Write UITableView DataSource Method.
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return DataArray.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"jsoncell" forIndexPath:indexPath];
NSDictionary *dict = DataArray[indexPath.row];
NSString *output = [NSString stringWithFormat:#"%# %#",dict[#"firstName"],dict[#"lastName"]];
cell.textLabel.text = output;
return cell;
}
I have UITableView with countries and their phone codes
- (NSArray *)sortedCountryLetters {
if (_sortedCountryLetters == nil) {
[self countriesInfo];
}
return _sortedCountryLetters;
}
- (NSDictionary *)countriesInfo {
if (_countriesInfo == nil) {
NSMutableArray *countries = [NSMutableArray new];
for (NSString *key in [AppDelegate phoneCodes]) {
[countries addObject:#{
#"key": key,
#"name": [_locale displayNameForKey:NSLocaleCountryCode value:key],
#"code": [AppDelegate phoneCodes][key]
}];
}
NSMutableArray *firstLetters = [NSMutableArray new];
NSMutableDictionary *result = [NSMutableDictionary new];
for (NSDictionary *country in countries) {
NSString *name = country[#"name"];
NSString *firstLetter = [[name substringToIndex:1] uppercaseString];
if ([[result allKeys] containsObject:firstLetter]) {
NSMutableArray *letterCountries = result[firstLetter];
[letterCountries addObject:country];
}
else {
result[firstLetter] = [#[country] mutableCopy];
[firstLetters addObject:firstLetter];
}
}
[firstLetters sortUsingComparator:^NSComparisonResult(NSString *letter1, NSString *letter2) {
return [letter1 compare:letter2];
}];
_sortedCountryLetters = [firstLetters copy];
for (NSString *firstLetter in [result allKeys]) {
NSMutableArray *letterCountries = result[firstLetter];
[letterCountries sortUsingComparator:^NSComparisonResult(NSDictionary *obj1, NSDictionary *obj2) {
NSString *name1 = obj1[#"name"];
NSString *name2 = obj2[#"name"];
return [[name1 lowercaseString] compare:[name2 lowercaseString]];
}];
}
_countriesInfo = [result copy];
}
return _countriesInfo;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[[self countriesInfo] allKeys] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSString *firstLetter = [self sortedCountryLetters][section];
NSArray *letterCountries = [self countriesInfo][firstLetter];
return [letterCountries count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"countryCell"];
NSString *firstLetter = [self sortedCountryLetters][indexPath.section];
NSArray *letterCountries = [self countriesInfo][firstLetter];
NSDictionary *country = letterCountries[indexPath.row];
[[cell textLabel] setText:country[#"name"]];
[[cell textLabel] setTextColor:[OmwThemes defaultColorForegroundMain]];
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
return [self sortedCountryLetters][section];
}
- (NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return [self sortedCountryLetters];
}
- (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
[tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:index] atScrollPosition:UITableViewScrollPositionTop animated:YES];
return [[self sortedCountryLetters] indexOfObject:title];
}
Section indices already shows at table view right side, but tapping do nothing.
In debug I saw that tableView:sectionForSectionIndexTitle:atIndex: method never called.
Table view is connected to datasource and delegate. I did try both plain and group table view styles.
What did I miss?
Update:
My table view look:
I get this json from web service and I need to group it depending on "PRICELISTCATEGORY" value. I tried the following code, but I get repeated rows and sections in the table. I collect the web service array in self.arrayPriceList. What am I doing wrong?
After collecting the array from json web service, I call [self didReceiveResponseJson:self.arrayPriceList];
-(NSMutableDictionary *)priceListCategoryDitionaryAllReadyExist:(NSString *)price {
for(NSMutableDictionary *priceListDict in self.arrayPriceList){
if([[[priceListDict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"] isEqualToString:price])
//return the existing array refrence to add
return priceListDict;
}
// if we dont found then we will come here and return nil
return nil;
}
-(void)didReceiveResponseJson:(NSMutableArray *)jsonArray {
for(NSDictionary *priceDict in jsonArray) {
NSMutableDictionary *existingPriceListDict=[self priceListCategoryDitionaryAllReadyExist:[[priceDict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"]];
NSMutableArray *existingTempArray = [NSMutableArray array];
if(existingPriceListDict != nil) {
//if name exist add in existing array....
[existingTempArray addObject:priceDict];
}
else {
// create new price list array
NSMutableArray *newPriceListArray=[[NSMutableArray alloc] init];
// Add name dictionary in it
[newPriceListArray addObject:priceDict];
// add this newly created pricelist array in globalNameArray
[self.arrayPriceList addObject:newPriceListArray];
}
}
//so at the end print global array you will get dynamic array with the there respetive dict.
//NSLog(#"Table array %#", self.arrayPriceList);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TGAPriceListCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TGAPriceListCellId" forIndexPath:indexPath];
NSDictionary *dict;
if (self.isFiltered) {
dict = [self.arrayFilteredPriceList objectAtIndex:indexPath.row];
} else {
dict = [self.arrayPriceList objectAtIndex:indexPath.section];
}
cell.lblAPNBarCode.text = [[dict objectForKey:#"APNBARCODE"] objectForKey:#"text"];
cell.lblAvgCost.text = [[dict objectForKey:#"AVERAGECOST"] objectForKey:#"text"];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.isFiltered) {
return self.arrayFilteredPriceList.count;
} else {
NSArray *arrayPrice = [self.arrayPriceList objectAtIndex:section];
return [arrayPrice count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [self.arrayPriceList count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDictionary *arrayPrice = [self.arrayPriceList objectAtIndex:section];
if([arrayPrice count]) {
return [[arrayPrice objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"];
}
else
return nil;
}
After calling didReceiveResponseJson in viewDidLoad
self.arrayPriceList = [NSMutableArray array];
self.dictPriceList = [NSMutableDictionary dictionary];
I made changes in tableview datasource methods
-(void)didReceiveResponseJson:(NSMutableArray *)jsonArray {
for (NSDictionary *dict in jsonArray ) {
NSString *strPriceListCategory = [[dict objectForKey:#"PRICELISTCATEGORY"] objectForKey:#"text"];
if ([[self.dictPriceList allKeys] containsObject:strPriceListCategory]) {
NSMutableArray *arrayTemp = [self.dictPriceList objectForKey:strPriceListCategory];
[arrayTemp addObject:dict];
[self.dictPriceList setObject:arrayTemp forKey:strPriceListCategory];
} else {
NSMutableArray *arrayTemp = [[NSMutableArray alloc] initWithObjects:dict, nil];
[self.dictPriceList setObject:arrayTemp forKey:strPriceListCategory];
}
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
TGAPriceListCell *cell = [tableView dequeueReusableCellWithIdentifier:#"TGAPriceListCellId" forIndexPath:indexPath];
NSDictionary *dict;
if (self.isFiltered) {
dict = [self.arrayFilteredPriceList objectAtIndex:indexPath.row];
} else {
NSArray *arrayPriceListAllKeys = [self.dictPriceList allKeys];
NSArray *arrayPrice = [self.dictPriceList objectForKey:[arrayPriceListAllKeys objectAtIndex:indexPath.section]];
dict = [arrayPrice objectAtIndex:indexPath.row];
}
cell.lblAPNBarCode.text = [[dict objectForKey:#"APNBARCODE"] objectForKey:#"text"];
cell.lblAvgCost.text = [[dict objectForKey:#"AVERAGECOST"] objectForKey:#"text"];
return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.isFiltered) {
return self.arrayFilteredPriceList.count;
} else {
NSArray *arrayPriceListAllKeys = [self.dictPriceList allKeys];
NSArray *arrayPrice = [self.dictPriceList objectForKey:[arrayPriceListAllKeys objectAtIndex:section]];
return [arrayPrice count];
}
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.dictPriceList allKeys] count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *price = [[self.dictPriceList allKeys] objectAtIndex:section];
return price;
}
I have this json
{
"title": "xyz",
"category": "Monetary",
"target": "55",
"achieve": "0",
"todolist": [
{
"todoitem": "one"
},
{
"todoitem": "two"
},
{
"todoitem": "three"
}
]
}
coming from API and I want to add todolist array to
In .h file
#property (strong, nonatomic) NSMutableArray *todolist;
#property (strong, nonatomic) NSMutableArray *todolists;
#property (strong, nonatomic) NSMutableArray *listnumber;
In .m file
todolist=[[NSMutableArray alloc] initWithObjects: nil];
todolists=[[NSMutableArray alloc] initWithObjects: nil];
listnumber=[[NSMutableArray alloc] initWithObjects: nil];
In function getting json
todolists = [result valueForKey:#"todolist"];
for (int j =0; j < todolist.count; j++)
{
[todolist addObject:[[todolists objectAtIndex:j] valueForKey:#"todoitem"]];
[listnumber addObject:[NSString stringWithFormat:#"%d", j]];
}
[tvToDoList reloadData];
CellForRowAtIndexPath I am adding values two field
static NSString *CellIdentifier=#"Cell";
TodolistTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(cell==nil)
{
cell = [[TodolistTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier ];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
int row = (int)[indexPath row];
cell.valListitem.text = todolist[row];
cell.lblNo.text = listnumber[row];
return cell;
}
where result is containing the whole json
Try this in one line code.
todolist = [[[result valueForKey:#"todolist"] valueForKey:#"todoitem"] mutableCopy];
If you want to get string from array here is solution
for (int i =0; i < listnumber.count; i++)
{
[todolist addObject:[[listnumber objectAtIndex:i] valueForKey:#"todoitem"]];
}
Parse your json string and get the todos as NSArray from that.
#Try this
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:data
options:0
error:&error];
NSArray *todos = [object valueForKey:#"todolist"];
NSMutableArray *mutableToDos = [[NSMutableArray alloc] initWithArray:todos];
Here is the code for display in cell
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
NSDictionary *todo = [mutableToDos objectAtIndex:indexPath.row];
[[cell textLabel] setText:[todo valueForKey:#"todoitem"];
return cell;
}
Try this
#property (strong, nonatomic) NSMutableArray *todolist;
todolist=[[NSMutableArray alloc] initWithObjects: nil];
//Convert to NSData
NSData* jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
//JSON object
id object = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//Array of ToDo List
NSArray *list = (NSArray *)[object valueForKey:#"todolist"];
//Fetch items of ToDo List
for (int i =0; i < [list count]; i++)
{
[todolist addObject:[[list objectAtIndex:i] valueForKey:#"todoitem"]];
}
NSLog(#"Array :: %#", todolist);
Hopefully, this will help you.
Thanks.
I am trying to figure out how I can get data from a JSON array that is in another array.
Here is the JSON. I'm wanting to get one of the image URLs from photos.
[
{
"id":6901439,
"name":"INDTTIN CD",
"description":"Full-length released June 2013 via Little Heart Records. \r\n\r\nTrack Listing:\r\n\r\n1. Tired\r\n2. Time to Heal\r\n3. Gypsy Summer\r\n4. Sketchbooks\r\n5. I Never Deserve the Things I Need\r\n6. Say it With the \"I\"\r\n7. A Negative Mind\r\n8. Rafters\r\n9. Indrid Cold\r\n10. Present Tense ",
"short_url":"http://onmyhonor.storenvy.com/products/6901439-indttin-cd",
"status":"active",
"labels":null,
"preorder":false,
"on_sale":true,
"store_id":373949,
"price":"7.00",
"marketplace_category":"music-cds",
"marketplace_category_id":345,
"photos":[
{
"photo":{
"original":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_original.jpg",
"large":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_large.jpg",
"homepage":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_homepage.jpg",
"medium":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_medium.jpg",
"small":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_small.jpg",
"64w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64w.jpg",
"200w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200w.jpg",
"400w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400w.jpg",
"600w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_600w.jpg",
"1000w":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_1000w.jpg",
"64sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_64sq.jpg",
"200sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_200sq.jpg",
"400sq":"//d111vui60acwyt.cloudfront.net/product_photos/15878486/inddthin_20vinyl_20image_201_400sq.jpg"
}
}
],
"variants":[
{
"variant":{
"id":14382188,
"name":"INDTTIN CD",
"position":1,
"sku":"",
"full_quantity":300,
"in_stock":300,
"percent_available":100,
"is_default_variant?":false,
"price":7.0,
"sold_out":false,
"status":"active"
}
}
],
"collections":[
],
"store":{
"id":373949,
"name":"On My Honor",
"marketplace_url":"http://www.storenvy.com/stores/373949-on-my-honor"
}
}
]
Here is my code:
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
#define storeURL [NSURL URLWithString: #"http://onmyhonor.storenvy.com/products.json"]
#import "GRSStoreViewController.h"
#import "GRSStoreDetailViewController.h"
#interface GRSStoreViewController ()
#end
#implementation GRSStoreViewController
#synthesize name, description, short_url, price, productImage, nameArray, descriptionArray, urlArray, priceArray, imageArray, url;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Store";
self.tableView = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
url = [NSURL URLWithString:#"http://onmyhonor.storenvy.com/products.json"];
dispatch_async(kBgQueue, ^{
NSData *data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData
{
NSError *error;
nameArray = [[NSMutableArray alloc]init];
descriptionArray = [[NSMutableArray alloc]init];
urlArray = [[NSMutableArray alloc]init];
priceArray = [[NSMutableArray alloc]init];
imageArray = [[NSMutableArray alloc]init];
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
for (NSDictionary *item in json)
{
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
[self.tableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [nameArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
cell.textLabel.font = [UIFont systemFontOfSize:16.0];
}
if (cell)
{
cell.textLabel.text = [nameArray objectAtIndex:indexPath.row];
cell.textLabel.textColor = [UIColor darkGrayColor];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
GRSStoreDetailViewController *itemDetail = [[GRSStoreDetailViewController alloc]initWithNibName:#"GRSStoreDetailViewController" bundle:nil];
itemDetail.priceString = [priceArray objectAtIndex:indexPath.row];
itemDetail.descriptionString = [descriptionArray objectAtIndex:indexPath.row];
itemDetail.itemURL = [urlArray objectAtIndex:indexPath.row];
[self.navigationController pushViewController:itemDetail animated:YES];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Change loop to
for (NSDictionary *item in json)
{
NSArray *photos = item[#"photos"];
NSDictionary *dict = [photos[0] valueForKeyPath:"photo"];
NSLog(#"original = %#", dict[#"original"]);
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
Change this
NSArray *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
for (NSDictionary *item in json)
{
name = [item objectForKey:#"name"];
description = [item objectForKey:#"description"];
short_url = [item objectForKey:#"short_url"];
price = [item objectForKey:#"price"];
[nameArray addObject:name];
[descriptionArray addObject:description];
[urlArray addObject:short_url];
[priceArray addObject:price];
}
[self.tableView reloadData];
To this
NSdictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
name = [json objectForKey:#"name"];
description = [json objectForKey:#"description"];
short_url = [json objectForKey:#"short_url"];
price = [json objectForKey:#"price"];
// this is your photos array
NSArray *photos = [josn objectForKey:#"photos"];
// every object in this array is a dictionary. In your case this array has only one dictionary so
NSDictionary *photosDict = [photos firstObject];
// from here you can access all keys of photosDict
All available keys in your photosDict:
original
large
homepage
medium
small
64w
200w
400w
600w
1000w
64sq
200sq
400sq