How to handle two custom cells in one UITableView with UISegmentedControl Actions? - ios

Hi i am new to iOS and SO also. i am facing a problem in my app to display the two custom cells in one tableview with selection of segmented control.when the user click on the segmented=0,it displays the one custom cell and segmented=1 display the second custom cell.
Here is my code upto now i tried,
-(void)callSegmentSelected
{
value1 = (int)segment.selectedSegmentIndex;
if (segment.selectedSegmentIndex == 0)
{
NSString *urlString = [NSString stringWithFormat:#"http:"url"];
NSString *jsonString = [NSString stringWithFormat:catid];
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
array =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[myTableView reloadData];
}
else
{
NSLog(#"Error");
}
}
else if (segment.selectedSegmentIndex == 1)
{
}
Here is my tableview Delegate methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return array.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (value1 == 0)
{
static NSString *cellId = #"Cell";
Cell1 * cell = (Cell1 *)[myTableView dequeueReusableCellWithIdentifier:cellId];
if (cell == nil)
{
NSArray *myNib;
myNib = [[NSBundle mainBundle]loadNibNamed:#"Cell1" owner:self options:nil];
cell = [myNib lastObject];
}
cell.examLbl.text = [[array objectAtIndex:indexPath.row]objectForKey:#"examtitle"];
myTableView.dataSource = self;
myTableView.delegate = self;
[myTableView reloadData];
return cell;
}
else
{
if (value1 == 1)
{
static NSString * cellIdentifier = #"Cell2";
Cell2 *cell = (ContestRewardCell *)[myTableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil)
{
NSArray *myNib;
myNib = [[NSBundle mainBundle]loadNibNamed:#"cell2" owner:self options:nil];
cell =[myNib objectAtIndex:0];
}
cell.titleLbl.text = [[array objectAtIndex:indexPath.row]objectForKey:#"title"];
myTableView.dataSource = self;
myTableView.delegate = self;
[myTableView reloadData];
return cell;
}
}
return nil;
}
In this code there are no errors,i checked with debugging mode data will coming to "cell.examLbl.text",but not displaying the custom cell in tableview.What i did mistake in this Code Please help me any one.
Thanks in advance.
Here is answer for my problem, i am not implemented the this
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
if (value1 == 0)
{
return 102;
}
else if(value1 == 1)
{
return 193;
}
return 0;
}

you need to first register the cell nib in viewDid load
[YourTableView registerNib:[UINib nibWithNibName:#“YourCellNibName” bundle:nil] forCellReuseIdentifier:#“Identifier”];
then use the cell in cellForRowAtIndexPath
example:
-(void)viewDidLoad
{
[super viewDidLoad];
[TableView registerNib:[UINib nibWithNibName:#“MyTableViewCell” bundle:nil]forCellReuseIdentifier:#"cell"];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MyTableViewCell *cell = (MyTableViewCell *)[myTableView dequeueReusableCellWithIdentifier:#"cell”];
cell.labelTitle=#"cell”;
return cell;
}

Related

UITableViewCell stored in other array

I have one array(arrData) and UITableViewCell reload arrData. arrData stored in web service array of objects.
UITableViewCell in a two label and one image, label and image load data by arrData. so all label and image reload in same array but i want to reload different-different array each label and image.
ViewController
#import "ViewController.h"
#import "MemberTableViewCell.h"
#import "member_details.h"
#interface ViewController ()
{
NSArray *arrData;
}
#end
#implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.tabel_view setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.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 %#",json);
NSArray *status = json[#"status"];
arrData = status;
[self.tabel_view reloadData];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSArray<NSIndexPath *> *selectedRows = [tableView indexPathsForSelectedRows];
if (selectedRows && [selectedRows containsObject:indexPath]) {
return 127.0; // Expanded height
}
return 50.0; // Normal height
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [arrData count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
MemberTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.name.text= [[arrData objectAtIndex:indexPath.row] valueForKey:#"business_category_name"];
cell.title.text= [[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"name"];
cell.email.text=[[[[arrData objectAtIndex:indexPath.row] valueForKey:#"business_details"] objectAtIndex:0] valueForKey:#"email"];
cell.image_view.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[[arrData objectAtIndex:indexPath.row]valueForKey:#"business_details"]objectAtIndex:0] valueForKey:#"img_url"]]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[self.tabel_view beginUpdates];
[self.tabel_view endUpdates];
}
#end
try this code
#import "ViewController.h"
#interface ViewController ()
{
IBOutlet UITableView *tbl;
NSMutableData *response;
NSMutableArray *Arrdata;
NSMutableArray *ArrySubData;
}
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
Arrdata=[[NSMutableArray alloc]init];
ArrySubData=[[NSMutableArray alloc]init];
[tbl setAllowsMultipleSelection:YES];
NSURLRequest *req=[[NSURLRequest alloc]initWithURL:[NSURL URLWithString:#"http://edutimeapp.com/toshow/chamber-of-commerc/ws/fetch_member.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 %#",json);
NSArray *status = json[#"status"];
Arrdata = status;
NSLog(#"%#",Arrdata);
[tbl reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
ArrySubData=[[Arrdata objectAtIndex:section] objectForKey:#"business_details"];
return ArrySubData.count;
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [NSString stringWithFormat:#" %#",[[Arrdata objectAtIndex:section] objectForKey:#"business_category_name"]];
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
return 25;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UILabel *myLabel = [[UILabel alloc] init];
myLabel.frame = CGRectMake(0, 0, 320, 20);
myLabel.font = [UIFont fontWithName:#"Roboto-Bold" size:13.0];
myLabel.textColor=[UIColor whiteColor];
myLabel.backgroundColor=[UIColor colorWithRed:70.0/255.0 green:82.0/255.0 blue:88.0/255.0 alpha:1.0];
myLabel.text = [self tableView:tableView titleForHeaderInSection:section];
UIView *headerView = [[UIView alloc] init];
[headerView addSubview:myLabel];
return headerView;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIImageView *ImgBrands = (UIImageView *) [cell viewWithTag:101];
UILabel *lblName = (UILabel *) [cell viewWithTag:102];
UILabel *lblEmail = (UILabel *) [cell viewWithTag:103];
UILabel *lblPhone = (UILabel *) [cell viewWithTag:104];
ArrySubData=[[Arrdata objectAtIndex:indexPath.section] objectForKey:#"business_details"];
NSString *strName=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"name"]];
NSString *stremail=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"email"]];
NSString *strphone=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"phone"]];
NSString *strimage=[NSString stringWithFormat:#"%#",[[ArrySubData objectAtIndex:indexPath.row] objectForKey:#"image"]];
lblName.text=strName;
lblEmail.text=stremail;
lblPhone.text=strphone;
ImgBrands.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:strimage]]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self updateTableView];
}
- (void)updateTableView
{
[tbl beginUpdates];
[tbl endUpdates];
}

How to count two arrays in a single label in UITableViewCell? Objective-C

I want to create a message conversation screen.I have two arrays, first is web_array and the second is local_array. First, I have one UITableViewCell in one UILabel, and one UITextField, and one UIButton. In the textfield, write any text and it will print on UITableViewCell label. TextField text is stored in a one array (local_array). (application run time local_array is empty).
And second array (web_array), web_array is stored in a web service get data, I want to web_array count on UITableViewCell label after local_array count in same label.
web_array data counting is over after just down local_array data counting start.
My english is very bad and i can't explain proper. seriously i'm so tired please help me and guide.
ViewController
#import "Chat_ViewController.h"
#import "chatview_Cell.h"
#interface Chat_ViewController () <UITableViewDataSource,UITableViewDelegate>
{
NSArray*web_array;
NSMutableArray*Local_array;
}
#end
#implementation Chat_ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Local_array=[[NSMutableArray alloc]init];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"MYURL"]];
//create the Method "GET" or "POST"
[request setHTTPMethod:#"POST"];
//Pass The String to server(YOU SHOULD GIVE YOUR PARAMETERS INSTEAD OF MY PARAMETERS)
NSString *userUpdate =[NSString stringWithFormat:#"senderid=%#&recid=%#&",_chat_myuid.text,_chat_uid.text, nil];
//Check The Value what we passed
NSLog(#"the data Details is =%#", userUpdate);
//Convert the String to Data
NSData *data1 = [userUpdate dataUsingEncoding:NSUTF8StringEncoding];
//Apply the data to the body
[request setHTTPBody:data1];
//Create the response and Error
NSError *err;
NSURLResponse *response;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&err];
NSString *resSrt = [[NSString alloc]initWithData:responseData encoding:NSASCIIStringEncoding];
//This is for Response
NSLog(#"got response==%#", resSrt);
NSArray *results = [json objectForKey:#"status"];
web_array = [results valueForKey:#"message"];
NSLog(#"your message %#",web_array);
//This is for Response
NSLog(#"got response==%#", resSrt);
if(resSrt)
{
NSLog(#"got response");
}
else
{
NSLog(#"faield to connect");
}
}
- (IBAction)send:(id)sender
{
NSString *textNameToAdd = self.mymsg.text; //mymsg is UITextField outlet
[Local_array addObject:textNameToAdd];
[self.table_view reloadData];
}
//TABLEVIEWCELL Code
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([Local_array count] > 0 && web_array.count>0)
{
return [Local_array count];
}
else
return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
chatview_Cell *cell = [tableView dequeueReusableCellWithIdentifier:#"ht"];
if (cell==nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"Cell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (Local_array.count > 0 && web_array.count>0)
{
cell.other_msg.text=[NSString stringWithFormat:#"%#",[Local_array objectAtIndex:indexPath.row]];
}
cell.other_msg.text=[NSString stringWithFormat:#"%#",[web_array objectAtIndex:indexPath.row]];
return cell;
}

How to maintain two custom cells in one tableview with segment selection?

I am new to iOS. I have one UIViewController in that added one tableview and segmented control. If I press the segmented value = 0, I want to the first custom cell with loading images and title and segment value = 1, I want to display my second custom cell with UICollectionView with loading of images and title, how can I do that please help me? Here is some of my code:
MenuViewController.m
-(void)callSegmentSelected
{
value=(int)segment.selectedSegmentIndex;
if (segment.selectedSegmentIndex == 0)
{
NSString *urlString = [NSString stringWithFormat:#"http://API"];
NSString *jsonString = #"";
NSData *myJSONData =[jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSMutableData *body = [NSMutableData data];
[body appendData:[NSData dataWithData:myJSONData]];
[request setHTTPBody:body];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
if(str.length > 0)
{
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSLog(#"%#", [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error]);
listBannerArray =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
[progressHud hide:YES];
[self.tableViewContest reloadData];
}
else
{
NSLog(#"Error");
}
}
Here is my CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = #"Cell";
MenuTableViewCell *cell = (MenuTableViewCell *)[tableViewContest dequeueReusableCellWithIdentifier:cellId];
if (cell == nil)
{
NSArray * myNib;
myNib =[[NSBundle mainBundle]loadNibNamed:#"MenuTableViewCell" owner:self options:nil];
cell = (MenuTableViewCell *)[myNib lastObject];
}
if(value == 0)
{
#try
{
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"] length] > 0)
{
NSURL *imageURL = [NSURL URLWithString:[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"listbanner"]];
[cell.listBanner sd_setImageWithURL:imageURL
placeholderImage:[UIImage imageNamed:#"profilepic_bg"]];
}
else
{
}
}
}
#catch (NSException *exception)
{
}
if((NSNull *)[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] != [NSNull null])
{
if([[[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"] length] > 0)
{
cell.examTitle.text = [[listBannerArray objectAtIndex:indexPath.row] objectForKey:#"examtitle"];
}
else
{
cell.examTitle.text = #"Data Error";
}
}
else
{
cell.examTitle.text = #"Data Error";
}
}
When Click on SegmentIndex=0 Screen like this
When Click on SegmentIndex=1 like this
You can create the enum for differentiate the segment action.
Step 1 : Create the enum for the selection.
typedef enum {
OPTION_FIRST = 0,
OPTION_SECOND
} SEGMENT_SELECTION;
Step 2 : On your MenuViewController.m
1) Create the instance of SEGMENT_SELECTION
#property(nonatomic) SEGMENT_SELECTION segmentSelection;
2) Assign the value to segmentSelection
-(void)callSegmentSelected
{
if (segment.selectedSegmentIndex == 0)
segmentSelection = OPTION_FIRST
else
segmentSelection = OPTION_SECOND
[self.tableViewContest reloadData];//For update the content in tableview
}
Step 3 : Write the below code on CellForRowAtIndexPath
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
if(segmentSelection == OPTION_FIRST) {
//Load the content of FIRST segment action
}
else {
//Load the content of SECOND segment action
}
}
Hope it works for you.

Issue reloading cellForRowAtIndexPath - Objective C

I am having an issue reloading my tableView when calling from an outside class to start a method and reload the tableView
More specifically:
Here is the call from the outside class:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
NSInteger tag = cell.tag;
impact* myScript = [[impact alloc] init];
[myScript startProcess:tag];
}
**From here** it moves to the `impact` class and loads the `startProcess` method:
- (void)startProcess:(NSInteger)number {
NSInteger testing = number;
cellID = testing;
// MAKE REQuEST TO SERVER
[self makeRequests];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}
This is the makeRequests method it calls:
-(void)makeRequests
{
/* GRAB USERNAME TO BE SENT OVER FOR NOTIFICATIONS */
NSArray *get = [[SSKeychain allAccounts] init];
//NSLog(#"get%#", get);
NSString *username = [get[0] objectForKey:#"acct"];
//if(cellID != 0)
//{
NSDictionary *dictionary = #{#"function": #"populateNotfications", #"username" : username};
NSError *error = nil;
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary options:0 error:&error];
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (error)
NSLog(#"%s: JSON encode error: %#", __FUNCTION__, error);
NSURL *url = [NSURL URLWithString:#"test.com/dev/iphone/test.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
NSString *params = [NSString stringWithFormat:#"json=%#",
[string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *paramsData = [params dataUsingEncoding:NSUTF8StringEncoding];
[request addValue:#"8bit" forHTTPHeaderField:#"Content-Transfer-Encoding"];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request addValue:[NSString stringWithFormat:#"%lu", (unsigned long)[paramsData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:paramsData];
// issue the request
NSURLResponse *response = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error)
NSLog(#"%s: NSURLConnection error: %#", __FUNCTION__, error);
// GRAB STATUS OBJECT
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:returnData //1
options:kNilOptions
error:&error];
self.impactsGrabed = [json objectForKey:#"requested_data"];
//}
}
Now from here it will run my tableView methods as shown below:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.impactsGrabed count];
}
- (double) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 75;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"timelineCell";
impactTimelineCell *cell = (impactTimelineCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell = [[impactTimelineCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[cell initTimelineCell];
cell.statusLabel.text = [self.impactsGrabed[indexPath.row] objectForKey:#"message"];
cell.timestampLabel.text = [self.impactsGrabed[indexPath.row] objectForKey:#"time_post"];
return cell;
}
I have logged every method and every method works until I hit cellForRowAtIndexPath where nothing happens than. Nothing is returning void. Now heres the thing:
When calling the function startProcess from another class that starts the whole process of loading the tableView cells it does not work. If I call the startProcess method inside the viewDidLoad in that file on initiation the tableView cells load properly.
So for example:
If I place [self startProcess:1]; within the viewDidLoad it works perfect! If I call [myScript startProcess:tag]; from the other class, it wont work properly.
What do you guys think the issue is?
Since all your controller are already instantiated and on screen, you don't need to instantiate one (and indeed you shouldn't since that creates a new instance that's not on screen).
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [collectionView cellForItemAtIndexPath:indexPath];
NSInteger tag = cell.tag;
impact* myScript = self.parentViewController.childViewControllers[1]; // if my script is one of the child view controllers, then this is how you need to access it -- the number might be 0,1 or 2 depending on which one is the impact controller
[myScript startProcess:tag];
}
You can also do this in prepareForSegue -- when your controller is instantiated, all the embedded child controllers will also be, and you can get a reference to them from the destinationViewController property of the segue.
Because this controller is already on screen, it's ok to call reloadData where you do in startProcess.

Parse links of a JSON file und download them

I want to create an App which parses the picture Links of a Facebook page and shows them in an iOS app (display them in tableView). But after I parsed the JSON file and added them to an array which should be downloaded nothing is displayed.
Here's the code:
- (void)viewDidLoad
{
self.edgesForExtendedLayout = UIRectEdgeNone;
[super viewDidLoad];
items = [[NSMutableArray alloc] init];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/HuppFotografie/photos/uploaded/?fields=id,name,picture"];
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
{
NSLog(#"fail with error");
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 250.0;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
static NSString *CellIdentifier = #"MyImageCell";
ImageCell *cell = (ImageCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.backgroundColor = [UIColor clearColor];
if (cell == nil) {
NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"ImageCell" owner:self options:nil];
for (id currentObject in topLevelObjects) {
if ([currentObject isKindOfClass:[UITableViewCell class]]) {
cell = (ImageCell *)currentObject;
break;
}
}
}
// Here we use the new provided setImageWithURL: method to load the web image
[cell.imageView setImageWithURL:[NSURL URLWithString:[items objectAtIndex:indexPath.row]] placeholderImage:[UIImage imageNamed:#"Placeholder.jpg"]];
cell.imageSource.text = [items objectAtIndex:indexPath.row];
return cell;
}
I really don't get why. I'm sorry if this question is stupid but I am coding just as a hobby and have not that great experience.
In fact your connection is asynchronous, so you just need to reload your table view programmatically to display loaded images:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSDictionary *allDataDictionary = [NSJSONSerialization JSONObjectWithData:webData options:0 error:nil];
NSArray *arrayOfData = [allDataDictionary objectForKey:#"data"];
for (NSDictionary *dicton in arrayOfData) {
NSString *picture = [dicton objectForKey:#"picture"];
[items addObject:picture];
}
// Just add this line, in order to force reload when all your data is arrived
[self.tableView reloadData];
}

Resources