Load Only Few Cell When Table View DidScroll in ios - ios

I made an application that use JSON Data and WebServices containing more pages when I scroll the UITableView. This fetches and displays the next set of data. Next page consists of 10 sets of data. But I only want to show 5 of them. How is it possible? If possible, please share the code.
Here's my code :
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
pageNum = pageNum + 1;
[self getData];
}
-(void)getData
{
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.truemanindiamagazine.com/webservice/news.php?page=%d",pageNum]];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL:url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
And fetch data method code :
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.newsTable reloadData];
NSLog(#"images,%#",self.imageArray);
}
}
[self.spinner stopAnimating];
self.spinner.hidesWhenStopped=YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.imageArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
And Remaining Code is :
{
[super viewDidLoad];
pageNum=0;
self.imageArray =[[NSMutableArray alloc]init];
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.truemanindiamagazine.com/webservice/news.php?page=%d",pageNum]];
[self.newsTable setShowsHorizontalScrollIndicator:NO];
[self.newsTable setShowsVerticalScrollIndicator:NO];
SDWebImageManager.sharedManager.imageDownloader.maxConcurrentDownloads = 3;
SDWebImageManager.sharedManager.imageDownloader.executionOrder = SDWebImageDownloaderLIFOExecutionOrder;
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
}
-(CustumCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier=#"Cell";
CustumCell *cell=[tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell ==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustumCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
{
[cell.spinner startAnimating];
NSDictionary *dict = [self.imageArray objectAtIndex:indexPath.section];
NSString *img2=[dict valueForKey:#"post_image"];
[cell.imagePhoto sd_setImageWithURL:[NSURL URLWithString:[img2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:#"Setting.png"] options:SDWebImageHighPriority completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
[cell.spinner stopAnimating];
cell.spinner.hidesWhenStopped=YES;
}];

Take a temparary array alloc and try to add the data from the server to this arrray.
Now I do the implementation for this.
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if([mTenarray count]==0) {
pageNum = pageNum + 1;
[self getData];
} else {
[self.imageArray addObjectsFromArray:mTenarray];
[mTenarray removeAllObjects];
[self.newsTable reloadData];
}
}
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length > 0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.mTenarray addObjectsFromArray:arr];
NSArray *mfivedatarray = [self.mTenarray subarrayWithRange:NSMakeRange(0, 5)];
[self.imageArray addObjectsFromArray:mfivedatarray];
self.mTenarray // remove first five objects
[self.newsTable reloadData];
NSLog(#"images,%#",self.imageArray);
}
}
[self.spinner stopAnimating];
self.spinner.hidesWhenStopped=YES;
}
In some place I wrote the concept to implement

Related

how to show array data on UITableViewCell?

How to array data reload in UITableView? I use a web services and fetch data stored in a array. I got a data and print on consol but same array can't reload in TableView.
Please help me how to show data on table view i trying to many times but can't show data.
JSON
{
"status": {
"event": [
{
"event_id": "28",
"event_name": "Event name",
"event_title": "svsav",
"img": "http:\/\/edutimeapp.com\/toshow\/chamber-of-commerc\/uploads\/1461402793-Vtcg8pRB.jpg",
"event_date": "2016-04-05",
"event_time": "12:00",
"event_detail": "svsa"
},
viewcontroller
#import "ViewController.h"
#import "celltable.h"
#interface ViewController ()
{
NSArray*name;
}
#end
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableview setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_event.php"]];
response =[[NSMutableData alloc]init];
[NSURLConnection connectionWithRequest:req delegate:self];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[response appendData:data];
NSLog(#"error receving data %#",response);
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",son);
NSError *jsonParsingError = nil;
NSDictionary *retrievedJTransD = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSArray* retrievedJTrans = retrievedJTransD[#"status"][#"event"];
name = [retrievedJTrans valueForKey:#"event_name"];
NSLog(#"success %#", name);
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [name count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"tableview cell");
celltable *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.date.text=[NSString stringWithFormat:#"%#",[name objectAtIndex:indexPath.row]];
return cell;
}
Your mistake is cannot reload the tableview, next you did not correctly set the array values, Use this below code,
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *error;
NSLog(#"Error in receiving data %#",error);
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"response data %#",son);
NSError *jsonParsingError = nil;
NSDictionary *retrievedJTransD = [NSJSONSerialization JSONObjectWithData:response options:0 error:&jsonParsingError];
NSArray* retrievedJTrans = retrievedJTransD[#"status"][#"event"];
//you are wrong in name array change it.
name = retrievedJTrans;
NSLog(#"success %#", name);
[self.tableview reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [name count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"tableview cell");
celltable *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.date.text=[NSString stringWithFormat:#"%#",[[name objectAtIndex:indexPath.row] valueForKey:#"event_name"]];
return cell;
}
hope its helpful
After You get response from WS
dispatch_async(dispatch_get_main_queue(), ^{
[self.yourTableview reloadData];
});
Always remember that when you need reload tableview and you are using WS Call or any other block operations reload it in main thread

How to implement search option with webservice url in ios, using objective C

I'm getting data from a web service.If we pass any string through service url, then it will returns data according to it.I have implemented and display data in a tableview . now what I want is to implement search option for it. so I used uisearchcontroller and to do that.but it is not working well.I mean if we send letter 'y' for the web service, it will return all the results that starts from y. this is my code.
- (void)viewDidLoad {
[super viewDidLoad];
self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
self.searchController.searchResultsUpdater = self;
self.searchController.dimsBackgroundDuringPresentation = NO;
self.searchController.searchBar.scopeButtonTitles = #[NSLocalizedString(#"ScopeButtonCountry", #"Airport"), NSLocalizedString(#"ScopeButtonCapital", #"AirportCode")];
self.searchController.searchBar.delegate = self;
//self.searchController.searchBar.frame = CGRectMake(self.searchController.searchBar.frame.origin.x, self.searchController.searchBar.frame.origin.y, self.searchController.searchBar.frame.size.width, 44.0);
self.mtableView.tableHeaderView = self.searchController.searchBar;
self.definesPresentationContext = YES;
[self.searchController.searchBar sizeToFit];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (void)getAirports:(NSString *)needeedString
{
airportList = nil;
needeedString = [NSString stringWithFormat:#""];
NSString *apiKey = [NSString stringWithFormat:#"some api"];
NSString *fullUrl = [NSString stringWithFormat:#"someurl%#%#",apiKey,needeedString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:fullUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *result = (NSArray *)responseObject;
airportList = [NSMutableArray array];
for (NSDictionary *all in result)
{
Details *d1 = [Details new];
d1.airport = [all objectForKey:#"Airport"];
[airportList addObject:d1];
[self.mtableView reloadData];
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = searchController.searchBar.text;
if (searchString == nil || [searchString isEqual: #""]) {
[self getAirports:#""];
[self.mtableView reloadData];
}
[self getAirports:searchString];
[self.mtableView reloadData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [airportList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ci"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"ci"];
}
Details *newDetails = [airportList objectAtIndex:indexPath.row];
cell.textLabel.text = newDetails.airport;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Details *newDetails = [airportList objectAtIndex:indexPath.row];
NSString *selectedText = newDetails.airport;
[[NSUserDefaults standardUserDefaults] setObject:selectedText forKey:#"st"];
[[NSUserDefaults standardUserDefaults] synchronize];
[self dismissViewControllerAnimated:YES completion:nil];
}
Please find the below changes I have made ,hope it will work
- (void)getAirports:(NSString *)needeedString
{
airportList = nil;
needeedString = [NSString stringWithFormat:#""];
NSString *apiKey = [NSString stringWithFormat:#"some api"];
NSString *fullUrl = [NSString stringWithFormat:#"someurl%#%#",apiKey,needeedString];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:fullUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *result = (NSArray *)responseObject;
airportList = [NSMutableArray array];
for (NSDictionary *all in result)
{
Details *d1 = [Details new];
d1.airport = [all objectForKey:#"Airport"];
[airportList addObject:d1];
//remove reload data method from here because it will reload your table on each iteration
}
dispatch_async(dispatch_get_main_queue(), ^{
//reload on main thread
[self.mtableView reloadData];
});
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
}
- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
NSString *searchString = searchController.searchBar.text;
if (searchString != nil && ![searchString isEqual: #""]) {
[self getAirports:searchString];
}
//here there is no need to reload
//also changed condition
}
Call reload in dispatch main queue:
dispatch_async(dispatch_get_main_queue(), ^{
[self.mtableView reloadData];
});
I guess In method
- (void)getAirports:(NSString *)needeedString
remove
[self.mtableView reloadData];
outside the for loop
and you can call reloadData like
self.mtableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES

How to Download Faster and Faster Image From Json Parsing with SDWebImageLibrary?

I make a Application that contain tableview with image and it Contain JSON Data.it is working Good But image downloading take upto 15minutes how do i fast?
My code for image Cache is
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH,0)
- (void)viewDidLoad
{
[self.spinner startAnimating];
[super viewDidLoad];
Reachability *networkReachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [networkReachability currentReachabilityStatus];
if (networkStatus == NotReachable)
{
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"No Internet Avaliable" message:#"Please Check YOur Internet Connection" delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else
{
pageNum=0;
self.imageArray =[[NSMutableArray alloc]init];
NSURL * url=[NSURL URLWithString:[NSString stringWithFormat:#"http://www.truemanindiamagazine.com/webservice/news.php?page=%d",pageNum]];
[self.newsTable setShowsHorizontalScrollIndicator:NO];
[self.newsTable setShowsVerticalScrollIndicator:NO];
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: url];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
}
}
-(void)fetchedData:(NSData *)responsedata
{
if (responsedata.length >0)
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
if ([[_json objectForKey:#"data"] isKindOfClass:[NSArray class]])
{
NSArray *arr = (NSArray *)[_json objectForKey:#"data"];
[self.imageArray addObjectsFromArray:arr];
[self.newsTable reloadData];
NSLog(#"images,%#",self.imageArray);
}
if (self.imageArray.count == 0)
{
self.newsTable.scrollEnabled=NO;
}
else
{
self.newsTable.scrollEnabled=YES;
}
}
[self.spinner stopAnimating];
self.spinner.hidesWhenStopped=YES;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.imageArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (self.imageArray == nil || self.imageArray.count <1)
{
return 0;
}
else
{
return 1;
}
}
-(CustumCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier=#"Cell";
CustumCell *cell=[tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell ==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"CustumCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
{
[cell.spinner startAnimating];
NSDictionary *dict = [self.imageArray objectAtIndex:indexPath.section];
NSString *img2=[dict valueForKey:#"post_image"];
[cell.imagePhoto sd_setImageWithURL:[NSURL URLWithString:[img2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:#"Setting.png"] options:SDWebImageHighPriority completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL)
{
[cell.spinner stopAnimating];
cell.spinner.hidesWhenStopped=YES;
}];
it Shows CashedImage Perfectly but take a time to Downloaded image that can not be cashed
please Give me Solution For that.

Parse an image in to the Collection-view Custom cell in ios

i want to parse an image from web services and show onto the collection view custom cell for this i write a code as
in my .h file
#property(strong,nonatomic)IBOutlet UICollectionView *imagecollection;
#property(strong,nonatomic)NSArray *imagesa;
#property(strong,nonatomic)NSDictionary *json;
#property(strong,nonatomic)NSArray *aimages;
and in my .m file
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)
#define imageURL [NSURL URLWithString:#"http://www.truemanindiamagazine.com/webservice/gallery_image.php"]
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
data = [NSData dataWithContentsOfURL: imageURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:data waitUntilDone:YES];
});
[self.imagecollection registerNib:[UINib nibWithNibName:#"Custumcell" bundle:nil] forCellWithReuseIdentifier:#"CellIdentifier"];
}
-(void)fetchedData:(NSData *)responsedata
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa=[json objectForKey:#"data"];
NSLog(#"images,%#",self.imagesa);
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return self.imagesa.count;
}
-(Custumcell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Custumcell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"CellIdentifier" forIndexPath:indexPath];
UIImageView *img=[[UIImageView alloc]initWithFrame:CGRectMake(0,0,100,100)];
NSString *img2=[self.imagesa objectAtIndex:indexPath.row];
img.image=[UIImage imageNamed:img2];
cell.imageview.image=[UIImage imageNamed:img2];
return cell;
}
then images from web services is parsed but not shown into the collection view please give me any solution.
try to replace your
-(void)fetchedData:(NSData *)responsedata
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa=[json objectForKey:#"data"];
NSLog(#"images,%#",self.imagesa);
}
with the code
-(void)fetchedData:(NSData *)responsedata
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa=[json objectForKey:#"data"];
if (self.imagesa.count) {
dispatch_async(dispatch_get_main_queue(), ^{
[imagecollection reloadData];
});
}
NSLog(#"images,%#",self.imagesa);
}
now use SDWebImageDownloader and inside your cellForRowAtIndexpath method, replace your method cellForRowAtIndexPath with
Custumcell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"CellIdentifier" forIndexPath:indexPath];
NSDictionary *dict = [self.imagesa objectAtIndex:indexPath.item];
NSString *img2=[dict valueForKey:#"link"];
[cell.imageview sd_setImageWithURL:[NSURL URLWithString:[img2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:#"temp.png"] options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"downloaded");
});
}];
return cell;
also import #import "UIImageView+WebCache.h" in your file
May be this will help you.
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
-(Custumcell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
Custumcell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:#"CellIdentifier" forIndexPath:indexPath];
cell.imageview.image= nil; // or cell.poster.image = [UIImage imageNamed:#"placeholder.png"];
dispatch_async(kBgQueue, ^{
NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[[self.imagesa objectAtIndex:indexPath.row] objectForKey:#"link"]]];
if (imgData) {
UIImage *image = [UIImage imageWithData:imgData];
if (image) {
dispatch_async(dispatch_get_main_queue(), ^{
Custumcell *updateCell = (id)[collectionView cellForItemAtIndexPath:indexPath];
if (updateCell)
updateCell.imageview.image = image;
});
}
}
});
return cell;
}

UITableView loading and reloading

I have trouble loading a UITableView with multiple sections. In order to fill it I use a function (fetches feed from Twitter). At the moment the view loads, the function returns NULL values for it's fields, but after a few seconds it returns the desired feed.
However, before the desired feed is returned, the fields in my tableView are shown to be NULL and then they refresh and are filled properly (No NULL values).
My question is, How can I make the tableView cells not load until the feed is properly loaded?
I have the same problem with my Facebook feed, however it crashes because it doesn't even return any of the values.
in ViewDidLoad I have put
[self getTwitterFeed:^() {
[self.tableView reloadData];
}];
EDIT here is the code of the method
- (void)getTwitterFeed:(void (^)(void))completion {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
#try
{
if ([[[NSUserDefaults standardUserDefaults] objectForKey:#"TwitterLoggedIn"] isEqualToString:#"YES"]) {
[account requestAccessToAccountsWithType:accountType
options:nil completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
ACAccount *twitterAccount = [arrayOfAccounts objectAtIndex:[[NSUserDefaults standardUserDefaults] integerForKey:#"TwitterAccountNumber" ]];
NSURL *requestURL = [NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/home_timeline.json"];
NSMutableDictionary *parameters =
[[NSMutableDictionary alloc] init];
[parameters setObject:#"35" forKey:#"count"];
[parameters setObject:#"true" forKey:#"include_entities"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL parameters:parameters];
postRequest.account = twitterAccount;
[postRequest performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse
*urlResponse, NSError *error)
{
self.dataSource = [NSJSONSerialization
JSONObjectWithData:responseData
options:NSJSONReadingMutableLeaves
error:&error];
if (self.dataSource.count != 0) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Description %#",_dataSource);
for(int i=0;i<[_dataSource count];i++)
{
NSMutableString *url = [NSMutableString stringWithFormat: #"https://www.twitter.com/%#/status/%#",[[[_dataSource objectAtIndex:i ]objectForKey:#"user"] valueForKey:#"screen_name"],[[_dataSource objectAtIndex:i ]objectForKey:#"id"]];
[tweetURL addObject:url];
NSMutableString *urlApp = [NSMutableString stringWithFormat: #"twitter://user?screen_name=%#?status?id=%#",[[[_dataSource objectAtIndex:i ]objectForKey:#"user"] valueForKey:#"screen_name"],[[_dataSource objectAtIndex:i ]objectForKey:#"id"]];
[tweetAppURL addObject:urlApp];
}
CGRect frame = CGRectMake (120, 120, 80, 80);
activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame: frame];
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhiteLarge;
activityIndicator.color = [UIColor whiteColor];
[activityIndicator startAnimating];
activityIndicator.hidesWhenStopped=YES;
[self.view addSubview:activityIndicator];
completion();
//[self.tableView reloadData];
});
}
}];
}
} else {
}
}];
}
else //IF FEED IS NOT TURNED ON
{
[self.tableView reloadData];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Your TWITTER feed is either turned of or isn't initiated!" message:#"Please enable it in Settings" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
}
}
Try something like this
- (void)viewDidLoad
{
[super viewDidLoad];
// Do something perhaps
// Do any additional setup after loading the view, typically from a nib.
[self getTwitterFeed:^() { // Completion block
dispatch_async(dispatch_get_main_queue(), ^{
[myTableView reloadData];
});
}];
}
- (void)getTwitterFeed:(void (^)(void))completion {
// Get the feed and call:
NSLog(#"We finished receiving the data");
completion();
}
And to show the correct number of rows (need to be edited according to # sections)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return (self.myFeedArray.count == 0 ? 0 : self.myFeedArray.count);
}
Loading cells
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(myFeedArray.count == 0) { // no feeds yet
NSLog(#"The count in the table is 0");
UITableViewCell *cell = [[UITableViewCell alloc] init];
cell.textLabel.text = #"Updating...";
[cell.textLabel setTextAlignment:NSTextAlignmentCenter];
[cell.textLabel setAlpha:0.5];
cell.userInteractionEnabled = NO;
return cell;
}
//else do stuff
}
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
NSData * data=[NSData dataWithContentsOfURL:[NSURL URLWithString:URLForPayload]];
[self performSelectorOnMainThread:#selector(fetchCompleted:) withObject:data waitUntilDone:YES];
});
}
-(void) fetchCompleted:(NSData *)responseData
{
// Complete data available now reload TableView
}

Resources