Add UIProgressView to a TableView Cell - iphone

I have an app that presents Table View of different files. I have it set up to Asynchronously download, and would like to have the selected cell show a progress bar. I've looked online all afternoon, and everything I have found so far seems real incomplete on how to do this. Here is my code so far for the download, and set up to have a progressview show download status.
Code:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row];
NSURL *url = [NSURL URLWithString:entry.articleUrl];
self.nameit = entry.articleTitle;
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
progress.hidden = NO;
[receivedData setLength:0];
expectedBytes = [response expectedContentLength];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length] / (float)expectedBytes;
[progress setProgress:progressive];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[connection release];
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[currentURL stringByAppendingString:#".mp3"]];
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[receivedData writeToFile:pdfPath atomically:YES];
progress.hidden = YES;
[connection release];
}

First, add an UIProgressView variable to you interface, so that you can reference to it from any method in your class.
Then, when user selects it. you have to initialize it
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell =[tableView cellForRowAtIndexPath:indexPath];
progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
progress.frame = CGRectMake(10, 10, 30, 30);
progress.progress = 0.0;
progress.center = CGPointMake(23,21);
[cell.contentView addSubview:progress];
}
Now you can update a progressBar as the file downloads and after it just send[progress removeFromSuperView]
That's it!

Related

i want add json framework in ios6 and using that how to fetch data from server? [duplicate]

This question already has answers here:
json parsing+iphone
(4 answers)
Closed 9 years ago.
I have to retrieve data from web-service and store in to table-view.
I have one framework but that cant work for me that is here
HERE PROBLEM IS USING THAT CAN'T ALLOWED TO CREATE CREATE OBJECT OF IT.
Thank you
You don't need to create the object of json.h file. You just need to import json.h file and then use it by [responseString JSONValue].
check this code
#interface videoViewController ()
{
NSMutableData *webData;
NSURLConnection *connection;
NSMutableArray *array;
NSMutableArray *array2;
}
- (void)viewDidLoad
{
[super viewDidLoad];
array=[[NSMutableArray alloc]init];
array2=[[NSMutableArray alloc]init];
NSURL *url=[NSURL URLWithString:#"http://localhost/videosphp/videoname2.php"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
connection=[NSURLConnection connectionWithRequest:request delegate:self];
if(connection)
{
webData=[[NSMutableData 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
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"alert" message:#"Unable to connect internet. Please check your internet connection" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
return;
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//use NSDictionary if the data in dictionary
NSArray *allDataArray=[NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
for (NSDictionary *diction in allDataArray)
{
NSString *videoname=[diction objectForKey:#"videoname"];
[array addObject:videoname];
}
[[self tableview]reloadData];
}
-(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:UITableViewCellAccessoryDisclosureIndicator reuseIdentifier:CellIdentifier];
}
cell.textLabel.text=[array objectAtIndex:indexPath.row];
return cell;
}

Loading Json into uitableview

I am trying to load json into a uitableview. I have worked with json before but never used it with a tableview. I keep getting this error: -[__NSCFNumber count]: unrecognized selector sent to instance. I'm pretty sure it is because in the numberOfRowsInSection method im returning the count of the array. Please let me know how to fix this or if I am missing something and not seeing it.
Here is he code:
.h file
#interface HistoryViewController : UITableViewController <UITableViewDataSource, UITableViewDelegate>
{
NSArray *jsonData;
NSMutableData *responseData;
}
.m file
- (void)viewDidLoad
{
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"Json url"]];
[[NSURLConnection alloc] initWithRequest:request delegate:self ];
[super viewDidLoad];
}
- (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 {
NSLog(#"Connection failed: %#", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
[connection release];
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *dictionary = [responseString JSONValue];
NSArray *response = [dictionary objectForKey:#"name"];
jsonData = [[NSArray alloc] initWithArray:response];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return jsonData.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [[UITableViewCell alloc]
initWithStyle:UITableViewCellStyleDefault
reuseIdentifier:#"cell"];
cell.textLabel.text = [jsonData objectAtIndex:indexPath.row];
return cell;
}
All right, I notice that your array is never initialized until the connectionDidFinishLoading method is run. The delegate methods for your data table are likely running before connectionDidFinishLoading, so you should initialize your jsonData array in viewDidLoad instead of connectionDidFinishLoading.
You can keep your connectionDidFinishLoading calls the same, but make sure you call reloadData on your data table at the end of the connectionDidFinishLoading method to fill out your data table with the downloaded data.

NSURLConnection and SBJSon in AppDelegate

I'm in xCode 4.2 using ARC and Storyboard (iOS 5). I suppose to put Tweets to my TableViewController. As I placed my NSURLConnection, everything goes fine and I have the response already in tweets(NSArray) in the delegate. The problem is it doesn't populate the table view. I am using SBJson for the received data. Am I missing something?
AppDelegate.m
#import "AppDelegate.h"
#import "TwitterViewController.h"
#import "SBJson.h"
#implementation AppDelegate
#synthesize window = _window;
#synthesize receivedData;
#synthesize tableViewController;
#synthesize tweets;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
tweets = [NSMutableArray array];
NSURLRequest *request = [NSURLRequest requestWithURL:
[NSURL URLWithString:#"http://search.twitter.com/search.json?q={username}&rpp=5"]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
if (theConnection) {
receivedData = [NSMutableData data];
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
NSLog(#"Connection failed! Error - %# %#",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(#"Succeeded! Received %d bytes of data",[receivedData length]);
NSString *responseString = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
NSDictionary *results = [responseString JSONValue];
NSArray *allTweets = [results objectForKey:#"results"];
[tableViewController setTweets:allTweets];
}
#end
This is the delegate methods in my table view controller.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [tweets count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"twitter";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSDictionary *aTweet = [tweets objectAtIndex:[indexPath row]];
NSString *textFrom = [aTweet objectForKey:#"text"];
cell.textLabel.text = textFrom;
return cell;
}
I really need some advice.
Table reload. Gosh! I learned!

iphone load table with wcf

atm i can successfully loading data from a WFC, read the json and put it on the right objects.
But my problem comes when i need to show a table with this data, cuz i don't know where to play the method or when should i call it. Atm looks like the table is created and after that i get the data from the web. Should i reload the table or can i get the info before the class calls cellForRowAtIndexPath: ?
Is there a way to make a connection synchronic and not synchronic? because in this case, if i cant get the list of eventos form wfc its has not point showing a table. So
Thx in advance!
my code:
-(id)init{
//call superclass designated inizialzer
self= [super initWithStyle:UITableViewStyleGrouped];
if(self){
[[self navigationItem] setTitle:#"Eventos"];
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://xxx.xxx.xxx.xxx/..."]];
[[[NSURLConnection alloc] initWithRequest:request delegate:self]autorelease];
}
return self;
}
about connection:
- (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 {
// label.text = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSError *error;
SBJSON *json = [[SBJSON new] autorelease];
NSDictionary *luckyNumbers = [json objectWithString:responseString error:&error];
[responseString release];
if (luckyNumbers == nil)
// label.text = [NSString stringWithFormat:#"JSON parsing failed: %#", [error localizedDescription]];
[luckyNumbers release];
else {
for (NSDictionary *object in [luckyNumbers objectForKey:#"EResult"]) {
Evento *e=[[Evento alloc] init];
e.nombre= [object objectForKey:#"nombre"];
e._id= (int)[object objectForKey:#"id"];
e.fecha= [object objectForKey:#"fecha"];
[[EventoStore defaultStore]addEvento:e];
[e release];
}
}
}
about the table it self:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [[[EventoStore defaultStore] allEventos]count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
//check for reusable cell first and use it
UITableViewCell *cell= [tableView dequeueReusableCellWithIdentifier:#"UITableViewCell"];
//if there is no reusable cell, we create one
if(!cell){
cell= [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1
reuseIdentifier:#"UITableViewCell"]autorelease];
}
Evento *e=[[[EventoStore defaultStore] allEventos] objectAtIndex:[indexPath row]];
[[cell textLabel] setText:[e nombre]];
return cell;
}
-(void)tableView:(UITableView *) aTableView didSelectRowAtIndexPath:(NSIndexPath *) indexPax{
LotesViewController *loteViewController= [[[LotesViewController alloc]init]autorelease];
NSArray *eventos=[[EventoStore defaultStore]allEventos];
[loteViewController setEvento: [eventos objectAtIndex:[indexPax row]]];
[[self navigationController]pushViewController:loteViewController animated:YES];
}
you should reload the table after getting the data. you can show the activity indicator on the table till you get the data and once you get the data, you can remove the activity indicator and reload the table. this way you can find the solution to your problem. No need to go for synchronous connection. Just add the activity indicator once the connection is satrted and remove it when data comes.

Adding a new row in a UITableView

HI Everyone,
It is my first post here and this is my problem:
I am trying to get some data from a REST API call and show then in a UITableView.
This s what I am doing:
in the viewDidLoad: 1) here I initialize my array of things to show in the Table (that is empty at the beginning) 2) the table is loaded (with 0 rows) and 3) then the HTTP async call is issued.
Done this I do my stuff with the HTTP Response and when ready I call the reloadData on my table. Here the strange happens.
numberOfRowsInSelection returns me the correct number of rows
but
tableView:cellForRowAtIndexPath:indexPath for the indexPath.row always returns me zero!
so no new row is added to the table.
- (void)doJSONRequest{
responseData = [[NSMutableData data] retain];
NSString *addr = [[NSString alloc] initWithFormat:#"http://localhost:8080/blabla/v1/items?count=10"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[addr release];
}
- (void)doJSONRequestWithURL:(NSString *)url{
responseData = [[NSMutableData data] retain];
NSString *addr = [[NSString alloc] initWithFormat:url];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:addr]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
[addr release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
//NSLog(#"[%#] connection:didReceiveResponse %#",[self class], response);
[responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
//NSLog(#"[%#] connection:didReceiveData %#",[self class], data);
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"[%#]",[NSString stringWithFormat:#"Connection failed: %#", [error description]]);
UIAlertView *alert = [[UIAlertView alloc] init];
[alert setTitle:#"NETWORK ERROR!"];
[alert setMessage:#"App will close"];
[alert setDelegate:self];
[alert addButtonWithTitle:#"Close"];
[alert show];
[alert release];
[alert show];
[alert release];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
//NSLog(#"[%#] connectionDidFinishLoading %#",[self class], connection);
[connection release];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSDictionary *res = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]];
NSDictionary *tmp = [res valueForKey:#"reviews"];
tmp = [tmp valueForKey:#"reviews"];
NSEnumerator *e = [tmp objectEnumerator];
NSDictionary *tmp_review;
int i=0;
while (tmp_review = [e nextObject]) {
//NSLog(#"tmp_review %#", tmp_review);
//NSLog(#"count %d", i++);
MyObject r = [... doing my staff...]
[reviews addObject: r];
[r release];
};
[reviewListTableView reloadData];
[responseString release];
}
- (void)viewDidLoad {
//- (void)initUI {
//review is the array where I put my data
//it is empty at the beginning
reviews = [[NSMutableArray alloc] initWithObjects:nil];
[super viewDidLoad];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [reviews count]
}
Sounds like you may not have properly implemented numberOfSectionsInTableView:. You should log indexPath.section in tableView:cellForRowAtIndexPath:indexPath to see what section value you are passing. You will have multiple indexPath.row values of zero because there is a zero row for each section.
add new object in the array and [mytableview reloadData];
Implement following data source return number of section to be present in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;
In tableView:cellForRowAtIndexPath:indexPath check section number and do your operation.
Note: If you don't need sections you can remove it.