Refresh table view? - ios

I think I have a pretty easy task, but somehow it doesn't want to work. I am a total beginner in objective-c, so I guess it's just a small mistake. I still don't really know what I do, currently it's more like copy&paste programming. Like I don't really know if I need the IBOutlet in the interface or as a property or as both.
What I have:
A ViewController with a Button, a Label and a Table View. The button connects to a sharepoints server and reads a list and adds the value to an array. This part works.
Delegate and DataSource outlet is connected to the View Controller.
What I want:
The array should be the datasource of the Table View, so I just want it to refresh after I've read the new data in the array. The test data I add in the viewDidLoad function to the array, shows up. So I guess I somehow connected the array to the table view.
I'll give you the full code:
ViewController.h:
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
{
IBOutlet UILabel *output;
IBOutlet UITableView *tableView;
NSMutableData *webData;
NSString *finaldata;
NSString *convertToStringData;
NSMutableString *nodeContent;
}
#property (nonatomic, retain) UILabel *output;
#property (nonatomic, weak) IBOutlet UITableView *tableView;
-(IBAction)invokeService:(UIButton *) sender;
#end
ViewController.m:
#import "ViewController.h"
#interface ViewController ()
{
NSMutableArray *foundUrlaub;
}
#end
#implementation ViewController
#synthesize output;
- (void)viewDidLoad
{
[super viewDidLoad];
// SOME TEST DATA... THIS SHOWS UP IN MY TABLE VIEW
foundUrlaub = [[NSMutableArray alloc]init];
[foundUrlaub addObject:#"first cell"];
[foundUrlaub addObject:#"second cell"];
[foundUrlaub addObject:#"third cell"];
}
-(IBAction)invokeService:(UIButton *) sender
{
// connection to sharepoint
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(#"didReceiveResponse");
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSLog(#"didReceiveData");
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"ERROR with the Connection");
NSLog(error.description);
}
-(BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace
{
NSLog(#"canAuthenticateAgainstProtectionSpace");
return YES;
}
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSLog(#"didReceiveAuthenticationChallenge");
NSURLCredential *credential = [NSURLCredential credentialWithUser:#"XXXXXX" password:#"XXXXXX" persistence:NSURLCredentialPersistenceForSession];
[[challenge sender] useCredential:credential forAuthenticationChallenge:challenge];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"DONE. Received Bytes: %d", [webData length]);
convertToStringData = [[NSString alloc] initWithData:webData encoding:NSUTF8StringEncoding];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"(?<=ows_Title=')(.*)(?=' ows_MetaInfo)" options:0 error:NULL];
NSArray *matches = [regex matchesInString:convertToStringData options:0 range:NSMakeRange(0, [convertToStringData length])];
// HERE I LOAD SOME DATA IN THE ARRAY
[foundUrlaub removeAllObjects];
for (NSTextCheckingResult *match in matches)
{
NSRange matchRange = [match rangeAtIndex:1];
NSString *matchString = [convertToStringData substringWithRange:matchRange];
NSLog(#"Match: %#", matchString);
[foundUrlaub addObject:matchString]; // <- ADDS 3 STRINGS TO ARRAY
}
// THIS DOES NOT WORK!
[tableView reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [foundUrlaub count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"TableItem";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
}
cell.textLabel.text = [foundUrlaub objectAtIndex:indexPath.row];
return cell;
}
#end

try using [_tableView reloadData]; You didn't #synthesize your tableView in your .m so you have to use the autosynthesized identifier

Your code looks fine ,
make sure
IBOutlet for tableView is connected properly
Datasource and delegates from nib is connected to the files owner
A must watch and a must read for you

You have to connect the Outlet in the Interfacebuilder to your UITableview tableView.

You are trying to reload table from separate thread. so UIView can be changed only from main thread so do something like this:
[tableView performSelectorOnMainThread:#selector(reloadData)
withObject:nil
waitUntilDone:YES];

Related

Pass Json Value to UICollection View

i want to display my images in grid view. i have used UICollection view controller,data which is i'm passing in JSON format.i cant able to display images using JSON format. Can anyone pls find my mistake? Here is my code
#interface ReceipeCollectionViewController()
{
NSMutableData *webdata;
NSURLConnection *connection;
NSMutableArray *contentarray;
NSMutableArray *array;
}
#end
#implementation ReceipeCollectionViewController
(void)viewDidLoad
{
[super viewDidLoad];
[array removeAllObjects];
[[self collectionView]setDelegate:self];
[[self collectionView]setDataSource:self];
array = [[NSMutableArray alloc] init];
}
(void)viewDidAppear:(BOOL)animated
{
NSString *serverurl=#"http://wesotech.com/web/myrecipe/web_services/recipe_listing.php?";
NSURL *url=[NSURL URLWithString:serverurl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
connection = [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webdata=[[NSMutableData alloc]init];
}
else
{
NSLog(#"Connection failure");
}
}
(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webdata appendData:data];
}
(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Fail with error");
}
(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSArray *results=[NSJSONSerialization JSONObjectWithData:webdata options:0 error:&error];
[array removeAllObjects];
[array addObjectsFromArray:results];
[[self collectionView]reloadData];
}
(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webdata setLength:0];
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [array count];
}
(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
[self.mySpinner stopAnimating];
static NSString *identifier = #"Cell";
UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
UIImageView *recipeImageView = (UIImageView *)[cell.contentView viewWithTag:100];
recipeImageView.image=[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]]];
UITextField *recipeTitleView =(UITextField *)[cell.contentView viewWithTag:101];
recipeTitleView.text=[[array objectAtIndex:indexPath.row]valueForKey:#"recname"];
return cell;
}
#end
My JSON Format is,
[
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704658059030.jpg","recname":"Italian Chicken","recid":"1"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704653421637.jpg","recname":"Fast Food Friday","recid":"2"},
{"image":"http:\/\/wesotech.com\/web\/myrecipe\/recipeimages\/2016080614704648912893.jpg","recname":"Honey Clazed Lamb Chops","recid":"3"}
]
Instead of escaping your URL with \, use percentage encoding in your JSON and decode it back to unescaped string using the below code
NSString *imageUrl = #"http%3A%2F%2Fwesotech.com%2Fweb%2Fmyrecipe%2Frecipeimages%2F2016080614704658059030.jpg";
NSString *url = [imageUrl stringByRemovingPercentEncoding];
Another important point: Since you are loading an image with http://, you should set Allow Arbitrary Loads to YES under App Transport Security Settings in your info.plist file.
Also, make a note that it is not advisable to set allow arbitrary loads as it would result in security issues. It would be better if you
could have all your network calls to use https://
Make a class of tableViewCell and assign that class name to cell of collectionView in utility area. Make the outlet of imageView in tableViewCell Class and access it in cellForItemAtIndexPath delegate method.
Then assign the image with this code :
[cell. recipeImageView sd_setImageWithURL:[NSURL URLWithString:[[array objectAtIndex:indexPath.row] valueForKey:#"image"]]];
This will surely help you.

Segue performing in story

I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
#import "thirdViewController.h"
#import "ViewController.h"
#import "DetailViewController.h"
#import "secondViewController.h"
#interface thirdViewController (){
NSDictionary *currencies;
NSMutableArray *arrayCurrenciesKeys;
NSMutableData *webData;
NSURLConnection *connection ;
NSMutableArray *array;
NSMutableArray *temp;
}
#end
#implementation thirdViewController
#synthesize tableView,cityname;
- (void)viewDidLoad
{
[super viewDidLoad];
self.title=#"Типи валют";
[[self tableView]setDelegate:self];
[[self tableView]setDataSource:self];
array=[[NSMutableArray alloc]init];
NSURL *url =[NSURL URLWithString:#"http:resources.finance.ua/ua/public/currency-cash.json"];
NSURLRequest *request =[NSURLRequest requestWithURL:url];
connection= [NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData alloc] init];
}
tableView.backgroundColor=[UIColor clearColor];
tableView.alpha=0.9;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [array count];
}
-(UITableViewCell*) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier =#"Cell"; UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Error");
}
-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed =[allDataDictionary objectForKey:#"organizations";
for(NSDictionary *diction1 in feed){
NSString *label1 = [diction1 objectForKey:#"cityId"];
[temp addObject:label1];
NSString *label2 =[[allDataDictionary objectForKey: #"cities" ] objectForKey:[NSString stringWithFormat:#"%#",label1]];
if(![array containsObject:label2]){
[array addObject:label2];}
else{
;
}
[[self tableView]reloadData];
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self performSegueWithIdentifier:#"Banks" sender:self];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:#"Banks"]) {
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#end
Also i add segue identificator in the storyboard. I also try to present it with navigation controller,but it doesn't work too.
I have three ViewControllers. In first I open thirdViewController and in thirdViewController I open secondViewController. I use segue to perform seondViewController, but id doesn't work.
I assume that your "first" is ViewController.h
1- Are you sure that the identifier of the segue from thirdViewController to secondViewController is #"Banks"?
You can be misleading it with the identifier of the segue from ViewController to thirdViewController.
2- Double check that you have the exact same string in Interface Builder and in code.
It can be #"Bankss" in Interface Builder and can be #"Banks" in code.

How do I populate my UITableView with data from JSON array?

I have been trying to populate my tableView for the pas 4 days and I keep hitting dead ends.
I have been through the questions on here and tried some of the suggestions that others have been given, but none of them seem to work. Basically I have JSON data sent from my website and that is populating an array that I then wish to put into a tableView.
The NSLog is returning all correct info, but seems to stop once the array is created, and doesn't have any data logging after the array populates.
here is my .h file
//
// reportsTestViewController.h
// TESG-iConnect
//
// Created by TESG on 7/03/14.
// Copyright (c) 2014 TESG. All rights reserved.
//
#import <UIKit/UIKit.h>
#interface reportsTestViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>{
IBOutlet UITableView *reportsTable;
NSString *response;
NSMutableArray *reportsArray;
}
#property (nonatomic, retain) NSString *response;
#property (nonatomic, strong) NSMutableData *myDataIvar;
#end
and my .m file
//
// reportsTestViewController.m
// TESG-iConnect
//
// Created by TESG on 7/03/14.
// Copyright (c) 2014 TESG. All rights reserved.
//
#import "reportsTestViewController.h"
#import "ReportsDataObject.h"
#interface reportsTestViewController ()
#end
#implementation reportsTestViewController
#synthesize response;
#synthesize myDataIvar;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
#pragma mark NSURLConnection Delegate Methods
//
//Create your request pointing to the test page
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://www.tesg.com.au/allCustBuild.php"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15.0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
//initialize it when you create your connection
if (connection){
self.myDataIvar = [[NSMutableData alloc] init];
}
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
[self.myDataIvar setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[self.myDataIvar appendData:data];
[reportsTable reloadData];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
NSLog(#"Connection Failed: %#", error.userInfo);
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
//this is where you would parse the data received back from the server
NSString *responseString = [[NSString alloc] initWithData:self.myDataIvar encoding:NSUTF8StringEncoding];
NSLog(#"Received Data: %#",responseString);
[self setupReportsFromJSONArray:self.myDataIvar];
}
-(void)connectionWasASuccess:(NSData *)data{
[self setupReportsFromJSONArray:data];
}
-(void)setupReportsFromJSONArray:(NSData*)dataFromReportsArray{
NSError *error;
// NSMutableArray *reportsArray = [[NSMutableArray alloc] init];
NSArray *arrayFromServer = [NSJSONSerialization JSONObjectWithData:dataFromReportsArray options:0 error:&error];
if(error){
NSLog(#"error parsing the json data from server with error description - %#", [error localizedDescription]);
}
else {
reportsArray = [[NSMutableArray alloc] init];
for(NSDictionary *eachReport in arrayFromServer)
{
ReportsDataObject *report = [[ReportsDataObject alloc] initWithJSONData:eachReport];
[reportsArray addObject:report];
}
NSLog(#"Array Populated");
NSLog(#"%u reports found",reportsArray.count);
//Now you have your reportsArray filled up with all your data objects
}
}
-(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//We check against table to make sure we are displaying the right number of cells
// for the appropriate table. This is so that things will work even if one day you
//decide that you want to have two tables instead of one.
// if(tableView == reportsTable)
{
return([reportsArray count]);
}
return 0;
NSLog(#"%u",reportsArray.count);
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *reportsTableIdentifier = #"ReportsTableCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reportsTableIdentifier];
if(cell)
{
//set your configuration of your cell
}
//The beauty of this is that you have all your data in one object and grab WHATEVER you like
//This way in the future you can add another field without doing much.
if([reportsArray count] == 0){
cell.textLabel.text = #"no reports to show";
}
else{
ReportsDataObject *currentReport = [reportsArray objectAtIndex:indexPath.row];
cell.textLabel.text = [currentReport reportName];
// in the future you can grab whatever data you need like this
//[currentReport buildingName], or [currentReport reportName];
}
return(cell);
}
#end
and my NSLog output
2014-03-11 14:40:13.006 TESG-iConnect[29384:a0b] PostData:
username=&password= 2014-03-11 14:40:13.119
TESG-iConnect[29384:a0b] Response code: 200 2014-03-11 14:40:13.119
TESG-iConnect[29384:a0b] Response ==> {"success":1} 2014-03-11
14:40:13.120 TESG-iConnect[29384:a0b] Success: 1 2014-03-11
14:40:13.120 TESG-iConnect[29384:a0b] Login SUCCESS 2014-03-11
14:40:14.677 TESG-iConnect[29384:a0b] Received Data:
[{"id":"7684","title":"POT Feb 2011","date":"2011-04-18
10:49:27","link":"1303087767_POT 113 Lonsdale St
feb11.pdf"},{"id":"7683","title":"Audit Feb 2011","date":"2011-04-18
10:49:12","link":"1303087751_CA 113 Lonsdale St feb
11.pdf"},{"id":"11189","title":"AESMR 2011","date":"2012-01-30 09:49:28","link":"1327877368_AESMR 113 Lonsdale Street, Melbourne
2011.pdf"},{"id":"8761","title":"Annual 2011","date":"2011-08-02 12:55:56","link":"1312253756_Annual Passive 113 Lonsdale St May
2011.pdf"},{"id":"8762","title":"Audit May 2011","date":"2011-08-02 12:56:16","link":"1312253775_CA 113 Lonsdale Street May
11.pdf"},{"id":"8763","title":"POT May 2011","date":"2011-08-02 12:56:34","link":"1312253794_POT 113 Lonsdale Street May
2011.pdf"},{"id":"10286","title":"Audit Aug 2011","date":"2011-11-08 14:31:34","link":"1320723094_CA 113 Lonsdale Street Aug
11.pdf"},{"id":"10287","title":"POT Aug 2011","date":"2011-11-08 14:31:46","link":"1320723106_POT 113 Lonsdale Street Aug 2011.pdf"}]
2014-03-11 14:40:14.678 TESG-iConnect[29384:a0b] Array Populated
2014-03-11 14:40:14.678 TESG-iConnect[29384:a0b] 8 reports found
I cannot seem to find where the code is not working. can someone point me in the right direction please??
EDIT TO INCLUDE dataObject JUST IN CASE
//
// ReportsDataObject.h
// TESG-iConnect
//
// Created by TESG on 7/03/14.
// Copyright (c) 2014 TESG. All rights reserved.
//
#import <Foundation/Foundation.h>
#interface ReportsDataObject : NSObject
-(id)initWithJSONData:(NSDictionary*)data;
#property (assign) NSInteger reportId;
#property (strong) NSString *buildingName;
#property (strong) NSString *reportName;
#property (strong) NSString *reportDate;
#property (strong) NSString *reportLink;
#end
//
// ReportsDataObject.m
// TESG-iConnect
//
// Created by TESG on 7/03/14.
// Copyright (c) 2014 TESG. All rights reserved.
//
#import "ReportsDataObject.h"
#implementation ReportsDataObject
#synthesize reportId;
#synthesize buildingName;
#synthesize reportName;
#synthesize reportDate;
#synthesize reportLink;
-(id)initWithJSONData:(NSDictionary*)data{
self = [super init];
if(self){
//NSLog(#"initWithJSONData method called");
self.reportId = [[data objectForKey:#"id"] integerValue];
self.buildingName = [data objectForKey:#"buildingname"];
self.reportName = [data objectForKey:#"reportname"];
self.reportDate = [data objectForKey:#"reportdate"];
self.reportLink = [data objectForKey:#"reportlink"];
}
return self;
}
#end
You haven't initialised your uitableviewcell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell =[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
I think you need to call reloadData at the end of the setupReportsFromJSONArray method rather than in didReceiveResponse since you don't create the reportsArray until then.

iOS Basic Request to webservice

Can anyone point me in the right direction of a good tutorial or possibly answer this question.
I have some JSON to be returned on my web server
{
first_name: "Joe";
last_name: "Smith";
department: "Human Resources";
}
How do I make a http request to get this information at the click of a button and display as text on the iphone.?
Complete newbie so please 'dumb' down.
create a jsonviewcontroller class
#import <UIKit/UIKit.h>
#interface JSONViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,NSURLConnectionDataDelegate>
{
NSString *label;
}
#property (weak, nonatomic) IBOutlet UITableView *myTableView;
- (IBAction)getTop10AlbumAction:(id)sender;
#end
then in implementation class:-
#import "JSONViewController.h"
#interface JSONViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSString *category;
}
#end
#implementation JSONViewController
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[webData setLength:0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(#"Failed with Error");
}
this is the place where actual parsing happens, we fetch the title of albums from respective dictionary and arrays. to understand this first go to this link http://jsonviewer.stack.hu/#http://itunes.apple.com/us/rss/topalbums/limit=10/json this is the json viewer which shows the structure of the content that we are going to access. dont panic! its really easy if u try parsing some json urls
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSDictionary *feed=[allDataDictionary objectForKey:#"feed"];
NSArray *arrayOfEntry=[feed objectForKey:#"entry"];
for (NSDictionary *dict in arrayOfEntry) {
NSDictionary *title=[dict objectForKey:#"title"];
NSString *label=[title objectForKey:#"label"];
[array addObject:label];
}
[[self myTableView]reloadData];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[array count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier=#"cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//clear background color
[[cell textLabel] setBackgroundColor:[UIColor clearColor]];
[[cell detailTextLabel] setBackgroundColor:[UIColor clearColor]];
//set cell text
cell.textLabel.text=[array objectAtIndex:indexPath.row];
//set cell accessory type
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
return cell;
}
here we specify the itunes url that we are going to parse and make connection request
- (IBAction)getTop10AlbumAction:(id)sender {
NSURL *url=[NSURL URLWithString:#"http://itunes.apple.com/us/rss/topalbums/limit=10/json"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if (connection) {
webData=[[NSMutableData alloc]init];
}
[[self myTableView]reloadData];
}
#end
i hope i have made it clear enough!
I suggest you two different tutorials:
Creating a simple interface. Here is a sample from Apple that have a button and a text displayed: iOS Button - Label sample
Insert into controller code (i.e. changeGreeting:) the code that calls the webservice: iOS JSON Webservice tutorial

Getting JSON data and populate TableView in iOS

Good evening!
I need some help. I'm getting some data from the Google Places API in JSON format but I'm not getting to populate a TableView in iPad (SplitView Based Application). I starting with iOS developing so probably there are many mistakes! I used a project example that used Twitter API to retrieve the posts and just renamed the JSON data names.
I have four files that are used in the project and implement the function:
SimpleSplitController.h
SimpleSplitController.m
SplitSampleAppDelegate.h
SplitSampleAppDelegate.m
I get an ERROR at SplitSampleDelegate.m file, as it's checked there...
If someone may help me, I'd be very grateful!
Here are the codes that implement:
SplitSampleAppDelegate.h
#import <UIKit/UIKit.h>
#class APTabBarControllerForSplitController;
#interface SplitSampleAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate> {
NSMutableData *responseData;
NSMutableArray *tweets;
}
#property (nonatomic, retain) IBOutlet UIWindow *window;
#property (nonatomic, retain) IBOutlet APTabBarControllerForSplitController *tabBarController;
#property (nonatomic, retain) NSMutableArray *tweets;
#end
SplitSampleAppDelegate.m
#import "SplitSampleAppDelegate.h"
#import "APTabBarControllerForSplitController.h"
#implementation SplitSampleAppDelegate
#synthesize window=_window;
#synthesize tabBarController=_tabBarController;
#synthesize tweets;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
self.tabBarController.delegate = self;
// Override point for customization after application launch.
// Add the tab bar controller's current view as a subview of the window
// Add the view controller's view to the window and display.
responseData = [[NSMutableData data] retain];
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"https://maps.googleapis.com/maps/api/place/search/json?location=-15.815347,-47.9164097&radius=500&types=restaurant&sensor=true&key=AIzaSyBLY-lBALViJ6ybrgtOqQGhsCDQtsdKsnc"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
self.window.rootViewController = self.tabBarController;
[self.window makeKeyAndVisible];
return YES;
}
#pragma mark NSURLConnection delegate methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *results = [responseString JSONValue];
NSMutableArray *allTweets = [results objectForKey:#"results"];
//This is the part that I get an ERROR
[viewController setTweets:allTweets];
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
SimpleSplitController.h
#import <UIKit/UIKit.h>
#import "APSplitViewController.h"
#import <MapKit/MapKit.h>
#interface SimpleSplitController : APSplitViewController {
NSMutableData *responseData;
NSArray *tweets;
}
#property (nonatomic, retain) UIViewController *left;
#property (nonatomic, retain) UIViewController *right;
#property (nonatomic, retain) NSArray *tweets;
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;
#end
SimpleSplitController.m
#import "SimpleSplitController.h"
#import <QuartzCore/QuartzCore.h>
#import "JSON/JSON.h"
#import "Tweet.h"
#interface SimpleSplitController()
- (UIColor *) randomColor;
- (UIViewController*) randomViewController1;
- (UIViewController*) randomViewController2;
- (UIViewController*) randomViewController3;
- (void) buttonPushRandomViewController1;
- (void) buttonPushRandomViewController2;
#end
#implementation SimpleSplitController
#synthesize left, right;
#synthesize tweets;
- (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];
}
// Configure the cell...
NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];
cell.textLabel.text = [aTweet objectForKey:#"name"];
cell.textLabel.adjustsFontSizeToFitWidth = YES;
cell.textLabel.font = [UIFont systemFontOfSize:12];
cell.textLabel.minimumFontSize = 10;
cell.textLabel.numberOfLines = 4;
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.detailTextLabel.text = [aTweet objectForKey:#"vicinity"];
NSURL *url = [NSURL URLWithString:[aTweet objectForKey:#"icon"]];
NSData *data = [NSData dataWithContentsOfURL:url];
cell.imageView.image = [UIImage imageWithData:data];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;
}
Probable you are wrong here. You are checking object, instead of value.
NSMutableArray *allTweets = [results valueForKey:#"results"];
Jope your problem is resolved.

Resources