I have a table view on InquiryViewController that I want to be reloaded when I click the update status button. The update status button is a JSON that gets the status of a message.
Here's the code:
-(BOOL)getMessageStatus : (NSMutableArray *)emails : (UIAlertView *)alert : (UIProgressView *)progress : (InquiryLogViewController *)controller
{
_emailsInApi = [[NSArray alloc]init];
_emailsInApi = [[DBManager getSharedInstance]arrayOfEmails];
NSMutableArray *newArrayEmail = [[NSMutableArray alloc]init];
NSString *arrayEmail =#"";
for(int i = 0; i<[_emailsInApi count]; i++){
arrayEmail = [_emailsInApi objectAtIndex:i];
[newArrayEmail addObject:arrayEmail];
}
NSURL *url = [NSURL URLWithString:#"http://www.url.com/API/2.0/message.php"];
NSDictionary *params =#{#"api_key":#"APIKEYIOS",#"action":#"get-message-status",#"email":newArrayEmail};
NSLog(#"params: %#",params);
NSData *paramsData = [NSJSONSerialization dataWithJSONObject:params
options:NSJSONWritingPrettyPrinted
error:nil];
NSString *paramsString = [[NSString alloc]initWithData:paramsData encoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
paramsString = [paramsString stringByReplacingOccurrencesOfString:#"%5C" withString:#""];
NSString *post = [NSString stringWithFormat:#"params=%#", paramsString];
NSData *sendData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:sendData];
NSURLSessionDataTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
if (!error)
{
NSString *responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response...... = %#", responseString );
//get data frm response
self.responseData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
self.responseArray = [self.responseData objectForKey:#"data"];
for(NSDictionary *items in self.responseArray)
{
Inquiry *inq = [[Inquiry alloc]init];
inq.email = [items objectForKey:#"to_email"];
inq.status = [items objectForKey:#"status_id"];
[emails addObject:inq];
}
float newProg = (float)1 - (float)[emails count] / (float)5;
dispatch_async(dispatch_get_main_queue(), ^{
[progress setProgress:newProg animated:YES];
});
dispatch_async(dispatch_get_main_queue(), ^{
[[DBManager getSharedInstance]updateInquirylog:emails];
});
dispatch_async(dispatch_get_main_queue(), ^{
controller.arrayOfEmails = [[DBManager getSharedInstance]loadInquiries];
[controller.tableViews reloadData];
});
dispatch_async(dispatch_get_main_queue(), ^{
[alert dismissWithClickedButtonIndex:0 animated:YES];
});
}
else
{
self.alert = [[UIAlertView alloc] initWithTitle:nil message:error.localizedDescription delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
self.responseData = nil;
[alert show];
}
}];
[task resume];
return YES;
}
My problem here is in: [controller.tableViews reloadData];
It doesn't reload my table. Why? Help me please. Thank you
EDIT: This json is in a class
Ok I'm sorry. I forgot to include my table view method.
Here it is:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellID =#"Cell";
tableCellOfInquiryLog *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
if (tableView == self.searchDisplayController.searchResultsTableView){
if(cell == nil)
{
NSArray *topLevelObjects = [[NSBundle mainBundle]loadNibNamed:#"searchCell" owner:self options:nil];
cell = [topLevelObjects objectAtIndex:0];
}
Inquiry *inquiry = [searchResult objectAtIndex:indexPath.row];
cell.sInquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.sName.text = inquiry.name;
cell.sItem.text = inquiry.item_name;
cell.sDate.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
else
{
if(cell == nil)
{
cell = [[tableCellOfInquiryLog alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
}
Inquiry *inquiry = [arrayOfInquiries objectAtIndex:indexPath.row];
cell.inquiry_id.text =[NSString stringWithFormat:#"%d",inquiry.ID];
cell.name.text = inquiry.name;
cell.item.text = inquiry.item_name;
cell.date.text = inquiry.dDate;
cell.status.layer.cornerRadius = 10;
if ([inquiry.status isEqual: #"1"]) {
cell.status.backgroundColor = [UIColor greenColor];
}
else if ([inquiry.status isEqual: #"2"]) {
cell.status.backgroundColor = [UIColor orangeColor];
}
else if ([inquiry.status isEqual: #"3"]) {
cell.status.backgroundColor = [UIColor redColor];
}
return cell;
}
return nil;
}
create a instance of your tableview and the add the given code in which ever method u want to add to [self.nameoftableview reloaddata]
if (indexPath.section ==1) {
cell = [tableView dequeueReusableCellWithIdentifier:section1identifier];
cell = nil;//here i have made it nil
if (!cell)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:section1identifier];
data *newObj = [callingObj.itemslist objectAtIndex:indexPath.row];
UITextView *titlelabel = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x+5, cell.frame.origin.y-2, 320, 38)];
titlelabel.textColor = [UIColor redColor];
titlelabel.font= [UIFont fontWithName:#"Times New Roman" size:FONT_SIZE];
titlelabel.text = newObj.title;
titlelabel.scrollEnabled = NO;
titlelabel.editable = NO;
[cell.contentView addSubview:titlelabel];
desView = [[UITextView alloc]initWithFrame:CGRectMake(cell.frame.origin.x,cell.frame.origin.y+25 , 320, i + 160)];
desView.text = newObj.description;
desView.editable = NO;
desView.hidden = NO;
[cell.contentView addSubview:desView];
if (check == NO) {
desView.hidden = YES;
}
}
}
return cell;
Related
I'm using the below code in my ViewController.m to log a user in to my app. However on the following ViewController (AccountViewController), I have a tableView. Upon successful login, I want to reload/populate the data in the tableView, but instead after a successful login, I get an empty table. I've put reloadData in viewWillAppear at the top of MyAccountViewController. See below. Not sure why it's doing this, as when I navigate from AccountViewController to another screen and back, the table is populated. Is my AFNetworking bit causing the table not to populate for some reason?
ViewController.m
[DIOSUser userLoginWithUsername:_userField.text
andPassword:_passField.text
success:^(AFHTTPRequestOperation *op, id response) {
// Saving to keychain/NSUserDefaults
NSDictionary *diosSession = [[DIOSSession sharedSession] user];
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:diosSession] forKey:#"diosSession"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[DIOSSession sharedSession] getCSRFTokenWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString *csrfToken = [NSString stringWithUTF8String:[responseObject bytes]];
[[NSUserDefaults standardUserDefaults] setObject:csrfToken forKey:#"diosToken"];
[[NSUserDefaults standardUserDefaults] synchronize];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
// failure handler
}];
wrongLogin.hidden = YES;
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
MyAccountViewController *yourViewController = (MyAccountViewController *)[storyboard instantiateViewControllerWithIdentifier:#"MyAccount"];
[self.navigationController pushViewController:yourViewController animated:YES];
[self.activityIndicatorViewOne stopAnimating];
self.activityIndicatorViewOne.hidden = YES;
NSLog(#"Success!");}
failure:^(AFHTTPRequestOperation *op, NSError *err) { NSLog(#"Fail!"); wrongLogin.hidden = NO; }
];
AccountViewController.m
- (void)viewWillAppear:(BOOL)animated {
[self.tableView reloadData];
}
- (void)viewDidLoad {
[super viewDidLoad];
[self.tableView reloadData];
if ([self respondsToSelector:#selector(edgesForExtendedLayout)])
self.edgesForExtendedLayout = UIRectEdgeNone;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(ReloadDataFunction:)
name:#"refresh"
object:nil];
[self.tableView reloadData];
self.descripData = [[NSMutableArray alloc] init];
UIBarButtonItem *flipButton = [[UIBarButtonItem alloc] initWithImage: [UIImage imageNamed:#"logouticon4.png"]
// initWithTitle:#"Logout"
style:UIBarButtonItemStylePlain
target:self
action:#selector(flipView)];
self.navigationItem.rightBarButtonItem = flipButton;
[flipButton release];
self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
[self.navigationItem setHidesBackButton:YES animated:YES];
refreshControl = [[UIRefreshControl alloc]init];
[self.tableView addSubview:refreshControl];
[refreshControl addTarget:self action:#selector(refreshTable) forControlEvents:UIControlEventValueChanged];
// Do any additional setup after loading the view.
self.storageData = [[NSMutableDictionary alloc] init];
userName.text = [[[DIOSSession sharedSession] user] objectForKey:#"name"];
//emailAddress.text = [[[DIOSSession sharedSession] user] objectForKey:#"mail"];
NSLog(#"%#", [[DIOSSession sharedSession] user]);
// DIOSView *view = [[DIOSView alloc] init];
NSMutableDictionary *viewParams = [NSMutableDictionary new];
[viewParams setValue:#"storeditems" forKey:#"view_name"];
[DIOSView viewGet:viewParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
self.descripData = [responseObject mutableCopy];
NSLog(#"%#",self.descripData);
// [self.tableView reloadData];
// [HUD hide:YES];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failure: %#", [error localizedDescription]);
}];
[DIOSNode nodeIndexWithPage:#"0" fields:#"title" parameters:[NSArray arrayWithObjects:#"storage_item", nil] pageSize:#"20" success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Nodes retrieved!");
__block int iCount = 0;
for (id object in responseObject) {
// NSLog(#"adding object!");
[self.storageData setObject:(NSDictionary *)object forKey:[NSString stringWithFormat:#"%d",iCount]];
iCount++;
[self.tableView reloadData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//failure
}];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([self.storageData count] > 0 && self.descripData.count > 0)
{
return [self.descripData count];
}
else
return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *DoctorsTableIdentifier = #"StorageItemTableViewCell";
StorageItemTableViewCell *cell = (StorageItemTableViewCell *)[tableView dequeueReusableCellWithIdentifier:DoctorsTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"StorageItemTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
if (self.storageData.count > 0 && self.descripData.count > 0) {
noitemsView.hidden = YES;
cell.cellCountLabel.text = [NSString stringWithFormat:#"%i", indexPath.row+1];
NSDictionary *title = [self.descripData objectAtIndex:indexPath.row];
[[cell itemName] setText:[title objectForKey:#"node_title"]];
NSDictionary *node = [self.descripData objectAtIndex:indexPath.row];
[[cell itemDescrip] setText:[node objectForKey:#"body"]];
NSDictionary *value = [self.descripData objectAtIndex:indexPath.row];
[[cell valueLabel] setText:[value objectForKey:#"storeditemvalue"]];
NSLog(#"%#", self.descripData);
NSDictionary *quantity = [self.descripData objectAtIndex:indexPath.row];
[[cell quantityLabel] setText:[quantity objectForKey:#"numberofitemstored"]];
NSLog(#"%#", self.descripData);
NSString *secondLink = [[self.descripData objectAtIndex:indexPath.row] objectForKey:#"photo"];
[cell.itemPhoto sd_setImageWithURL:[NSURL URLWithString:secondLink]];
NSLog(#"%#",secondLink);
}
else {
noitemsView.hidden = NO;
}
return cell;
}
You have a "refresh" observer, but it calls a function you haven't shown here. You set your data it looks like with this:
for (id object in responseObject) {
// NSLog(#"adding object!");
[self.storageData setObject:(NSDictionary *)object forKey:[NSString stringWithFormat:#"%d",iCount]];
iCount++;
[self.tableView reloadData];
}
but because that is in viewDidLoad, it is only called once, BEFORE viewWillAppear. You need to fill self.storageData and self.descripData in a separate function, then call THAT function from viewWillAppear, or using your NSNotificationCenter notification from the previous VC.
I am using UITableView and after calling web service I am creating cells and binding data. Web service fetching data speed is very good and fast but i checked it's taking time to bind cells to UITableView.My code is -
.m file
#pragma mark tableViewDelegate Methods
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//return ([team1Arr count]+1);
if (isFiltered) {
return [filteredMySquareArr count];
}
else
return [mySquareArr count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
dispatch_async(dispatch_get_main_queue(), ^{
UILabel *squareNameLbl = [[UILabel alloc] initWithFrame:CGRectMake(25.0, 7.0, 300, 25)];
[squareNameLbl setFont:[UIFont systemFontOfSize:15]];
UILabel *descLbl = [[UILabel alloc]initWithFrame:CGRectMake(25.0, 32.0, 285.0, 13.0)];
[descLbl setFont:[UIFont systemFontOfSize:12]];
descLbl.textColor = [UIColor colorWithRed:72.0f/255 green:180.0f/255 blue:71.0f/255 alpha:1.0f];
UIImageView *lockImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 15, 10, 10)];
NSString *accessTypeStr;
if (isFiltered) {
//cell.textLabel.text = [filteredMySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [filteredMySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles", [[filteredMySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[filteredAccessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
else
{
//cell.textLabel.text = [mySquareArr objectAtIndex:indexPath.row];
squareNameLbl.text = [mySquareArr objectAtIndex:indexPath.row];
descLbl.text =[NSString stringWithFormat:#"Located within %.2f miles",[[mySquareDescArr objectAtIndex:indexPath.row] doubleValue]];
accessTypeStr = [NSString stringWithFormat:#"%#",[accessTypeArr objectAtIndex:indexPath.row]];
if ([accessTypeStr isEqualToString:#"private"]) {
lockImage.image = [UIImage imageNamed:#"lock.png"];
}
}
cell.backgroundColor = [UIColor clearColor];
[cell addSubview:squareNameLbl];
[cell addSubview:descLbl];
[cell addSubview:lockImage];
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 10, 20)];
[image setImage:[UIImage imageNamed:#"arrow_list.png"]];
cell.accessoryView = [[UIImageView alloc]initWithFrame:CGRectMake(260.0, 7.0, 10, 20)];
[cell.accessoryView addSubview:image];
});
// });
//cell.accessoryView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:#"arrow_list.png"]];
return cell;
}
WebService
#pragma mark - Webservice Methods
-(void)fetchUpcomingSquares
{
NSString *post = [NSString stringWithFormat:#"access_token=%#&page=0",globalAccessToken];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upcoming_squares",GLOBALURLDOMAIN]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSURLResponse *response;
NSError *error =nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"responsedata =%#",responseData);
if(error)
{
if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
NSLog(#"HTTP Error: %d %#", httpResponse.statusCode, error);
return;
}
NSLog(#"Error %#", error);
[hud hide:YES];
return;
}
if (responseData == NULL) {
AppDelegate *appdel = [[UIApplication sharedApplication]delegate];
[hud hide:YES];
[appdel alertError];
}
else
{
NSDictionary *parsingResultLogin = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"parsingResultLogin = %#",parsingResultLogin);
if ([#"-1" isEqualToString:[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_code"]]) {
NSLog(#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]);
[self showAlertWithMessage:[NSString stringWithFormat:#"%#",[[parsingResultLogin objectForKey:#"result"]objectForKey:#"error_message"]]];
[hud hide:YES];
}
else
{
NSLog(#"Valid ID");
NSDictionary *result= [parsingResultLogin objectForKey:#"result"];
//NSLog(#"result = %#", result);
squareList = [result objectForKey:#"squares"];
NSLog(#"squareList = %#", squareList);
for (NSDictionary *sq in squareList) {
[mySquareArr addObject:[sq objectForKey:#"square_name"]];
[mySquareDescArr addObject:[sq objectForKey:#"max_distance"]];
[accessTypeArr addObject:[sq objectForKey:#"access_type"]];
}
[self.mySquareTblView reloadData];
[hud hide:YES];
}
}
});
NSLog(#"access Type =%#",accessTypeArr);
}
I think it's pretty clear. You're not using your cell identifier on this line of code:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:nil];
You should do it like this:
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
I used bellow code and it's working fine
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:YES];
I have this piece of code and it should bring a ActivityIndicator (thats fine), then go out a query databases twice (looking at the logs it brings in all the correct info). I just STILL does not show up on the tableview and it is driving me crazy!! Can you if possible have a look over the code and see whats wrong - I have been on this for days now - please help!
[super viewDidLoad];
// create the activity indicator in the main queue
self.MainTableView.hidden = YES;
UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:ac];
[ac startAnimating];
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
self.table = [self.client tableWithName:#"notifications"];
self.rowitems = [[NSMutableArray alloc] init];
MSQuery *query = [self.table query];
query.fetchLimit = 3;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
{
self.rowitems = [items mutableCopy];
// we have the notifications and the barID in ROWITEMS array
// so lets make this into a dictionary so we can query it
// we need to run this next block of code 3 times, for the 3 bar ids we have got in ROWITEMS
//[self.TableView reloadData];
int a;
for (a = 0; a < 3; a++)
{
NSDictionary *apt = [self.rowitems objectAtIndex:a];
NSLog(#"%#", apt[#"barID"]);
NSDictionary *barIDDictionary = #{ #"myParam": apt[#"barID"]};
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos" body:barIDDictionary HTTPMethod:#"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
}
else {
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
[self.logoURL addObject:finalstring];
NSLog(#"%#",finalstring);
}
}];
}
}];
[self.MainTableView reloadData];
self.MainTableView.hidden = YES;
}
THIS IS ALL MY CODE THANKS
#import "ViewController.h"
#interface ViewController ()
#property (nonatomic, strong) MSTable *table;
#property (nonatomic, strong) NSMutableArray *items;
#property (nonatomic, strong) NSMutableArray *logoURL;
#property (weak, nonatomic) IBOutlet UITableView *MainTableView;
#end
#implementation ViewController {
dispatch_queue_t MyQueue;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// create the activity indicator in the main queue
self.MainTableView.hidden = YES;
UIActivityIndicatorView *ac = [[UIActivityIndicatorView alloc]
initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
[self.view addSubview:ac];
[ac startAnimating];
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
self.table = [self.client tableWithName:#"notifications"];
self.rowitems = [[NSMutableArray alloc] init];
MSQuery *query = [self.table query];
query.fetchLimit = 3;
[query readWithCompletion:^(NSArray *items, NSInteger totalCount, NSError *error)
{
self.rowitems = [items mutableCopy];
// we have the notifications and the barID in ROWITEMS array
// so lets make this into a dictionary so we can query it
// we need to run this next block of code 3 times, for the 3 bar ids we have got in ROWITEMS
[self.MainTableView reloadData];
int a;
for (a = 0; a < 3; a++)
{
NSDictionary *apt = [self.rowitems objectAtIndex:a];
NSLog(#"%#", apt[#"barID"]);
NSDictionary *barIDDictionary = #{ #"myParam": apt[#"barID"]};
self.client = [MSClient clientWithApplicationURLString:#"https://outnight-mobile.azure-mobile.net/" applicationKey:#"okYeRGfBagYrsbkaqWIRObeDtktjkF10"];
[self.client invokeAPI:#"photos" body:barIDDictionary HTTPMethod:#"POST" parameters:nil headers:nil completion:^(id result, NSHTTPURLResponse *response, NSError *error) {
if (error) {
NSLog(#"Error %#", error );
}
else {
NSString *string = [NSString stringWithFormat:#"%#", [result objectForKey:#"rows"]];
NSString *stringWithoutbracketsend = [string stringByReplacingOccurrencesOfString:#")" withString:#""];
NSString *stringWithoutbracketsfront = [stringWithoutbracketsend stringByReplacingOccurrencesOfString:#"(" withString:#""];
NSString *completion = [stringWithoutbracketsfront stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *newStr = [completion substringFromIndex:1];
NSString *finalstring = [newStr substringToIndex:newStr.length-(newStr.length>0)];
[self.logoURL addObject:finalstring];
NSLog(#"%#",finalstring);
[ac stopAnimating];
[self.MainTableView reloadData];
self.MainTableView.hidden = NO;
}
}];
}
}];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"cell"];
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = stress[#"content"];
// putting an image on a row
switch (indexPath.row) {
case 0:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(0)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
case 1:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(1)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
case 2:
[cell.imageView setImageWithURL:[NSURL URLWithString:[self.logoURL objectAtIndex:(2)]] placeholderImage:[UIImage imageNamed:#"greybox40.png"]];
break;
}
return cell;
}
#end
Looks like you need to call
[self.MainTableView reloadData];
self.MainTableView.hidden = NO;
inside Completion block
I think your Query is running asynchronously. All you need to do is to put your [tableView reloadData] in the block that runs after completion of the Query Block and make sure that you put the reloadData call inside a dispatch_async block.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Background work
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI
[tableView reloadData];
}); });
Did you implement UITableViewDatasource and UITableViewDelegate protocols?
Implement required methods of this 2 protocols and link your MainTableView.
Programmatically:
MainTableView.datasource = self;
MainTableView.delegate = self;
Via storyboard:
UPD:
Try this code:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
NSDictionary *stress = [self.rowitems objectAtIndex:indexPath.row];
cell.textLabel.text = [stress objectForKey:#"content"];
I'm parsing some data from a JSON-file located on my server to my Table View.
When I launch the app the app successfully downloads the data to my table view, but when I begin to scroll, the app crashes.
Here's my code:
#import "FirstViewController.h"
#import "YoutubePost.h"
#import "AFNetworking.h"
#interface FirstViewController ()
#end
#implementation FirstViewController
#synthesize tableView = _tableView, activityIndicatorView = _activityIndicatorView, movies = _movies;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Videos", #"Videos");
self.tabBarItem.image = [UIImage imageNamed:#"newtab1"];
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.navigationController setNavigationBarHidden:YES];
self.tableView.separatorColor = [UIColor clearColor];
// Setting Up Activity Indicator View
self.activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
self.activityIndicatorView.hidesWhenStopped = YES;
self.activityIndicatorView.center = self.view.center;
[self.view addSubview:self.activityIndicatorView];
[self.activityIndicatorView startAnimating];
self.tableView.separatorColor = [UIColor clearColor];
// Initializing Data Source
self.movies = [[NSArray alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://my-website.com/link-to-json.php?name=Name&orderby=published"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.movies = JSON;
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
}
// Table View Data Source Methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
if (self.movies && self.movies.count) {
return self.movies.count;
} else {
return 0;
}
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 378;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *simpleTableIdentifier = #"YoutubePost";
YoutubePost *cell = (YoutubePost *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"YoutubePost" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
cell.title.text = [movie objectForKey:#"title"];
NSURL *url = [[NSURL alloc] initWithString:[movie objectForKey:#"link"]];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
int storyIndex = [indexPath indexAtPosition: [indexPath length] - 1];
NSString * storyLink = [[_movies objectAtIndex: storyIndex] objectForKey:#"link"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:storyLink]];
NSString *formattedJSON = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:[self.tweets objectAtIndex:indexPath.row] options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding];
NSLog(#"tweet:\n%#", formattedJSON);
}
#end
What is wrong? I see that the data successfully downloads to my custom Table View Cell, but every time I try to scroll down the app crashes. Please help me fix this.
Thanks.
Correct this:
// Initializing Data Source
//self.movies = [[NSArray alloc] init];
NSURL *url = [[NSURL alloc] initWithString:#"http://my-website.com/link-to-json.php?name=Name&orderby=published"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
self.movies = [[NSArray alloc] initWithArray:JSON];
[self.activityIndicatorView stopAnimating];
[self.tableView reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(#"Request Failed with Error: %#, %#", error, error.userInfo);
}];
[operation start];
And in your YouTubePost Nib add Identifier "YouTubePost":
And also in your YouTubePost Nib select your title UILabel and in the inspector change from:
To:
Or Change:
To:
This will do the job.
Change the lines below:
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"YoutubePost" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
Like this:
if (cell == nil)
{
UINib *nib = [UINib nibWithNibName:#"YoutubePost" bundle:nil];
[tableView registerNib:nib forCellReuseIdentifier:#"YoutubePost"];
tableViewCell = [tableView dequeueReusableCellWithIdentifier:#"YoutubePost"];
}
It looks like you're not doing any checking for [NSNull null] in your JSON. It is possible that the following code will give you [NSNull null] instead of an NSDictionary:
NSDictionary *movie = [self.movies objectAtIndex:indexPath.row];
You should filter these out before calling reloadData
Similarly, this line could also potentially return [NSNull null]:
cell.title.text = [movie objectForKey:#"title"];
You need to be prepared to handle that case. This may help you: Replace all NSNull objects in an NSDictionary
I am using the following code to reload my tableView when its done adding all the data to my Mutable Arrays, but the app always crashes
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//Spinner Add while waiting
UIActivityIndicatorView *spinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
spinner.frame = CGRectMake(147, 10, 25, 25);
[self.tableView addSubview:spinner];
[spinner startAnimating];
operationQueue = [[NSOperationQueue alloc] init];
usersFirstName = [[NSMutableArray alloc] init];
usersLastName = [[NSMutableArray alloc] init];
usersAvatar = [[NSMutableArray alloc] init];
NSString *urlstring = [NSString stringWithFormat:#"https://www.test.com/scribble/%#/",scribbleId];
NSURL *url = [NSURL URLWithString:urlstring];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
users = JSON[#"users_favored"];
if (users.count > 0) {
NSUInteger count = [users count];
for (NSUInteger i =0; i<count; i++) {
NSString *urlString = [NSString stringWithFormat:#"https://www.test.com%#",[users objectAtIndex:i]];
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *requestUser = [NSURLRequest requestWithURL:url];
AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:requestUser success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON){
if (i == 0) {
usersFirstName = [JSON[#"first_name"] mutableCopy];
usersLastName = [JSON[#"last_name"] mutableCopy];
usersAvatar = [JSON[#"user_avatar"] mutableCopy];
}else{
[usersFirstName addObjectsFromArray:JSON[#"first_name"]];
[usersLastName addObjectsFromArray:JSON[#"last_name"]];
[usersAvatar addObjectsFromArray:JSON[#"user_avatar"]];
}
if (i == count-1) {
[self.tableView reloadData];
[spinner stopAnimating];
[spinner removeFromSuperview];
}
}failure:nil];
[operationQueue addOperation:operation];
}
}else{
self.navigationItem.title = #"No Favors";
[spinner stopAnimating];
[spinner removeFromSuperview];
}
} failure:nil];
[operationQueue addOperation:operation];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return usersFirstName.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *simpleTableFavorIdentifier = #"FavorCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableFavorIdentifier];
if (cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableFavorIdentifier];
}
NSString *firstName = [usersFirstName objectAtIndex:indexPath.row];
NSString *lastName = [usersLastName objectAtIndex:indexPath.row];
NSString *avatar = [usersAvatar objectAtIndex:indexPath.row];
NSString *userFullName = [NSString stringWithFormat:#"%# %#",firstName,lastName];
UIImageView *userAvatar = (UIImageView *)[cell viewWithTag:100];
if ([avatar length ] > 0) {
NSString *img = [#"https://dtest_media_and_assets.s3.amazonaws.com/" stringByAppendingString:avatar];
[userAvatar setImageWithURL:[NSURL URLWithString:img] placeholderImage:[UIImage imageNamed:#"scribble.png"]];
}else{
userAvatar.image = [UIImage imageNamed:#"scribble.png"];
}
userAvatar.layer.cornerRadius = 4.0;
userAvatar.clipsToBounds = YES;
UILabel *userNameLabel = (UILabel *)[cell viewWithTag:101];
userNameLabel.text = userFullName;
return cell;
}
The error it gives is
2013-03-15 16:37:08.910 test[19547:c07] -[__NSCFString count]: unrecognized selector sent to instance 0x8679c80
2013-03-15 16:37:08.911 test[19547:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString count]: unrecognized selector sent to instance 0x8679c80'
*** First throw call stack:
(0x1cdf012 0x169fe7e 0x1d6a4bd 0x1ccebbc 0x1cce94e 0x143d7 0x7c8548 0x7cb224 0x68f952 0x68f2dc 0x140d7 0x281d2 0x29569 0x2f9553f 0x2fa7014 0x2f977d5 0x1c85af5 0x1c84f44 0x1c84e1b 0x21bb7e3 0x21bb668 0x5e3ffc 0x200d 0x1f35)
libc++abi.dylib: terminate called throwing an exception
Edit
everything works just fine when I use this instead
[usersFirstName addObject:JSON[#"first_name"]];
[usersLastName addObject:JSON[#"last_name"]];
[usersAvatar addObject:JSON[#"user_avatar"]];
[self.tableView reloadData];
if (i == count-1) {
[spinner stopAnimating];
[spinner removeFromSuperview];
}
try the same with that function:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSLog(#"usersFirstName is of type %#", NSStringFromClass([usersFirstName class]));
return [usersFirstName count];
}
I guess you have to replace:
if (i == 0) {
usersFirstName = [JSON[#"first_name"] mutableCopy];
usersLastName = [JSON[#"last_name"] mutableCopy];
usersAvatar = [JSON[#"user_avatar"] mutableCopy];
}else{
[usersFirstName addObjectsFromArray:JSON[#"first_name"]];
[usersLastName addObjectsFromArray:JSON[#"last_name"]];
[usersAvatar addObjectsFromArray:JSON[#"user_avatar"]];
}
with just:
[usersFirstName addObject:JSON[#"first_name"]];
[usersLastName addObject:JSON[#"last_name"]];
[usersAvatar addObject:JSON[#"user_avatar"]];
The issue is that this:
users = JSON[#"users_favored"];
Returns an NSString, when it looks you are expecting an NSArray.
Verify this using:
users = JSON[#"users_favored"];
NSLog(#"users is of type %#", NSStringFromClass([users class]));
Something is either wrong with your assumption or the JSON is broken.