hi i am new to iphone development
i am using a webservice to connect with where i am getting json response string and i am parsing json responsetring using JSONvalue and i am displaying the parsed json on the label using button...
when i click the button the parsed json it will display on label field..
my question is can v have a textfield,button and webview or tableview in the UI..
when i enter the particular method in the textfield as json file is huge and press button shd display contents of particular method on the webview or tableview..
is this possible? if so then how to implement?
thank u
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[connection release];
NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
self.dataWebService = nil;
NSArray* latestLoans = [(NSDictionary*) [responseString JSONValue] objectForKey:#"loans"];
[responseString release];
NSDictionary* loan = [latestLoans objectAtIndex:0];
//fetch the data
NSNumber* fundedAmount = [loan objectForKey:#"funded_amount"];
NSNumber* loanAmount = [loan objectForKey:#"loan_amount"];
float outstandingAmount = [loanAmount floatValue] - [fundedAmount floatValue];
NSString* name = [loan objectForKey:#"name"];
NSString* country = [(NSDictionary*)[loan objectForKey:#"location"] objectForKey:#"country"];
//set the text to the label
label.numberOfLines = 0;
label.text = [NSString stringWithFormat:#"Latest loan: %# \n \n country: %# \n \n µamount $%.2f", name,country,outstandingAmount];
If you want the loans in a table, you should read up on UITableView and Cell Styles
you'll add your table, then indicate the number of sections, rows in each section, the content for each cell (row), and what to do if one of the rows is touched:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
//after turning latestLoans into a property
return self.latestLoans.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text=[[self.latestLoans objectAtIndex:indexPath.row] objectForKey:#"name"];
cell.detailTextLabel.text=[[self.latestLoans objectAtIndex:indexPath.row] objectForKey:#"loan_amount"];
}
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//do something with the row that was selected, like load a table of detailed information
}
Related
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Get Data from a PList into UITableView?
I have a plist with Dictionary and numbers of strings per dictionary.show into the url below.and this list of items is in thousands in the plist.
Now want to display these list into the tableview
.
now how can i display this plist into the UITableView
what I am trying is:
- (id)readPlist:(NSString *)fileName
{
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:#"A" ofType:#"plist"];
dic =[NSDictionary dictionaryWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:dic mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
NSLog(#"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
[error release];
}
return plist;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
dict =[self readPlist:#"A"];
return dict.allKeys.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
dict = [self readPlist:#"A"];
key = [dict.allKeys objectAtIndex:section];
return [[dict valueForKey:key] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[dict objectForKey:key] objectAtIndex:indexPath.row];
return cell;
}
UPDATE 2: You need to set the delegate and datasource for your tableView in your xib or ViewController.
In your ViewController.h file
#interface ViewController:UIViewController <UITableViewDelegate, UITableDataSource>
Try this code which I have written for you.
- (void)viewDidLoad {
tableView.delegate = self;
tableView.dataSource = self;
NSString *path = [[NSBundle mainBundle] pathForResource:#"Filename" ofType:#"plist"];
NSArray *contentArray = [NSArray arrayWithContentsOfFile:path];
// Having outlet for tableArray variable.
tableArray = [[NSMutableArray alloc]initWithArray:contentArray copyItems:YES];
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [tableArray count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// In your case dictionary contains strings with keys and values. The below line returns dictionary only. not array..
NSDictionary *dictionary = [tableArray objectAtIndex:section];
return dictionary.allKeys.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"MyCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:cellIdentifier];
}
NSDictionary *dictionary = [tableArray objectAtIndex:indexPath.section];
NSArray *keysArray = dictionary.allKeys;
// This below line display the key in textLabel
cell.textLabel.text = [keysArray objectAtIndex:indexPath.row];
// Below line will display the value of a key in detailTextLabel.
cell.detailTextLabel.text = [dictionary valueForKey:[keysArray objectAtIndex:indexPath.row]];
return cell;
}
UPDATE 2: After I have seen your plist in my MAC, I have found out that we are working with array of dictionaries in your A.plist.
So I found there is a bug in our code itself. Not in the plist file and you can use your 8000 data plist too.. Its working too. I have checked out totally. Now you can get the above Code and start work with.
store Plist data in array
- (id)readPlist:(NSString *)fileName
{
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:#"A" ofType:#"plist"];
// declare your array in .h file
array = [NSArray arrayWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:dic mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
NSLog(#"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
[error release];
}
return plist;
}
and then write it in table
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [array objectAtIndex:indexPath.row] valueForKey:#"keyname"];;
return cell;
}
I want to display Plist to the UITableView .By my below code I can display one key values that is list of states. but i want to display all the values of three tables.
- (id)readPlist:(NSString *)fileName
{
NSData *plistData;
NSString *error;
NSPropertyListFormat format;
id plist;
NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:#"plist"];
plistData = [NSData dataWithContentsOfFile:localizedPath];
plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
if (!plist) {
NSLog(#"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
}
return plist;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [[[self readPlist:#"sample"] objectForKey:#"ListOfStates"] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[[self readPlist:#"sample"] objectForKey:#"ListOfStates"] objectAtIndex:indexPath.row];
return cell;}
MY output comes only listofkeystates values
is it also possible to display key name with values
Maybe use table sections...
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
NSDictionary* dict = [self readPlist:#"sample"];
return dict.allKeys.count;
}
-(NSString*) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSDictionary* dict = [self readPlist:#"sample"];
return [dict.allKeys objectAtIndex:section];
}
-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
NSDictionary* dict = [self readPlist:#"sample"];
NSString* key = [dict.allKeys objectAtIndex:section];
return [[dict valueForKey:key] count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary* dict = [self readPlist:#"sample"];
NSString* key = [dict.allKeys objectAtIndex:indexPath.section];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [[dict objectForKey:key] objectAtIndex:indexPath.row];
return cell;
}
just try to get data in NSDictionary and NSArray and then use it in UITableView
NSString *file = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile:file];
and use tableValue with its name like bellow...
NSArray *array = [dict objectForKey:#"ListOfStates"];
NSLog(#"%#", array);
i hope this help you..
EDIT : Corrected some typo mistakes
The idea
Loading plist in a dictonary
optional : sort it (!)
create the array of data for each section
create the array of section
Then implement the following things
viewDid load -> load the plist file in a dictionary, create an array of the sections and a dictionary of the data
numberOfSectionsInTableView -> the number of sections. In your case the number of keys
numberOfRowsInSection -> the number of rows of each section
titleForHeaderInSection -> for each section, the title of the section
cellForRowAtIndexPath -> the data of all row
sectionIndexTitlesForTableView -> the array that holds all you sections names. In your case all the keys
assuming you have a property called mySections and a property called myData
also assuming you use storyboard with standard cell with recycle identifier "Cell"
#synthesize mySections
#synthesize myData
- (void)viewDidLoad
{
[super viewDidLoad];
//LOADING THE PLIST FILE
//Create a string representing the file path
NSString *plistPath = [bundle pathForResource:#"yourFilename" ofType:#"plist"];
//Load the file in a dictionnary
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
self.myData = dict;
//SORTING THE DICTIONARY
NSArray *dicoArray = [[self.myData allKeys] sortedArrayUsingComparator:^(id firstObject, id secondObject) {
return [((NSString *)firstObject) compare:((NSString *)secondObject) options: NSCaseInsensitiveSearch];
}];
self.mySections = dicoArray;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
//Return the number of sections.
return [self.mySections count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
NSString *key = [self.mySections objectAtIndex:section];
NSArray *dataInSection = [self.myData objectForKey:key];
return [dataInSection count];
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
NSString *key = [self.mySections objectAtIndex:section];
return [NSString stringWithFormat:#"%#", key];
}
-(NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
return self.mySections;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath: (NSIndexPath *)indexPath
{
NSUInteger section = [indexPath section];
NSUInteger row = [indexPath row];
NSString *key = [self.mySections objectAtIndex:section];
NSArray *dataForSection = [self.myData objectForKey:key];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
cell.textLabel.text = [dataForSection objectAtIndex:row];
return cell;
}
I am developing and tableView in which in each row I have to display the click counter and row number.Each cell must have an initial click counter value of 0 when application is initialized. Then increment the click counter value within a cell whenever a user clicks on the cell.
I have take 26 fixed rows. I have taken tableData.plist file as in the attached image.
I am initializing the self.dataArray with the plist .
Now I want to do implementation in the didSelectRowAtIndexPath delegate method,if any row is tapped that row's click counter should increment.
- (void)viewDidLoad {
[super viewDidLoad];
NSString *path = [[NSBundle mainBundle] pathForResource:#"tableData" ofType:#"plist"];
self.dataArray = [NSMutableArray arrayWithContentsOfFile:path];//array initialized with plist
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.dataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *kCustomCellID = #"MyCellID";
UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(160.0f, 2.0f, 30.0f, 20.0f)];//label for rowid
UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(160.0f, 24.0f, 30.0f, 30.0f)];//label for counter
label2.textColor = [UIColor grayColor];
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:kCustomCellID];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:kCustomCellID] autorelease];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
if([self.dataArray count]>indexPath.row)
{
label1.text = [[self.dataArray objectAtIndex:indexPath.row] objectForKey:#"Lable1"];
label2.text =[[self.dataArray objectAtIndex:indexPath.row] objectForKey:#"Lable2"];
}
else {
label1.text = #"";
label2.text =#"";
}
[cell.contentView addSubview:label1];
[cell.contentView addSubview:label2];
[label1 release];
[label2 release];
return cell;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//implementation for row counter incrementer.
}
Try this.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
//take dictionary object from dataArray at selected index
//take Lable2 value as a string and convert it into integer and increment the integer value
//now convert this incremented integer value into string
//now save it new string in Lable2 for the object dictionary and add this dict object into dataArray at selected index
NSMutableDictionary * tempDict = [self.dataArray objectAtIndex:indexPath.row];
int tempLableInt = [[tempDict objectForKey:#"Lable2"] intValue];
tempLableInt = tempLableInt +1;
[tempDict setObject:[NSString stringWithFormat:#"%d",tempLableInt] forKey:#"Lable2"];
[self.dataArray replaceObjectAtIndex:indexPath.row withObject:tempDict];
[tableView reloadData];
}
just set nsdictionary value.In that set forkey is your uitableview didselectrowatindexpath value.Based on the for key value increment the value.
You could do the following
define this property in your class
NSMutableDictionary *dicCounter;
Then in your didSelectRowAtIndexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifier = [NSString stringWithFormat:#"%#,%#", indexPath.section, indexPath.row];
//Get the old counter
int counterForCell = [[dicCounter valueForKey:cellIdentifier] intValue];
//increment it
counterForCell++;
//set it in the dictionary
[dicCounter setValue:[NSNumber numberWithInt:counterForCell] forKey:cellIdentifier];
}
I have a plist with dictionary.
In the dictionary i have a string called "cellPic" that have url address of an image.
I'm trying to populate my table view with images that i put on my dropbox account & read them through the plist string.
("arrayFromPlist" is my array)
The problem is that when i run it, i'm getting an error in the console:
[__NSCFDictionary objectAtIndex:]: unrecognized selector
This is my code:
-(void) readPlistFromDocs
{
// Path to the plist (in the Docs)
NSString *rootPath =
[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0];
NSString *plistPath = [rootPath stringByAppendingPathComponent:#"Data.plist"];
NSLog(#"plistPath = %#",plistPath);
// Build the array from the plist
NSMutableArray *arrayFromDocs = [[NSMutableArray alloc] initWithContentsOfFile:plistPath];
if (arrayFromDocs)
{
NSLog(#"\n content of plist file from the documents \n");
NSLog(#"Array from Docs count = : %d", [arrayFromDocs count]);
}
arrayFromPlist = [[NSArray alloc] initWithArray:arrayFromDocs];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
// Returns the number of rows in a given section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrayFromPlist count];
NSLog(#"Array SIZE = %d",[arrayFromPlist count]);
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [aTableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
NSURL *url = [[NSURL alloc] initWithString:[[arrayFromPlist objectAtIndex:indexPath.row] objectForKey:#"cellPic"]];
NSData *urlData = [[NSData alloc] initWithContentsOfURL:url];
[[cell imageView] setImage:[UIImage imageWithData:urlData]];
return cell;
}
My other question is - how can i load the images asynchronous when i read the url from the plist string?
I tried to find an example for that but i found only asynchronous without uisng plist.
Thanks.
Change Following line
NSDictionary *arrayFromDocs = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
Best Tutorial for load the images asynchronous
Hope, this will help you..
I have a NSURL request that brings back an array of "name" and "phone", "etc"... The "name" Key shows up fine on the master table, but I'm having trouble figuring out how to get the rest of the array to show up on the detail table when I select the row. (I have the DetailerTableViewController working to accept the view). Any help would be appreciated.
Thanks,
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [rowsArray count];
NSLog(#"row count: %#",[rowsArray count]);
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *dict = [rowsArray objectAtIndex: indexPath.row];
cell.textLabel.text = [dict objectForKey:#"name"];
cell.detailTextLabel.text = [dict objectForKey:#"loginName"];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:0.0/255.0 green:207.0/255.0 blue:255.0/255.0 alpha:1.0];
self.title = NSLocalizedString(#"Master", #"Master");
NSURL *url = [NSURL URLWithString:#"http://10.0.1.8/~imac/iphone/jsontest.php"];
NSString *jsonreturn = [[NSString alloc] initWithContentsOfURL:url];
NSLog(jsonreturn); // Look at the console and you can see what the results are
NSData *jsonData = [jsonreturn dataUsingEncoding:NSUTF32BigEndianStringEncoding];
NSError *error = nil;
// In "real" code you should surround this with try and catch
NSDictionary * dict = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
if (dict)
{
rowsArray = [dict objectForKey:#"member"];
[rowsArray retain];
}
NSLog(#"Array: %#",rowsArray);
NSLog(#"count is: %i", [self.rowsArray count]);
[jsonreturn release];
}
You need to implement:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
to handle row selection and to push the view controller for the detail view.