Load More Table View in ios - ios

i want to load a data when user scroll a table view from web services. my web services contain three page but i get only one page JSON data. My code for this like as
in .h file
#property(strong,nonatomic)IBOutlet UITableView *table;
#property(strong,nonatomic)NSArray *imagesa;
#property(strong,nonatomic)IBOutlet UIActivityIndicatorView *spinner;
and in .m file first define two macro queue with url
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)
#define imgURL [NSURL URLWithString:#"http://www.truemanindiamagazine.com/webservice/news.php"]
and then view like as
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
jdata = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:jdata waitUntilDone:YES];
});
self.table.pagingEnabled=YES;
[self.table reloadData];
-(void)fetchedData:(NSData *)responsedata
{
NSError* error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.imagesa=[json objectForKey:#"data"];
if (self.imagesa.count)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.table reloadData];
});
}
NSLog(#"images,%#",self.imagesa);
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.imagesa.count;
}
-(UITableViewCell *)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];
}
NSDictionary *dict = [self.imagesa objectAtIndex:indexPath.row];
NSString *img2=[dict valueForKey:#"post_image"];
[cell.photoimage sd_setImageWithURL:[NSURL URLWithString:[img2 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]] placeholderImage:[UIImage imageNamed:#"Hisoka.jpg"] options:SDWebImageProgressiveDownload completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"downloaded");
});
}];
NSString *name=[dict valueForKey:#"post_title"];
cell.namelabel.text=name;
NSString *des=[dict valueForKey:#"post_content"];
cell.deslabel.text=des;
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSString *date=[dict valueForKey:#"post_date"];
NSDate * dateNotFormatted = [dateFormatter dateFromString:date];
[dateFormatter setDateFormat:#"d-MMM-YYYY"];
NSString * dateFormatted = [dateFormatter stringFromDate:dateNotFormatted];
NSLog(#"Date %#",dateFormatted);
cell.datelabel.text=dateFormatted;
[self.spinner stopAnimating];
self.spinner.hidesWhenStopped=YES;
if (indexPath.row == [self.imagesa count] - 1)
{
[self.table reloadData];
}
return cell;
}
how i get paging in table view and load more data in to table view like as in android load more list view.

you have to call service again with increase pagenumber. i dont see any pagenumber parameter you are passing to get data. maybe if your service contain 3 pages then your service must have pagenumber parameter so you can get data as per page.
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
CGFloat offsetY = scrollView.contentOffset.y;
CGFloat contentHeight = scrollView.contentSize.height;
if (offsetY > contentHeight - scrollView.frame.size.height)
{
// when your table is at last cell then increase your pagenumber and call service again and send increased pagenumber.
pageNum = pageNum + 1;
[self getData];
}
}
-(void)getData
{
dispatch_async(kBgQueue, ^{
jdata = [NSData dataWithContentsOfURL: imgURL];
[self performSelectorOnMainThread:#selector(fetchedData:) withObject:jdata waitUntilDone:YES];
});
}
Maybe this will help you.

Related

reloadData is stacking ontop of old data

I understand that I need to change the data in the data source before calling reloadData. My problem is that I'm not sure how this is done and why my getData method doesn't overwrite the current cells. Is it necessary to use subviews for this? Or is there a way to reset the cells when refresh is called to just create a new set of data?
#property (nonatomic,strong) NSMutableArray *objectHolderArray;
#end
#implementation MartaViewController
- (void)viewDidLoad
{
[super viewDidLoad];
[self getData];
//to add the UIRefreshControl to UIView
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:#"Please Wait..."];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
}
- (void)getData
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
for (NSDictionary *bpDictionary in dataDictionary) {
Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:#"station"] Status:[bpDictionary objectForKey:#"status"]];
[self.objectHolderArray addObject:currenHotel];
}
}
- (IBAction)refresh:(UIRefreshControl *)sender {
[self getData];
[self.tableView reloadData];
[sender endRefreshing];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
(NSInteger)section
{
return [self.objectHolderArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
MartaViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier
forIndexPath:indexPath];
Object *currentHotel = [self.objectHolderArray
objectAtIndex:indexPath.row];
cell.lblStation.text = currentHotel.station;
cell.lblStatus.text = currentHotel.status;
return cell;
}
-(NSMutableArray *)objectHolderArray{
if(!_objectHolderArray) _objectHolderArray = [[NSMutableArray alloc]init];
return _objectHolderArray;
}
#end
Because you are adding objects to self.objectHolderArray instead of overwriting in getData method. Try this
- (void)getData
{
NSURL *blogURL = [NSURL URLWithString:JSON_URL];
NSData *jsonData = [NSData dataWithContentsOfURL:blogURL];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization
JSONObjectWithData:jsonData options:0 error:&error];
[self.objectHolderArray removeAllObjects];
for (NSDictionary *bpDictionary in dataDictionary) {
Object *currenHotel = [[Object alloc]Station:[bpDictionary objectForKey:#"station"] Status:[bpDictionary objectForKey:#"status"]];
[self.objectHolderArray addObject:currenHotel];
}
}
First initialize the array in viewDidLoad self.objectArray = [NSMutlabelArray alloc] init] and when you are refreshing the table view remove all objects from object array using [self.orderArray removeAllObject] the copy new content in new array.

Double action on button click

First, I'm a new iOS developer.
I has 2 UITableView.
First UITableView use for Search.
Second UITableView use for see information.
I'm create button for go to second UITableView
press control+drag button to second UITableView.
And set identifier is "gotoF10"
If click button. Connector will get #"special_selected_f10" to process at requestEWIServiceFinish method.
- (IBAction)btnf10
{
NSMutableDictionary *content = [NSMutableDictionary dictionary];
[content setValue:[[AppSetting sharedInstance] token] forKey:#"ewitoken"];
];
[[EWIConnector connector] requestEWIService:#"special_selected_f10" requestData:content delegate:self];
}
If has #"special_selected_f10" from below code. It will follow Identifier name for go to second UITableView and response data.
- (void) requestEWIServiceStart:(EWIConnector *)connector{
NSLog(#"start %#",connector.endpoint);
}
- (void) requestEWIServiceFinish:(EWIConnector *)connector responseData:(NSDictionary *)responseData{
NSLog(#"finish %#",connector.serviceName);
NSLog(#"response %#",responseData);
if ([connector.serviceName isEqualToString:#"special_selected_f10"])
{
NSLog(#"finish %#", connector.serviceName);
NSDictionary *content = responseData[#"content"];
NSString *stAlertMes = [content objectForKey:#"alertMessage"];
stAlertMes = [self getString:stAlertMes];
NSLog(#"AlertMSG : %#", stAlertMes);
if (![stAlertMes isEqualToString:#""])
{
NSLog(#"ALERT MESSAGE : %#", stAlertMes);
gloablOnWherehouse.arTableDataSelected = [[NSArray alloc] init];
}
else
{
NSLog(#"HAS DATA");
gloablOnWherehouse.arTableDataSelected = [content objectForKey:#"DataList_SPI_DetailF10Collection"];
[self performSegueWithIdentifier:#"gotoF10" sender:nil];
//labelStatus.text = #"";
}
}
else
{
NSLog(#"response %#",responseData);
}
}
This is a code from second UITableView for response data.
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"DisplayEffectQtyViewCell";
DisplayEffectQtyViewCell *cell = [self.tableViewDetailList dequeueReusableCellWithIdentifier:simpleTableIdentifier forIndexPath:indexPath];
if(cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"DisplayEffectQtyViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
} else {
if (globlOnDisplayEffect.arTableDataSelected) {
NSMutableArray *myMutbleArray = [[NSMutableArray alloc] init];
[myMutbleArray addObject:globlOnDisplayEffect.arTableDataSelected];
if (myMutbleArray)
{
NSDictionary *myDic = [globlOnDisplayEffect.arTableDataSelected objectAtIndex:indexPath.row];
NSDictionary *cont = [myDic objectForKey:#"DataList_SPI_DetailF10"];
NSString *f10_cmpt = [self getString:[cont objectForKey:#"f10_cmpt"]];
NSString *f10_dt = [self getString:[cont objectForKey:#"f10_dt"]];
NSString *f10_item = [self getString:[cont objectForKey:#"f10_item"]];
NSString *f10_lot = [self getString:[cont objectForKey:#"f10_lot"]];
NSString *f10_model = [self getString:[cont objectForKey:#"f10_model"]];
NSString *f10_of = [self getString:[cont objectForKey:#"f10_of"]];
NSString *f10_semi = [self getString:[cont objectForKey:#"f10_semi"]];
NSString *f10_tm = [self getString:[cont objectForKey:#"f10_tm"]];
NSString *f10_uncmp = [self getString:[cont objectForKey:#"f10_uncmp"]];
[cell setf10_cmpt:f10_cmpt setf10_dt:f10_dt setf10_item:f10_item setf10_lot:f10_lot setf10_model:f10_model setf10_of:f10_of setf10_semi:f10_semi setf10_tm:f10_tm setf10_uncmp:f10_uncmp];
}
}
}
return cell;
}
From upper is a concept of my application.
But, When i'm click button.
From debug IBAction isn't take #"special_selected_f10" to check on "requestEWIServiceFinish" method.
It's go to second UITableView and response empty data. Before back to first UITableView and follow from my concept again.
So, My application has 2 second UITableView when i'm click button.
(empty second UITableView and work second UITableView)
I can a little speak English.
Sorry for my bad English language.

Load More JSON Data in Tableview with Pagination in iOS

i want to make a application that Shows JSON data in UITableView in iOS.Here my webservices contain 3 to 4 page.So,i want when table view scrolled load next page data. then i code for it
- (void)viewDidLoad
{
pagenum=1;
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
{
NSError* error;
self.json = [NSJSONSerialization JSONObjectWithData:responsedata options:kNilOptions error:&error];
self.dataArray=[_json objectForKey:#"data"];
if (self.dataArray.count > 0)
{
dispatch_async(dispatch_get_main_queue(), ^{
[self.newsTable reloadData];
});
}
NSLog(#"images,%#",self.dataArray);
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return self.dataArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 1;
}
-(TableCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *Cellidentifier=#"Cell";
TableCell *cell=[tableView dequeueReusableCellWithIdentifier:Cellidentifier];
if (cell ==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"TableCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
{
NSDictionary *dict = [self.dataArray objectAtIndex:indexPath.section];
NSString *img2=[dict valueForKey:#"post_image"];
[cell.newsImage sd_setImageWithURL:[NSURL URLWithString:img2] placeholderImage:[UIImage imageNamed:#"Hisoka.jpg"]];
NSString *title=[dict valueForKey:#"post_title"];
cell.headLabel.text=title;
NSString *content=[dict valueForKey:#"post_content"];
cell.descripLabel.text=content;
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSString *date=[dict valueForKey:#"post_date"];
NSDate * dateNotFormatted = [dateFormatter dateFromString:date];
[dateFormatter setDateFormat:#"d-MMM-YYYY"];
NSString * dateFormatted = [dateFormatter stringFromDate:dateNotFormatted];
cell.dateLabel.text=dateFormatted;
}
return cell;
}
-(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];
});
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSDictionary *dictionary=[self.dataArray objectAtIndex:indexPath.section];
NSString *url=[dictionary valueForKey:#"link"];
[[UIApplication sharedApplication]openURL:[NSURL URLWithString:url]];
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 80;
}
then Problem is that when i scroll table view it shows next page data but First page data was removed i want to keep all page data in to table view so please give me solution
I know this question was asked in past but it was not working for me please so give me solution.
The problem is that you are replacing your old page with the new page you get,so you only need to append the new data to the the old array data.
If you have allocated self.dataArray before using it in fetchedData then just use
NSArray* newArray=[_json objectForKey:#"data"];
if(newArray && [newArray isKindOfClass:[NSArray class]])
[self.dataArray addObjectsFromArray:newArray];
else you need to allocate the array for the first page you get, and append the next pages data to it later.
NSArray* newArray=[_json objectForKey:#"data"];
if(newArray && [newArray isKindOfClass:[NSArray class]]){
if (!self.dataArray)
self.dataArray=[NSMutableArray arrayWithArray:newArray];
else
[self.dataArray addObjectsFromArray:newArray];
}
The problem is that you override self.dataArray in fetchedData: method.
So, you need to add objects to array. I suppose you are using NSMutableArray.
[self.dataArray addObject:[_json objectForKey:#"data"]];
BTW, small code improvements:
1) you can use method getData in viewDidLoad instead of copy/paste the code twice.
2) if you do performSelectorOnMainThread:#selector(fetchedData:) then you dont need to have dispatch_async(dispatch_get_main_queue() because it is already in main thread.

UICollectionview datas loading issue

Hi i have implemented UICollectionView in my app..If my array count value greater than 20 and when i tried to scroll the view it was not showing previous datas,,
In cellForItemAtIndexPath:(NSIndexPath *)indexPath method every time i check
if (indexPath.row == [recipeImages count] - 1)
{
[self loadDatas];
}
method.So that i could download 10 datas everytime...
-(UICollectionViewCell *)collectionView:(UICollectionView*)collectionViewcellForItemAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"CourseList";
NSLog(#"indexpath %# in cell for row",indexPath);
CollectionCellContent *cell = (CollectionCellContent*)[collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
NSDictionary *course;
course=[courselist objectAtIndex:indexPath.row];
cell.coursename.text=[course objectForKey:#"course_name"];
cell.authorname.text=[course objectForKey:#"course_author"];
cell.price.text=[course objectForKey:#"course_price"];
cell.cover.image=[UIImage imageNamed:[course objectForKey:#"course_cover_image"]];
cell.review.image=[UIImage imageNamed:[course objectForKey:#"ratings"]];
NSString *imageUrlString = [[NSString alloc]initWithFormat:#"%#/%#/%#",delegate.course_image_url,[course objectForKey:#"course_id"],[course objectForKey:#"course_cover_image"]];
UIImage *imageFromCache = [self.imageCache objectForKey:imageUrlString];
if (imageFromCache) {
cell.cover.image= imageFromCache;
}
else
{
cell.cover.image = [UIImage imageNamed:#"placeholder"];
[self.imageOperationQueue addOperationWithBlock:^{
NSURL *imageurl = [NSURL URLWithString:imageUrlString];
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageurl]];
if (img != nil) {
[self.imageCache setObject:img forKey:imageUrlString];
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
CollectionCellContent *updateCell = (CollectionCellContent*)[self.ipadcollection cellForItemAtIndexPath:indexPath];
if (updateCell) {
[updateCell.cover setImage:img];
}
}];
}
}];
}
if (indexPath.row == [courselist count] - 1)
[self loadDatas];
return cell;
}
in load datas method:
[categorylist addObject:[arrayList1 objectForKey:#"category_name"]];
[category_tableView reloadData];
whenever i call reload data method i am facing this issue..
-(void)loadDatas
{
NSString *urltemp=[[databaseurl sharedInstance]DBurl];
NSString *url1=#"AllCourse.php";
NSString *URLString=[NSString stringWithFormat:#"%#%#?offset=%d",urltemp,url1,offset];
NSMutableArray *search = [du MultipleCharacters:URLString];
NSDictionary* menu = [search valueForKey:#"serviceresponse"];
NSArray *Listofdatas=[menu objectForKey:#"Course List"];
NSMutableArray *temp1=[[NSMutableArray alloc]init];
if ([Listofdatas count]>0)
{
for (int i=0;i<[Listofdatas count];i++)
{
NSDictionary *arrayList1= [Listofdatas objectAtIndex:i];
NSDictionary* temp=[arrayList1 objectForKey:#"serviceresponse"];
// NSLog(#"Received Values %#",temp);
if (offset==0) {
[courselist addObject:temp];
}
else
[temp1 addObject:temp];
}
if (offset!=0)
{
NSMutableArray *arrayWithIndexPaths = [NSMutableArray array];
for (NSInteger index =courselist.count; index < (courselist.count + temp1.count); index++) {
[arrayWithIndexPaths addObject:[NSIndexPath indexPathForRow:index inSection:0]];
}
if (courselist) {
[courselist addObjectsFromArray:temp1];
[self.ipadcollection performBatchUpdates:^{
[self.ipadcollection insertItemsAtIndexPaths:arrayWithIndexPaths];
}
completion:nil];
// [self.collectionView reloadData];
}
else {
courselist = [[NSMutableArray alloc] initWithArray:temp1];
}
}
if (![HUD isHidden]) {
[HUD hide:YES];
}
}
offset+=10;
[self.ipadcollection reloadData];
}
Make some delay before reloading UICollectionView.
[self performSelector:#selector(reloaddatas) withObject:nil afterDelay:0.5f];

UISegmentControl filter Table View data JSON error

I'm trying to filter the data of my Table View which is calling a JSON-file and parses the data to the Table View. I'm getting some strange errors. Here's my code:
#import "FacebookViewController.h"
#import "RNBlurModalView.h"
#import "FacebookPost.h"
#import "TwitterPost.h"
#define CELL_CONTENT_WIDTH 320.0f
#define CELL_CONTENT_MARGIN 10.0f
#define FONT_SIZE 14.0f
#interface FacebookViewController ()
{
NSInteger refreshIndex;
NSArray *fbPost;
NSArray *pic;
}
#end
#implementation FacebookViewController
#synthesize tweets;
- (void)refreshChannels:(id)sender {
if (tweets.count == 0) return;
// disable UI
self.title = #"Updating...";
self.navigationController.view.userInteractionEnabled = YES;
refreshIndex = 0;
}
- (void) reloadFB {
}
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *button = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemRefresh
target:self
action:#selector(refreshChannels:)];
self.navigationItem.rightBarButtonItem = button;
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu" style:UIBarButtonItemStyleBordered target:self action:#selector(showMenu)];
UIPanGestureRecognizer *gestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:#selector(swipeHandler:)];
[self.view addGestureRecognizer:gestureRecognizer];
self.myTableView.separatorColor = [UIColor clearColor];
[self issueLoadRequest];
}
- (void)swipeHandler:(UIPanGestureRecognizer *)sender
{
[[self sideMenu] showFromPanGesture:sender];
}
#pragma mark -
#pragma mark Button actions
- (void)showMenu
{
[[self sideMenu] show];
}
#pragma mark - Table view data source
- (void)issueLoadRequest
{
if (changeData.selectedSegmentIndex == 1) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site-facebookparse.php?person=Person"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
} else {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://my-site-twitterparse.php?person=Person"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
}
- (void)receiveData:(NSData *)data {
if (changeData.selectedSegmentIndex == 1) {
self.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
} else {
self.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
}
- (void)receiveTwitter:(NSData *)data {
// When we have the data, we serialize it into native cocoa objects. (The outermost element from twitter is
// going to be an array. I JUST KNOW THIS. Reload the tableview once we have the data.
self.tweets1 = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (changeData.selectedSegmentIndex == 1) {
return self.tweets.count;
} else {
return self.tweets1.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"FacebookPost";
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *tweet = [self.tweets objectAtIndex:indexPath.row];
NSDictionary *tweet1 = [self.tweets1 objectAtIndex:indexPath.row];
FacebookPost *cell = (FacebookPost *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"FacebookPost" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (changeData.selectedSegmentIndex == 1) {
cell.fbPost.text = [tweet objectForKey:#"message"];
} else {
cell.fbPost.text = [tweet1 objectForKey:#"tweet"];
}
return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 90;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (changeData.selectedSegmentIndex == 1) {
//Open the link
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"message"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
} else {
//Öppna länken eller liknande
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[tweets objectAtIndex: storyIndex] objectForKey:#"tweet"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
RNBlurModalView *modal = [[RNBlurModalView alloc] initWithViewController:self title:#"Message" message:storyLink];
[modal show];
// Spit out some pretty JSON for the tweet that was tapped. Neato.
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
}
}
#end
The table view data is downloading the Twitter post on the launch, even if I have set it to download the Facebook posts. It's very strange... Please help me fix this!
There's a couple of things you need to do. Firstly, you need to set the selected segment index. Before you call [self issueLoadRequest] in viewDidLoad, you should set the selected index like this:
changeData.selectedSegmentIndex = 0;
This will set the first segment to be the selected segment. Also, you'll need to make sure the correct data is loaded when you change the selected segment. To do that, you should add the following to viewDidLoad:
[changeData addTarget:self action:#selector(segmentedControlSelectedIndexChanged:) forControlEvents:UIControlEventValueChanged];
And the companying method, segmentedControlSelectedIndexChanged:
- (void)segmentedControlSelectedIndexChanged:(id)sender
{
[self issueLoadRequest];
}
Now whenever you changed between the Facebook segment and the Twitter segment, it will call the corresponding API, download the data, and update the table view. Depending on the speed on your connection, there may be a small, but noticeable delay between selecting the segment and the table view updating.

Resources