I have a very tricky situation. And all things I have did programmatically.
1) I have UITableView.
2) In every cell of this tableview I have one uibutton.
3) On click of UIButton I want to show a UIAlertView, Which have yes and not buttons.
4) On click of yes button I want to delete that cell whose UIButton had shown up this alertview.
Below is my code snippet:
- (void) removeFriends:(id)sender
{
/*
I want to show alertview at here...
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"CONFIRM",nil) message:NSLocalizedString(#"REMOVE_FRIEND",nil) delegate:self cancelButtonTitle:#"No" otherButtonTitles:#"Yes", nil];
alert.tag = 21;
alert.accessibilityIdentifier = #"Remove";
[alert show];
*/
UIButton *btn = (UIButton*)sender;
int indx = btn.tag;
NSString *friend_id = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
// URL creation
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",usrId];
NSURL *URL = [NSURL URLWithString:address];
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"DELETE"];
responseData = [[NSMutableData alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
[self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:pathOfTheCell, nil] withRowAnimation:UITableViewRowAnimationFade];
[self viewDidLoad];
[self.table reloadData];
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// here want to make call to server
}
}
}
Just put this:
NSString *friend_id = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
// URL creation
NSString *path = [[NSBundle mainBundle] objectForInfoDictionaryKey:#"path"];
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",usrId];
NSURL *URL = [NSURL URLWithString:address];
NSLog(#"%#",address);
// request creation
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLCacheStorageAllowedInMemoryOnly
timeoutInterval:60.0];
[request setHTTPMethod:#"DELETE"];
responseData = [[NSMutableData alloc] init];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
[self.table deleteRowsAtIndexPaths:[NSArray arrayWithObjects:pathOfTheCell, nil] withRowAnimation:UITableViewRowAnimationFade];
[self viewDidLoad];
[self.table reloadData];
into this:
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"]){
if (buttonIndex == 1) {
// here want to make call to server
}
}
and create a property in your .h file which will be holding the id of the button which had been pressed. Like this:
//in your .h file
#property (nonatomic, strong) NSString *yourId;
and in your button-action just set it like this:
self.yourId = [friendsId valueForKey:[NSString stringWithFormat:#"%d",indx]];
In the first code snippet I guess you will have to replace usrId with self.yourId, so it will be
NSString *address = [NSString stringWithFormat:#"%#%#%#", path,#"users/",self.yourId];
EDIT:
Remove this:
UITableViewCell *buttonCell = (UITableViewCell *)[btn superview];
and change this:
NSIndexPath* pathOfTheCell = [self.table indexPathForCell:buttonCell];
to this:
NSIndexPath* pathOfTheCell = [NSIndexPath indexPathForRow:self.yourId]
self.yourID is the indexPath.row value which was saved in your button.tag property.
In this situation, you can assign index of cell inalertview tag and use this tag to perform your operation.
Thanks
Update:
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// here want to make call to server
// User alertView.tag as index to delete
}
}
}
view.h
#interface MyReservationViewController : UIViewController
{
int Delete_row;
}
view.m
- (IBAction)delete_btn:(id)sender
{
UIButton *buttontag = (UIButton *)sender;
//NSLog(#"%d",buttontag.tag);
Delete_row = buttontag.tag;
UIAlertView *Alert = [[UIAlertView alloc]initWithTitle:#"Delete Reservation" message:#"Are you sure to want Delete Reservation ??" delegate:self cancelButtonTitle:#"Delete" otherButtonTitles:#"Cancel",nil];
Alert.tag=1;
[Alert show];
[Alert release];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(alertView.tag==1)
{
if(buttonIndex == 0)
{
NSLog(#"%d",Delete_row);
//delete cell
[Arr removeObject:Delete_row];
[tbl reloadData];
}
}
}
-(void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if([alertView.accessibilityIdentifier isEqualToString:#"Remove"])
{
if (buttonIndex == 1)
{
// add server call to delete the relevant data
// and then refresh your array that you are using in cellForRowAtIndex
//and reload table. thats it.
}
}
Related
I have an issue with reloading a UITableView when calling from other viewcontroller. I have called a service from viewcontroller.m and the results are displayed in tableviewcontroller.m. Here is my problem, I have a button in UITableViewCell, when clicked on a button, the table should be reloaded or refreshed.
Below is my code:
viewController.m
NSString * post = [[NSString alloc]initWithFormat:#"country=%#&state=%#&userId=%#",_txtSearchField.text,UserId];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"url"]];
tableviewcontroller.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
if(!cell)
{
cell = [[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
NSArray *arr=[[profileArr objectAtIndex:indexPath.row] allKeys];
cell.lblAge.text = [[[profileArr objectAtIndex:indexPath.row] valueForKey:key] valueForKey:#"Age"];
cell.lblLocation.text = [[[profileArr objectAtIndex:indexPath.row] valueForKey:key] valueForKey:#"Address"];
cell.lblProfession.text = [[[profileArr objectAtIndex:indexPath.row] valueForKey:key] valueForKey:#"Occupation"];
}
-(void)buttonclick:(id)sender
{
UIButton *btn = sender;
NSArray *arr=[[profileArr objectAtIndex:btn.tag] allKeys];
NSString *key=[arr objectAtIndex:0];
NSMutableDictionary *userDict=[[profileArr objectAtIndex:btn.tag] objectForKey:key];
NSString *str = [userDict objectForKey:#"UserId"];
[self callbuttonService:str];
}
-(void)callbuttonService:(NSString *)OtherUserId
{
//service is called
}
#pragma mark - MRConnection Delegate Methods
- (void)jsonData:(NSDictionary *)jsonDict
{
[SVProgressHUD dismiss];
NSMutableArray *jsonArr1;
jsonArr1=[jsonDict objectForKey:#"DataTable"];
if (![jsonArr1 isEqual:[NSNull null]]) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Employee" message:#"Sucess" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* ok = [UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:nil];
[alertController addAction:ok];
[self presentViewController:alertController animated:YES completion:nil];
[alertController.view setTintColor:[UIColor blackColor]];
}
else{
[SVProgressHUD showErrorWithStatus:#"Something went wrong!"];
}
}
According to your question, you have call service in viewcontroller.m file and you want to reload tableview in tableviewcontroller.m file. Please try this. keep coding.
viewController.m
-(void)callbuttonService:(NSString *)OtherUserId
{
//service is called
}
#pragma mark - MRConnection Delegate Methods
- (void)jsonData:(NSDictionary *)jsonDict
{
[SVProgressHUD dismiss];
NSMutableArray *jsonArr1;
jsonArr1=[jsonDict objectForKey:#"DataTable"];
if (![jsonArr1 isEqual:[NSNull null]]) {
NSDictionary *DictionaryData = [[NSDictionary alloc]init];
[DictionaryData setValue:jsonArr1 forKey:#"data"];
[[NSNotificationCenter defaultCenter] postNotificationName:#"tableReload" object:nil userInfo:DictionaryData];
}
else{
[SVProgressHUD showErrorWithStatus:#"Something went wrong!"];
}
}
tableviewcontroller.m
-(void)viewDidLoad() {
super.viewDidLoad()
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(tableReloadNotification:) name:#"tableReload" object:nil];
}
- (void) tableReloadNotification:(NSNotification *) notification {
NSDictionary *info = notification.userInfo;
if (info != nil) {
NSMutableArray *jsonArr1 = [info valueForKey:#"data"];
tableview.reloadData();
}
}
You can use NSNotificationCenter for reload table view from another class. When your web service respond successfully then post your local notification.
Have you tried just calling [tableView reloadData]?
Also I fail to see how you add a button to your default UITableViewCell. Maybe you want this:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
// check if correct cell was tapped
if (indexPath.section == 0 && indexPath.row == 0)
{
[tableView reloadData];
}
}
When you implement this method, it will be called whenever you tap a UITableViewCell, you won't need a button or something.
Of course, you're free to bind the [tableView reloadData] to any other action in your app, e. g. a button in the toolbar or something.
I have a master-detail program that I add items through a UIAlert to the master list, but when the app quits, the items I added are gone, how can I save the values I added? How would I change to the code below to do this? I've heard you can save to the plist, but I don't know how to use that functionality and I'm not sure its necessary. Thanks!
The value I want to save and reload is "keepValue" which is a NSString property I defined in the header file.
If you are curious how I change the NSDate to a pop up AlertView to add any value you want look here:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target:self
action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender
{
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self
cancelButtonTitle:#"Add"
otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString; //Want to keep after app quits
[self.savedSearchValues addObject:self.keepValue]; //trying to save values to reuse?
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"Cell" forIndexPath:indexPath];
NSString *object = _objects[indexPath.row]; //changed here from default NSDate
cell.textLabel.text = [object description];
return cell;
}
Use NSUserDefaults. There are a lot of answers in StackOverflow.
I got a good response on another site, thank you #Robert Bojor. For anyone else curious I added the save data to file portion of the code to the end of the AlertView method, and I added the read it back in the viewDidLoad (both in the Master View)
Here is final code if you are interested:
- (void)viewDidLoad
{
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
//**********************READ CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
if ([paths count] > 0) {
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:addedItems];
if (fileExists) {
_objects = [NSArray arrayWithContentsOfFile:addedItems];
} else {
// Notify the user the file doesn't exist or try to load it from a cached resource.
}
}
}
//modified to pop up alertView see: http://stackoverflow.com/questions/11163341/how-do-i-replace-the-date-with-a-writable-title
- (void)insertNewObject:(id)sender {
UIAlertView *getTitle = [[UIAlertView alloc] initWithTitle:#"Add Search Keyword" message:nil delegate:self cancelButtonTitle:#"Add" otherButtonTitles:nil];
getTitle.alertViewStyle = UIAlertViewStylePlainTextInput;
[getTitle show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (!_objects) {
_objects = [[NSMutableArray alloc] init];
}
NSString * userEnterThisString = [[alertView textFieldAtIndex:0] text];
[_objects insertObject:userEnterThisString atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
self.keepValue = userEnterThisString;
//**********************SAVE CODE*************************
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *addedItems = [[paths objectAtIndex:0] stringByAppendingPathComponent:#"addedItems.dta"];
// The file name and extension can be changed at will
[_objects writeToFile:addedItems atomically:YES];
}
In my UITableViewController there are custom cells populated from JSON. Each cell has a UILabel showing a text value (#"valoracion"). When the user selects a row, a detail view from the cell object is shown. At this detail view, the user can change the value of valoracion. If the user goes back to the UITableViewController, valoracion should show the new value, but actually it shows the old value.
What should I do to update valoracion in the UITableViewController, when the user goes back from the detail view to the UITableViewController.
UPDATED***
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
CustomCell *cell =[tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (cell ==nil){
cell = [[CustomCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"Cell"];
}
//cell.backgroundColor = [UIColor clearColor];
cell.nombreEmpresaLabel.text = [[categorias objectAtIndex:indexPath.row] objectForKey:#"nombreEmpresa"];
//[[cell contentView] setBackgroundColor:[UIColor clearColor]];
//cell.textLabel.backgroundColor = nil;
// cell.detailTextLabel.backgroundColor=nil;
cell.textLabel.textColor = [UIColor whiteColor];
cell.direccionEmpresaLabel.text= [[categorias objectAtIndex:indexPath.row] objectForKey:#"direccionEmpresa"];
NSMutableString *logo = [[NSMutableString alloc]initWithString:#"http://mujercanariasigloxxi.appgestion.eu/logos/"];
NSString *imageURL = [[categorias objectAtIndex:indexPath.row] objectForKey:#"strImagen"];
cell.meGustaHits.text = [[categorias objectAtIndex:indexPath.row] objectForKey:#"valoracionEmpresa"];
if(imageURL != nil && ![imageURL isEqual:[NSNull null]])
{
[logo appendString:imageURL];
NSURL *logoURL = [NSURL URLWithString:logo];
NSData *logoData = [NSData dataWithContentsOfURL:logoURL];
cell.logoImage.image = [UIImage imageWithData:logoData];
}
else{
cell.logoImage.image = [UIImage imageNamed:#"icono80"];
}
return cell;
}
Inside viewDidLoad method:
//URL definition where php file is hosted
int categoriaID = [[categoriaDescription objectForKey:#"idCategoria"] intValue];
NSString *string = [NSString stringWithFormat:#"%d", categoriaID];
NSLog(#"CATEGORIA ID STGRING %#",string);
NSMutableString *ms = [[NSMutableString alloc] initWithString:#"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresaslist.php?id="];
[ms appendString:string];
// URL request
NSLog(#"URL = %#",ms);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];
//URL connection to the internet
[[NSURLConnection alloc]initWithRequest:request delegate:self];
And now the JSON delegate methods and didSelecRowAtIndexpath method:
//methods to perform the connection and population of data
-(void)connection: (NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
data = [[NSMutableData alloc]init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{
[data appendData:thedata];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
//if data received network indicator not visible
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
//array waterfalls populated via JSON from database
categorias = [NSJSONSerialization JSONObjectWithData:data options:nil error:nil];
NSLog(#"THE DA TA &#",categorias);
[self.tableView reloadData];
}
//only in case of error
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
UIAlertView *errorView = [[UIAlertView alloc]initWithTitle:#"Error" message:#"The download could not complete - please make sure you are connected to eithre 3G or WiFi" delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil];
[errorView show];
//if no connection network indicator not visible
[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
DetalleEmpresaViewController *detailViewController =[self.storyboard instantiateViewControllerWithIdentifier:#"detailEmpresaViewController"];
detailViewController.title =[[categorias objectAtIndex:indexPath.row]objectForKey:#"idCategoria"];
detailViewController.detalleDescription = [categorias objectAtIndex:indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
}
Try call [tableview reloadData] method and make sure that you have correct implementation of tableview delegate methods.
If place where you change and save your JSON is another, than tableViewController, then put reloadData method in viewDidAppear of tableViewController class. If you saving JSON in other method of same tableViewController, then place reloadData in last line of this method.
I am using UITableView. And if there is no network connection then there will be exception thrown in viewDidload. My viewDidLoad function is:
#try {
NSLog(#"Request URL = %#",URLString);
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
URLWithString:URLString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request
returningResponse:nil error:nil];
NSError *jsonParsingError = nil;
NSDictionary *tableData = [NSJSONSerialization JSONObjectWithData:response
options:0
error:&jsonParsingError];
// Grab whole data with data field in JSON
// responseArray = [tableData objectForKey:#"data"];
responseArray = [[NSMutableArray alloc]initWithArray:[tableData objectForKey:#"data"]];
for(int i = 0; i < responseArray.count; i++)
{
NSArray * tempArray = responseArray[i];
responseArray[i] = [tempArray mutableCopy];
}
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(280.0, 0.0, 40.0, 40.0)];
[btn setImage:[UIImage imageNamed:#"sort_icon.png"] forState:UIControlStateNormal];
[btn addTarget:self action:#selector(showActionSheet) forControlEvents:UIControlEventTouchUpInside];
UIBarButtonItem *barbutton = [[UIBarButtonItem alloc]initWithCustomView:btn];
self.navigationItem.rightBarButtonItem = barbutton;
}
#catch (NSException *exception)
{
exceptionOccured = YES;
NSLog(#"Exception Ocurred");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
In cellForRowAtIndexPath I am doing this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
#try {
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
tempDict = [responseArray objectAtIndex:indexPath.row];
return cell;
}
#catch (NSException *exception)
{
NSLog(#"Error in CEll Create");
NSLog(#"Draw Alert");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
and in AlertViewDelegate Function I am doing
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
[self.navigationController popViewControllerAnimated:YES];
}
Now problem is that it is not showing the Alert whenever there is an exception and re-throws the exception and shows the Error
Thread 1: EXC_BAD_ACCESS(code=2, address=0x2)
Any help will be appreciated...
You should avoid throwing exceptions in your code.
First of all you could use Reachability Class to determine whether or not an active internet connection is available.
I would definitively recommend using the NSURLConnectionDelegate protocol for URL connections. So you can use the better asynchronous programming style.
The problem is somewhere else. When - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath is called it means the system needs the tableView to be reloaded. Therefore, you should not check for data inside that function. When you enter this function, you should be sure that your data is ok.
What you have to do is firstly check your data in a specific function:
-(void)CheckData(NSArray *responseArray) {
#try {
//Retrieve your data & check if its valid
self.dataArray = responseArray;
[self.tableView reloadData];
}
#catch (NSException *exception)
{
NSLog(#"Error in check Data");
NSLog(#"Draw Alert");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error in connectivity" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
Then, implement your data source delegates:
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.dataArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if(cell == nil){
cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ;
}
//TODO: Init your cell using your self.dataArray content
return cell;
}
I would recommend import this SystemConfiguration framework and use the same. This will check whether network connection is available or not. Below is the simple code:-
#import <SystemConfiguration/SystemConfiguration.h>
-(void)yourMethod
{
SCNetworkConnectionFlags flags = 0;
if (yourhostname && [yourhostname length] > 0)
{
flags = 0;
BOOL found = NO;
SCNetworkReachabilityRef reachabilityRef = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, [yourhostname UTF8String]);
if (reachabilityRef)
{
found = SCNetworkReachabilityGetFlags(reachabilityRef, &flags)
&& (flags & kSCNetworkFlagsReachable)
&& !(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachabilityRef);
reachabilityRef = NULL;
}
if (found)
{
NSLog(#"Connection available");
}
else
{
NSLog(#"Connection not available");
}
}
I am loading an image view from an online server (Google Sites in this case) based on what the user has selected from a table view (the table view is being populated from a plist which is loaded online). The code for that is already working but I'm trying to add an alert view for images that do not load. This is my Table View Controller.
#import "TableViewController.h"
#import "MapViewController.h"
#interface TableViewController ()
#end
#implementation TableViewController
#synthesize trailList;
#synthesize trailView;
- (void)viewDidLoad
{
[super viewDidLoad];
NSURL *url = [NSURL URLWithString: #"https://sites.google.com/site/majorprojectgjk/Trails.plist"];
trailList = [[NSMutableArray alloc] initWithContentsOfURL: url];
// Do any additional setup after loading the view, typically from a nib.
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [trailList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellid = #"trailCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier: cellid];
if (cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier: cellid];
}
cell.textLabel.text = [trailList objectAtIndex: indexPath.row];
return cell;
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString: #"pushView"])
{
NSIndexPath *indexPath = [self.trailView indexPathForSelectedRow];
MapViewController *mvc = segue.destinationViewController;
mvc.subjects = [trailList objectAtIndex: indexPath.row];
}
}
This would be my Map View Controller code.
#import "MapViewController.h"
#interface MapViewController ()
#end
#implementation MapViewController
#synthesize map;
#synthesize subjects;
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear: (BOOL)animated];
NSString *site = #"https://sites.google.com/site/majorprojectgjk/";
NSLog(#"Display: %#", subjects);
NSString *mapString = #"Map";
NSString *png = #".png";
//NSString *url = [NSString stringWithFormat: #"%#%#%#%#",site, subjects, mapString, png];
#try
{
NSString *space = subjects;
if ([space rangeOfString:#" "].location == NSNotFound)
{
NSString *url = [NSString stringWithFormat: #"%#%#%#%#",site, subjects, mapString, png];
map.image = [UIImage imageWithData: [NSData dataWithContentsOfURL: [[NSURL alloc] initWithString: url]]];
NSLog(#"URL: %#", url);
}
else
{
NSLog(#"string contains space");
NSString *removeSpace = [subjects stringByReplacingOccurrencesOfString:#" " withString:#""];
NSString *url = [NSString stringWithFormat: #"%#%#%#%#",site, removeSpace, mapString, png];
map.image = [UIImage imageWithData: [NSData dataWithContentsOfURL: [[NSURL alloc] initWithString: url]]];
NSLog(#"URL %#", url);
}
}
#catch (NSException *ex) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error!" message:#"The map could not load!" delegate: self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[alert show];
}
}
As I said earlier, the code for these are working perfectly fine. The image is downloading perfectly fine from the URL and the data is being parsed from the table view as well. I would like to know how to use a #try #catch block in order to alert the user that the UIImageView is empty (this happens when the URL is invalid and the map is not loaded into the server yet).
`enter code here`#catch(NSException *ex)
{
NSString *str=[ex copy];
//write code for alert
}