So i have this piece of code in my TVC
-(void)getCats {
[HUD showAnimated:YES whileExecutingBlock:^{
catArray = [menuPost getCategories];
} completionBlock:^{
if(catArray == nil){
[[[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Hubo un problema intente mas tarde" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil] show];
}
}];
}
i placed some break points and i noticed that i doesn't execute the method right away it jumps to
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return catArray.count;
}
so the problem is that since it skips this line of code(below) the numberOfRows is 0 and this method returns an NSMutableArray after making a post it wouldn't display the objects
catArray = [menuPost getCategories];
your code is fine , you are not refresh your table
-(void)getCats {
[HUD showAnimated:YES whileExecutingBlock:^{
catArray = [menuPost getCategories];
} completionBlock:^{
if(catArray == nil){
[[[UIAlertView alloc] initWithTitle:#"Oops!" message:#"Hubo un problema intente mas tarde" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil] show];
// if your array count ==0 , hidden the table
[yourtableviewname setHidden:YES];
}
else
{
// if your array count !=0 , open the table, and reload/refresh the table
[yourtableviewname setHidden:NO];
[yourtableviewname reloadData];
}
}];
}
I have an UITableView, with cells that you can tap on.
When you tap, some actions are run, but that is not important in this context. First time I press, it handles the tap correctly. Second time it is running the code, but all View updates like showing a UIAlertView or showing a new view is delayed. But not delayed by time - It's waiting for me to touch the screen. No matter where I press or how long I wait, I just have to press. And it's every time but the first.
My TableView is set to single selection and not to show selection on touch. Any Ideas why it does this?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if ([cell isKindOfClass:[DetailTableViewCell class]]) {
DetailTableViewCell *detailCell = (DetailTableViewCell *)cell;
NSString *hourString = [detailCell hourString];
if (!detailCell.booking) {
NSDate *rightNow = [NSDate new];
NSDate *cellDate = [self.currentDate dateWithHour:indexPath.row andMinutes:0];
// Only allow future bookings (but allow people people to book within the hour)
if([rightNow compare:[cellDate nextHour]] == NSOrderedAscending){
[self performSegueWithIdentifier:#"roomBooking" sender:indexPath];
return;
} else {
[[[UIAlertView alloc] initWithTitle:#"Error" message:#"We currently do not allow our users make bookings in the past" delegate:nil cancelButtonTitle:#"Gotcha" otherButtonTitles:nil] show];
return;
}
} else if ([detailCell.booking hasPhoneNumber]) {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:#"telprompt://%ld",(long)[detailCell.booking telephone]]]];
return;
} else {
//TODO: FIND OUT IF BOOKING IS OWNED BY THE CURRENT USER
[[[UIAlertView alloc] initWithTitle:#"Booking"
message:[NSString stringWithFormat:#"You are now removing the booking at %#.", hourString]
delegate:nil
cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
#weakify(self);
[self.room removeBookingWithId:[detailCell.booking.bookingId integerValue] andCompletion:^(BOOL success, NSError *error) {
#strongify(self);
if (success) {
#weakify(self);
[self.room.location updateBookingsWithCompletion:^(BOOL success, NSError *error) {
#strongify(self);
if (success) {
[self.calendar reloadData];
}
}];
}
}];
return;
}
}
}
SelectionStyle was set to None, but we changed it to something else, which solved the problem.
Click on the TableViewCell itself.
In your properties section locate: "Selection"
Set to: Blue/Grey/Default.
When I click on a button in one row, the button in a different row disappears. Why might this be happening?
I looked at the following question and all the other questions within it, but nothing really answers my issue.
Custom, Imageless UIButton title disappears
I used the Debug Color Blended Layers to see if it's just a color thing, but my button just appears to disappear completely. I suspected this was a button.hidden property thing so I hardcoded button.hidden = NO; but nothing has changed.
What went wrong here?
Table Control Code:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if ([locationObjectsArray count] > 0)
{
return [locationObjectsArray count]+1;
}
else
return 1;
}
// Populate the Table View with member names
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier= #"Cell";
UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the Cell...
UIButton *selectButton = (UIButton *)[cell viewWithTag:1];
UILabel *cityNamesText = (UILabel *)[cell viewWithTag:2];
UIButton *editButton = (UIButton *)[cell viewWithTag:3];
//NSLog(#"[locationObjectsArray count]: %lu", (unsigned long)[locationObjectsArray count]);
if (indexPath.row >= [locationObjectsArray count]) {
// locationObjectsArray count == 0; Empty Array
cityNamesText.text = #"Add New Location";
NSLog(#"%ld: %#", (long)indexPath.row, #"Add New Location");
editButton.hidden = NO;
[editButton setTitle:#"Add" forState:UIControlStateNormal];
//[editButton setTitle:#"Add" forState:UIControlStateApplication];
selectButton.hidden = YES;
}
else if ([locationObjectsArray count] > 0) {
LocationObject *locObject = [locationObjectsArray objectAtIndex:indexPath.row];
NSLog(#"%ld: %#", (long)indexPath.row, [locObject getLocationName]);
cityNamesText.text = [locObject getLocationName];
selectButton.hidden = NO;
editButton.hidden = NO;
}
// Assign button tags
selectButton.tag = indexPath.row;
editButton.tag = indexPath.row;
[selectButton addTarget:self action:#selector(selectButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
[editButton addTarget:self action:#selector(editButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
LocationObject *selectedLocationObject = [self loadLocationObjectWithKey:#"locObject"];
// Set Selected Cell to different Color
if ([cityNamesText.text isEqualToString:[selectedLocationObject getCityName]]) {
// Change to lightBlue color
UIColor * lightBlue = [UIColor colorWithRed:242/255.0f green:255/255.0f blue:254/255.0f alpha:1.0f];
[cell setBackgroundColor:lightBlue];
}
else
{
// All non-selected cells are white
//[cell setBackgroundColor:[UIColor whiteColor]];
//editButton.hidden = NO;
}
return cell;
}
// Select Button Clicked method
-(void)selectButtonClicked:(UIButton*)sender
{
if ([locationObjectsArray count] == 0)
{
NSLog(#"locObject count == 0");
// locationObjectsArray count == 0; Empty Array
// City name input is invalid
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"No Locations Set"
message:#"Please add a new location."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
else
{
NSLog(#"locObject count > 0");
if (sender.tag >= locationObjectsArray.count) {
// Create local isntance of the selected locationObject
LocationObject *locObject = [locationObjectsArray objectAtIndex:sender.tag];
// Set locObject as current default locObject
[self saveLocationObject:locObject key:#"locObject"];
}
[mainTableView reloadData];
}
}
// Edit Button Clicked method
-(void)editButtonClicked:(UIButton*)sender
{
if ([locationObjectsArray count] == 0) {
// locationObjectsArray count == 0; Empty Array
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"Add Location"
message:#"Input City Name"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles: nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert addButtonWithTitle:#"Save"];
[alert show];
}
else
{
selectedObjectInArray = sender.tag;
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"Edit Location"
message:#"Input City Name"
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles: nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert addButtonWithTitle:#"Save"];
[alert show];
}
}
// Handle alertView
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
if ([alertView.title isEqualToString:#"Add Location"]) {
// Add Location Alert View
if (buttonIndex == 0)
{
NSLog(#"You have clicked Cancel");
}
else if(buttonIndex == 1)
{
NSLog(#"You have clicked Save");
UITextField *cityNameTextField = [alertView textFieldAtIndex:0];
NSString *saveLocationName = cityNameTextField.text;
NSLog(#"saveLocationName: %#", saveLocationName);
if ([self isLocationValid:saveLocationName] == YES) {
NSLog(#"location is valid. locationObjectsArray.count = %lu", locationObjectsArray.count);
if (locationObjectsArray.count == 0) {
locationObjectsArray = [NSMutableArray array];
}
// City name input is valid
LocationObject *locObject = [[LocationObject alloc] init];
[locObject setCityName:saveLocationName];
locObject.byCityName = YES;
[locationObjectsArray addObject:locObject];
NSLog(#"After addObject: locationObjectsArray.count = %lu", locationObjectsArray.count);
[self saveLocationArrayObject:locationObjectsArray key:#"locationObjectsArray"];
[mainTableView reloadData];
}
else
{
// City name input is invalid
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"City Name Invalid"
message:#"Unable to locate input city."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
}
}
else if ([alertView.title isEqualToString:#"Edit Location"])
{
// Edit Location Alert View
if (buttonIndex == 0)
{
NSLog(#"You have clicked Cancel");
}
else if(buttonIndex == 1)
{
NSLog(#"You have clicked Save");
UITextField *cityNameTextField = [alertView textFieldAtIndex:0];
NSString *saveLocationName = cityNameTextField.text;
if ([self isLocationValid:saveLocationName]) {
// City name input is valid
int selectedIndex = (int)selectedObjectInArray;
LocationObject *locObject = [locationObjectsArray objectAtIndex:selectedIndex];
[locObject setCityName:saveLocationName];
[locObject setByCityName:(Boolean *)TRUE];
[locationObjectsArray setObject:locObject atIndexedSubscript:selectedIndex];
[self saveLocationArrayObject:locationObjectsArray key:#"locationObjectsArray"];
[mainTableView reloadData];
}
else
{
// City name input is invalid
UIAlertView * alert =[[UIAlertView alloc ] initWithTitle:#"City Name Invalid"
message:#"Unable to locate input city."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
}
}
}
}
Before:
After check button is selected:
Your issue is in these lines in cellForRowAtIndexPath:
// Assign button tags
selectButton.tag = indexPath.row;
editButton.tag = indexPath.row;
The tags will get mixed up as the cells are reused, I would recommend trying to omit using tags in this situation and use e.g. IBOutlets as #rdelmar pointed out.
I'm making a UITableView where you can click on a tableviewcell and this should trigger a phone call to a phone number in an array.
The phone numbers are listed in an array, and these are also shown in the tableviewcell.
_Number = #[#"100",
#"101",
#"070 245 245"];
I'm new at this and I don't know how to start with this, I already got my tableviewcontroller and tableviewcell classes which are working.
Gratz and thanks in advance
You can do following :
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *phoneNumber = [Number objectAtIndex:indexPath.row];
NSURL *phoneNumberURL = [NSURL URLWithString:[NSString stringWithFormat:#"tel:%#", phoneNumber]];
if( [[UIApplication sharedApplication] canOpenURL:phoneNumberURL] )
{
[[UIApplication sharedApplication] openURL:phoneNumberURL];
}
else
{
UIAlertView *errorAlert = [[UIAlertView alloc] initWithTitle:#"Alert!!!" message:#"Not able to make a phone call." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
}
I cannot resolve this issue and I have no idea why my UITableView duplicates rows whenever I click on the segment control. I want to refresh the table view with new data when segment control changes. I have tried many things and googled it but could not find any solution. I would appreciated if someone can help me please. I am still learning xcode and a lot to learn. here is my code -
#import "citsViewController.h"
#import "citsParseOperation.h"
#import "citsFuelFinder.h"
#import "citsTableViewCell.h"
#import "citsAboutViewController.h"
#import "MBProgressHUD.h"
#import <CoreLocation/CoreLocation.h>
// this framework is imported so we can use the kCFURLErrorNotConnectedToInternet error code
#import <CFNetwork/CFNetwork.h>
#import <MapKit/MapKit.h>
#interface citsViewController ()
{
CLLocationManager *locationManager;
CLGeocoder *geocoder;
CLPlacemark *placemark;
NSString *currentLoc;
int productName;
}
#property (nonatomic) NSMutableArray *earthquakeList;
#property (nonatomic) citsFuelFinder *currentEarthquakeObject;
#property (nonatomic, weak) IBOutlet UILabel *locationLabel;
// queue that manages our NSOperation for parsing earthquake data
#property (nonatomic) NSOperationQueue *parseQueue;
#end
#pragma mark -
#implementation citsViewController
#synthesize nomatchesView;
#synthesize footerLabel;
#synthesize headerLabel;
#synthesize fuelType;
#synthesize bannerIsVisible;
- (void)viewDidLoad {
[super viewDidLoad];
//refresh the tableview
UIRefreshControl *refreshControl=[[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(refresh:) forControlEvents:UIControlEventValueChanged];
self.refreshControl=refreshControl;
UIButton *infoButton = [UIButton buttonWithType:UIButtonTypeInfoLight];
[infoButton addTarget:self action:#selector(aboutUs:) forControlEvents:UIControlEventTouchUpInside];
//add info button in the navigation controller
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:infoButton] ;
//initialize location manager
locationManager=[[CLLocationManager alloc] init];
//to get location
geocoder=[[CLGeocoder alloc] init];
//show network activity
[UIApplication sharedApplication].networkActivityIndicatorVisible = TRUE;
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
//call the location manager update function
[locationManager startUpdatingLocation];
}
-(void)refresh:(id)sender {
//update table data
[locationManager startUpdatingLocation];
[self.refreshControl endRefreshing];
[self.tableView reloadData];
}
- (void)dealloc {
// we are no longer interested in these notifications:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:kAddEarthquakesNotificationName
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:kEarthquakesErrorNotificationName
object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:NSCurrentLocaleDidChangeNotification
object:nil];
}
/**
Handle errors in the download by showing an alert to the user. This is a very simple way of handling the error, partly because this application does not have any offline functionality for the user. Most real applications should handle the error in a less obtrusive way and provide offline functionality to the user.
*/
- (void)handleError:(NSError *)error {
NSString *errorMessage = [error localizedDescription];
NSString *alertTitle = NSLocalizedString(#"Error", #"Title for alert displayed when download or parse error occurs.");
NSString *okTitle = NSLocalizedString(#"OK ", #"OK Title for alert displayed when download or parse error occurs.");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle message:errorMessage delegate:nil cancelButtonTitle:okTitle otherButtonTitles:nil];
[alertView show];
}
/**
Our NSNotification callback from the running NSOperation to add the earthquakes
*/
- (void)addEarthquakes:(NSNotification *)notif {
assert([NSThread isMainThread]);
[self addEarthquakesToList:[[notif userInfo] valueForKey:kEarthquakeResultsKey]];
}
/**
Our NSNotification callback from the running NSOperation when a parsing error has occurred
*/
- (void)earthquakesError:(NSNotification *)notif {
assert([NSThread isMainThread]);
[self handleError:[[notif userInfo] valueForKey:kEarthquakesMessageErrorKey]];
}
/**
The NSOperation "ParseOperation" calls addEarthquakes: via NSNotification, on the main thread which in turn calls this method, with batches of parsed objects. The batch size is set via the kSizeOfFuelPumpBatch constant.
*/
- (void)addEarthquakesToList:(NSArray *)earthquakes {
NSInteger startingRow = [self.earthquakeList count];
NSInteger earthquakeCount = [earthquakes count];
NSMutableArray *indexPaths = [[NSMutableArray alloc] initWithCapacity:earthquakeCount];
for (NSInteger row = startingRow; row < (startingRow+earthquakeCount); row++) {
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:row inSection:0];
[indexPaths addObject:indexPath];
}
NSLog(#"record count %d",earthquakeCount);
[self.earthquakeList addObjectsFromArray:earthquakes];
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
//[self.tableView reloadData];
}
#pragma mark - UITableViewDelegate
// The number of rows is equal to the number of earthquakes in the array.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.earthquakeList count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *kEarthquakeCellID = #"EarthquakeCellID";
citsTableViewCell *cell = (citsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:kEarthquakeCellID];
if(cell==nil)
{
cell=[[citsTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kEarthquakeCellID];
}
// Get the specific earthquake for this row.
citsFuelFinder *earthquake = (self.earthquakeList)[indexPath.row];
[cell configureWithEarthquake:earthquake];
return cell;
}
/**
* When the user taps a row in the table, display the USGS web page that displays details of the earthquake they selected.
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *buttonTitle = NSLocalizedString(#"Cancel", #"Cancel");
//NSString *buttonTitle1 = NSLocalizedString(#"Show USGS Site in Safari", #"Show USGS Site in Safari");
NSString *buttonTitle2 = NSLocalizedString(#"Show Location in Maps", #"Show Location in Maps");
UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:buttonTitle destructiveButtonTitle:nil
otherButtonTitles: buttonTitle2, nil];
[sheet showInView:self.view];
}
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 500)];
headerLabel=[[UILabel alloc] initWithFrame:CGRectMake(10, 1.0, 300, 25)];
headerLabel.numberOfLines=0;
fuelType=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:#"ULP", #"PULP",#"Diesel",#"LPG", nil]];
fuelType.frame = CGRectMake(10, 30, 300,25);
//set first segment selected
[fuelType setSelectedSegmentIndex:0];
[fuelType addTarget:self action:#selector(segmentedControlHasChangedValue) forControlEvents:UIControlEventValueChanged];
headerLabel.font=[UIFont systemFontOfSize:10.0];
[headerView insertSubview:fuelType aboveSubview:headerLabel];
[headerView addSubview:headerLabel];
[headerView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:#"footer.gif"]]];
return headerView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
return 60;
}
#pragma mark -
/**
* Called when the user selects an option in the sheet. The sheet will automatically be dismissed.
*/
- (void)actionSheet:(UIActionSheet *)actionSheet willDismissWithButtonIndex:(NSInteger)buttonIndex {
NSIndexPath *selectedIndexPath = [self.tableView indexPathForSelectedRow];
citsFuelFinder *earthquake = (citsFuelFinder *)(self.earthquakeList)[selectedIndexPath.row];
switch (buttonIndex) {
case 0: {
// open the earthquake info in Maps
// create a map region pointing to the earthquake location
CLLocationCoordinate2D location = (CLLocationCoordinate2D) { earthquake.latitude, earthquake.longitude };
NSValue *locationValue = [NSValue valueWithMKCoordinate:location];
MKCoordinateSpan span = (MKCoordinateSpan) { 2.0, 2.0 };
NSValue *spanValue = [NSValue valueWithMKCoordinateSpan:span];
NSDictionary *launchOptions = #{ MKLaunchOptionsMapTypeKey : #(MKMapTypeStandard),
MKLaunchOptionsMapCenterKey : locationValue,
MKLaunchOptionsMapSpanKey : spanValue,
MKLaunchOptionsShowsTrafficKey : #(NO),
MKLaunchOptionsDirectionsModeDriving : #(NO) };
// make sure the map item has a pin placed on it with the title as the earthquake location
MKPlacemark *placemark = [[MKPlacemark alloc] initWithCoordinate:location addressDictionary:nil];
MKMapItem *mapItem = [[MKMapItem alloc] initWithPlacemark:placemark];
[mapItem setName:earthquake.location];
[mapItem openInMapsWithLaunchOptions:launchOptions];
break;
}
}
[self.tableView deselectRowAtIndexPath:selectedIndexPath animated:YES];
}
- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
NSLog(#"didFailWithError: %#", error);
UIAlertView *errorAlert = [[UIAlertView alloc]
initWithTitle:#"Error" message:#"Failed to Get Your Location" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[errorAlert show];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
HUD = [[MBProgressHUD alloc] initWithView:self.navigationController.view];
[self.navigationController.view addSubview:HUD];
// Regiser for HUD callbacks so we can remove it from the window at the right time
HUD.delegate = self;
HUD.labelText = #"Loading";
HUD.detailsLabelText = #"updating data";
HUD.square = YES;
self.earthquakeList = [NSMutableArray array];
self.currentEarthquakeObject=nil;
if([self.earthquakeList count] >0)
{
[self.earthquakeList removeAllObjects];
[self.tableView reloadData];
}
// Show the HUD while the provided method executes in a new thread
[HUD showWhileExecuting:#selector(addEarthquakesToList:) onTarget:self withObject:nil animated:YES];
NSLog(#"didUpdateToLocation: %#", newLocation);
CLLocation *currentLocation = newLocation;
if (currentLocation != nil) {
NSString *latitude=[NSString stringWithFormat:#"%.8f", currentLocation.coordinate.latitude];
NSString *longitude=[NSString stringWithFormat:#"%.8f", currentLocation.coordinate.longitude];
citsTableViewCell *tcell = [[citsTableViewCell alloc] init];
//set the latitude and longitude
tcell.lon =[longitude doubleValue];
tcell.lat = [latitude doubleValue];
NSLog(#"Lat:%#, Lon:%#", latitude,latitude);
}
//stop updating location
[locationManager stopUpdatingLocation];
//reverse geocoding
NSLog(#"Resolving the address");
[geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
NSLog(#"Found placemarks: %#, error: %#", placemarks, error);
if (error == nil && [placemarks count] > 0) {
placemark = [placemarks lastObject];
currentLoc=[NSString stringWithFormat:#"%#",placemark.locality];
if(currentLoc == NULL)
{
currentLoc=#"N/A";
}
NSLog(#"%#",currentLoc);
//add text to headertext
NSDate *currDate=[NSDate date];
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd/MM/yy HH:mm:ss"];
NSString *dateString=[dateFormatter stringFromDate:currDate];
NSString *loc=[NSString stringWithFormat:#"Your location: %#, Updated on: %#", currentLoc, dateString ];
[dateFormatter setDateFormat:#"EEEE, dd/MM/yyyy"];
NSString *headerDate=[dateFormatter stringFromDate:currDate];
headerLabel.text=[NSString stringWithFormat:#"Prices for: %#\n%#", headerDate,loc];
//currentLoc=[NSString stringWithFormat:#"%#", placemark.locality];
currentLoc=#"Mirrabooka";
if(productName==0)
{
productName=1;
}
NSString *prdStr=[[NSString alloc] initWithFormat:#"%d", productName];
NSString *str =[currentLoc stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
NSString *feedURLString =[[NSString alloc] initWithFormat: #"http://www.fuelwatch.wa.gov.au/fuelwatch/fuelWatchRSS?Product=%#&Suburb=%#", prdStr,str ];
NSURLRequest *earthquakeURLRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:feedURLString]];
NSLog(#"%#",feedURLString);
// send the async request (note that the completion block will be called on the main thread)
//
// note: using the block-based "sendAsynchronousRequest" is preferred, and useful for
// small data transfers that are likely to succeed. If you doing large data transfers,
// consider using the NSURLConnectionDelegate-based APIs.
//
[NSURLConnection sendAsynchronousRequest:earthquakeURLRequest queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
// back on the main thread, check for errors, if no errors start the parsing
//
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// here we check for any returned NSError from the server, "and" we also check for any http response errors
if (error != nil) {
[self handleError:error];
}
else {
// check for any response errors
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if ((([httpResponse statusCode]/100) == 2) ) {
// Update the UI and start parsing the data,
// Spawn an NSOperation to parse the earthquake data so that the UI is not
// blocked while the application parses the XML data.
//
citsParseOperation *parseOperation = [[citsParseOperation alloc] initWithData:data];
[self.parseQueue addOperation:parseOperation];
}
else {
NSString *errorString =
NSLocalizedString(#"HTTP Error", #"Error message displayed when receving a connection error.");
NSDictionary *userInfo = #{NSLocalizedDescriptionKey : errorString};
NSError *reportError = [NSError errorWithDomain:#"HTTP"
code:[httpResponse statusCode]
userInfo:userInfo];
[self handleError:reportError];
}
}
}];
// Start the status bar network activity indicator.
// We'll turn it off when the connection finishes or experiences an error.
//
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
self.parseQueue = [NSOperationQueue new];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(addEarthquakes:)
name:kAddEarthquakesNotificationName object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(earthquakesError:)
name:kEarthquakesErrorNotificationName object:nil];
} else {
NSLog(#"%#", error.debugDescription);
}
} ];
NSLog(#"%d",[self.earthquakeList count]);
}
-(void)clearData{
[self.tableView beginUpdates];
NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
for (int i = [self.tableView numberOfRowsInSection:0] - 1; i >= 0; i--)
{
[indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:0]];
NSLog(#"Deleted: %d",i);
}
[self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationFade];
[self.earthquakeList removeAllObjects];
[self.tableView endUpdates];
//[self.tableView reloadData] ;
}
-(void)segmentedControlHasChangedValue{
int product;
product=fuelType.selectedSegmentIndex;
switch (product) {
case 0:
productName=1;
[locationManager startUpdatingLocation];
[self clearData];
break;
case 1:
productName=2;
[self clearData];
[locationManager startUpdatingLocation];
break;
case 2:
productName=4;
[self clearData];
[locationManager startUpdatingLocation];
break;
case 3:
prod![enter image description here][1]uctName=5;
[self clearData];
[locationManager startUpdatingLocation];
break;
}
NSLog(#"%d",productName);
return;
}
#end
Try removing all previous object from the self.earthquakeList before adding new 1. use [self.earthquakeList removeAllObjects]
Remove this Line,
[self.tableView insertRowsAtIndexPaths:indexPaths withRowAnimation:UITableViewRowAnimationAutomatic];
And uncomment,
[self.tableView reloadData];
You are Already updating the data set, So you just need to reload the tableView instead of explicitly insert row.