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.
Related
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;
}
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;
}
I have a search bar in which user can filter user name.The string enter by the user that post to the server and responds with an array of users that got filtered. I am trying to load those users into the table view and when the user changes the search item it goes through the same process -
#import "AddFriend.h"
#implementation AddFriend
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
// Drawing code
}
*/
-(void)viewDidLoad{
_searchBar.delegate = self;
searchResults = [[NSMutableArray alloc]init];
myTableView.dataSource = self;
myTableView.delegate = self;
}
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
[searchResults removeAllObjects];
_searchString = searchBar.text;
[self postSearch];
}
-(void)postSearch{
// Create the request.
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:3000/api/v1/users/search"]];
// Specify that it will be a POST request
request.HTTPMethod = #"POST";
// This is how we set header fields
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// Convert your data and set your request's HTTPBody property
NSDictionary *parameters = [[NSDictionary alloc] initWithObjectsAndKeys:
_searchString, #"username",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
[request setHTTPBody:postdata];
// Create url connection and fire request
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
#pragma mark - NSURL Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
// A response has been received, this is where we initialize the instance var you created
// so that we can append data to it in the didReceiveData method
// Furthermore, this method is called each time there is a redirect so reinitializing it
// also serves to clear it
_responseData = [[NSMutableData alloc] init];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
// Append the new data to the instance variable you declared
[_responseData appendData:data];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection
willCacheResponse:(NSCachedURLResponse*)cachedResponse {
// Return nil to indicate not necessary to store a cached response for this connection
return nil;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// The request is complete and data has been received
// You can parse the stuff in your instance variable now
NSError *error = nil;
NSArray *json = [NSJSONSerialization
JSONObjectWithData:_responseData
options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves
error:&error];
for (int i = 0; i < json.count; i++) {
NSDictionary *resultsDictionary = [json objectAtIndex:i];
NSString *username = [resultsDictionary objectForKey:#"username"];
[searchResults addObject:username];
}
NSLog(#"%#", searchResults);
[myTableView reloadData];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
// Return the number of rows in the section.
return [searchResults count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
if (searchResults.count > 1) {
cell.textLabel.text = [searchResults objectAtIndex:indexPath.row];
}
return cell;
}
#end
check
NSLog(#"%#", searchResults);
what are you getting there?
also, every time you do a refresh of the data after search, you should clear your results array
[searchResults removeAllObjects]
I am developing a app that will load remote data in a UITableView but when I run it, it shows nothing. Please view and help me to debug it. Thanks
Json outPut
{
"emp_info" = (
(
1,
firstname_one,
lastname_one,
"abcd#xyz",
"500 B3 abc Town"
),
(
2,
firstname_two,
lastname_two,
"abcd#xyz",
"500 B3 abc Town"
),
(
18,
firstname_three,
lastname_three,
"abcd#xyz",
"500 B3 abc Town"
)
);
}
And .m file
- (void)viewDidLoad
{
[super viewDidLoad];
statuses=[[NSMutableArray alloc]init];
NSURL *myURL = [NSURL URLWithString:#"http://abcd.com/My_php/result.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"Finished with status code: %i", [(NSHTTPURLResponse *)response statusCode]);
id jsonObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
NSLog(#"jsonObject=%#",jsonObject);
statuses=[jsonObject mutableCopy];
[self.theTableView reloadData];
}];
NSLog(#"myURL=%#",myURL);
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"%d",[statuses count]);
return [statuses count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
}
id obj = [statuses objectAtIndex:indexPath.row];
cell.textLabel.text =[obj valueForKey:#"Title"];
return cell;
}
And when I compile it. it shows nothing in the table infect doesn't even show the table itself.
You should get NSArray contains NSArrays from NSDictionary from JSON:
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
...
// This Array contains arrays
statuses=[jsonObject[#"emp_info"] mutableCopy];
[self.theTableView reloadData];
}];
In cellForRowAtIndexPath, get value from this NSArray:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
...
// this is an NSArray, not an NSDictionary:
NSArray *obj = [statuses objectAtIndex:indexPath.row];
cell.textLabel.text = obj[1]; // just my example
}
Your data is a dictionary containing an array.
If you want just the array, get the array from the value object returned by the json parser:
statuses=[[jsonObject valueForKey:#"emp_info"] mutableCopy];
I've been reading for hours and I can't figure out why my table won't reload itself with the updated data, here is the request I am making in block form:
ASIHTTPRequest *_request= [ASIHTTPRequest requestWithURL:url];
__weak ASIHTTPRequest *request = _request;
request.requestMethod = #"POST";
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request setCompletionBlock:^{
NSString *responseString = [request responseString];
NSData *responseData = [request responseData];
NSLog(#"Response: %#", responseString);
NSError* error;
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"request finished");
[CommMTable reloadData];
}];
[request setFailedBlock:^{
NSError *error = [request error];
NSLog(#"Error: %#", error.localizedDescription);
}];
[request startAsynchronous];
It gets the json object successfully as it is printed in my console but the table doesn't update!
here is my table pragma section
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.json count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier=#"Cell";
UITableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
NSDictionary *tempDictionary= [self.json objectAtIndex:indexPath.row];
if(cell==nil) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
cell.accessoryType=UITableViewCellAccessoryDetailDisclosureButton;
cell.textLabel.text = [tempDictionary objectForKey:#"title"];
return cell;
}
any help is appreciated, this is really frustrating :(
Have you checked whether json array has been updated or not? And you have used json array as property(self.json) in pragma sections not in inside blocks.
json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
On doing this, the json array will be available only in the scope of setCompletionBlock.
Since you have synthesized json array, you need to assign it like
self.json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
If this was also not worked, just check whether the format of json was correct and you are parsing the json properly in cellForRowAtIndexPath.
I found the problem, I was doing everything correctly (json format and stuff were properly set). The problem was that for some reason the table got disconnected from it's delegate and datasource, for the people who had a similar problem try this solution.
In the xib file just ctrl + drag the tableview to the File Owner and connect it to the delegate and datasource.
or you can do it with just code if you don't like the interface builder with the following lines
[myTableView setDataSource:self];
[myTableView setDelegate:self];
or
self.tableView.delegate = self.tableDelegate;
self.tableView.datasource = self.tableDelegate;
both either/or should work.