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.
Related
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.
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.
I have a UITableView that loads content from a server.
All works fine and the content loads correctly, but when I scroll my UITableView lags a bit.
I created a method that downloads the content from a server, and I call this method in my viewDidLoad method, since it is the first thing that opens when I open the app.
I don't know if this is the best approach.
How I can avoid that? Here is my code:
- (void)viewDidLoad
{
[super viewDidLoad];
// Method that Loads the Content
[self retrieveData];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Retorna o número de linhas pelo array de programacao.
return programacaoArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
// ALTURA da TableViewCell
return 150;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *identifier = #"CellIdentifier";
ProgramacaoTableCell *cell = (ProgramacaoTableCell *)[self.tableView dequeueReusableCellWithIdentifier:identifier];
if (cell == nil) {
cell = [[ProgramacaoTableCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
}
// Configure the Cell
Programacao *programacaoObject;
programacaoObject = [programacaoArray objectAtIndex:indexPath.row];
cell.atracaoImagem.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:programacaoObject.programacaoImagem]]];
cell.nomeLabel.text = programacaoObject.programacaoNome;
cell.dataLabel.text = programacaoObject.programacaoData;
cell.localLabel.text = programacaoObject.programacaoLocal;
return cell;
}
- (void) retrieveData
{
NSURL *url = [NSURL URLWithString:getDataURL];
NSData *data = [NSData dataWithContentsOfURL:url];
jsonArray = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
// SETUP programacaoArray
programacaoArray = [[NSMutableArray alloc] init];
// Loop throught do Array
for (int i = 0; i < jsonArray.count; i++) {
// Cria o PROGRAMACAO Objeto
NSString *pID = [[jsonArray objectAtIndex:i] objectForKey:#"id"];
NSString *pNome = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoNome"];
NSString *pImagem = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoImagem"];
NSString *pDescricao = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoDescricao"];
NSString *pData = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoData"];
NSString *pLocal = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoLocal"];
NSString *pPrecos = [[jsonArray objectAtIndex:i] objectForKey:#"programacaoPrecos"];
// Add to the Array
[programacaoArray addObject:[[Programacao alloc] initWithNome:pNome andImagem:pImagem andDescricao:pDescricao andData:pData andLocal:pLocal andPrecos:pPrecos andID:pID]];
}
// RELOAD TABLE VIEW
[self.tableView reloadData];
}
There's a very obvious mistake you're making. You're loading the image synchronously (on the same thread, which in this case is the main thread), which is what's causing the lag. You should look into using AFNetworking's UIImageView category, which will load these images in the background for you.
You can download the AFNetworking library from here.
I think cause problem by code:
'cell.atracaoImagem.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:programacaoObject.programacaoImagem]]];
you can use SDWebImage framework, loading image
I think you should call the retrieveData function in viewWillAppear method instead of viewDidLoad
I'm trying to parse a json-file containing links to images. This is my code:
#import "Pictures.h"
#import "DEMONavigationController.h"
#import "PicturesObject.h"
#interface Pictures ()
{
NSInteger refreshIndex;
NSArray *images;
NSMutableArray *jsonIs;
NSArray *items;
IBOutlet UIImageView *imagesinsta;
}
#end
#implementation Pictures
- (void)viewDidLoad
{
[super viewDidLoad];
self.title = #"Pictures";
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:#"Menu"
style:UIBarButtonItemStylePlain
target:(DEMONavigationController *)self.navigationController
action:#selector(showMenu)];
// ***************** FETCHING DATA ******************* //
NSURL *URL = [NSURL URLWithString:[NSString stringWithFormat:#"link-to-json.php?image=Image"]];
NSData *data= [NSData dataWithContentsOfURL:URL];
if (data == nil) {
return;
}
NSError* error;
items = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"Json : %#",jsonIs);
if (jsonIs != nil) {
NSMutableDictionary* aDict = jsonIs[0];
NSString *item_media = [aDict objectForKey:#"link"];
}
// ***************** FETCHING DATA ******************* //
}
#pragma mark - Table view data source
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableIdentifier = #"PicturesObject";
PicturesObject *cell = (PicturesObject *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"PicturesObject" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
// The element in the array is going to be a dictionary. I JUST KNOW THIS. The key for the tweet is "text".
NSDictionary *item = [items objectAtIndex:indexPath.row];
NSString *item_media = [item objectForKey:#"link"];
return cell;
}
- (void)issueLoadRequest
{
// Dispatch this block asynchronosly. The block gets JSON data from the specified URL and performs the proper selector when done.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData* data = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"link-to-json.php?image=Image"]];
[self performSelectorOnMainThread:#selector(receiveData:) withObject:data waitUntilDone:YES];
});
}
- (void)receiveData:(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.tweets = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
[self.myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return self.tweets.count;
}
#end
This is how my custom PicturesObject table view look like:
But when I launch my app I only get a screen like this:
Json Data is similar to Dictionary and not an array. Instead of using
NSArray items
use
NSDictionary items
and then extract the the relevant data from dictionary.
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.