0

How can I add a UIAlertView that will appear only if successfully saving my coordinates to the text file, thanks so much.

I just updated the post with all the code & wonder if you can see why it is showing the alert view twice.

Thanks.

#import "ViewController.h"


@interface ViewController ()
@end

@implementation ViewController {
CLLocationManager *locationManager;
}

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
locationManager = [[CLLocationManager alloc] init];
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

- (IBAction)getCurrentLocation:(id)sender {
locationManager.delegate = (id)self;
locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}

#pragma mark - CLLocationManagerDelegate

- (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
{
NSLog(@"Location updated: %@", newLocation);
CLLocation *currentLocation = newLocation;

if (currentLocation != nil) {
    _LatitudeLabel.text = [NSString stringWithFormat:@"%.8f", currentLocation.coordinate.latitude];
    _LongitudeLabel.text = [NSString stringWithFormat:@"%.6f", currentLocation.coordinate.longitude];
    _GPSAccuracyLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.horizontalAccuracy];
    _AltitudeLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.altitude];
    _VerticalAccuracyLabel.text = [NSString stringWithFormat:@"%.2f", currentLocation.verticalAccuracy];
}

NSString *newLocString = [NSString stringWithFormat:@"%s%f\n%s%f","Lat=",currentLocation.coordinate.latitude,"Long=",currentLocation.coordinate.longitude];
NSString *path = @"var/mobile/Documents/location.txt";
NSError *error = nil;
// Save string and check for error
if (![newLocString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]) {
    NSLog(@"An Error occurred: %@", error.localizedDescription);
} else {
    UIAlertView *savedAlert = [[UIAlertView alloc] initWithTitle:@"File saved"message:@"File saved successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [savedAlert show];
}

/* IOS8

 else {
 // Create the alert itself
 UIAlertController *savedAlert = [UIAlertController alertControllerWithTitle:@"File saved" message:@"File saved successfully" preferredStyle:UIAlertControllerStyleAlert];

 // Create the "OK" button 'Action'
 UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {}];

 // Add the 'Action' created above, to our alert (otherwise, we won't have any button in it)
 [savedAlert addAction:defaultAction];

 // Presents the alert
 [self presentViewController:savedAlert animated:YES completion:nil];
 }

 ======================================

 FOR IOS 7

 else {
 UIAlertView *savedAlert = [[UIAlertView alloc] initWithTitle:@"File saved"message:@"File saved successfully" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
 [savedAlert show];
 }
 */

// Stop Location Manager
[locationManager stopUpdatingLocation];
}

@end
Nicoll
  • 257
  • 1
  • 5
  • 16

1 Answers1

1

You already have an if statement that checks if there was error when trying to save the file.
Just add an else statement, meaning the file saved successfully, that shows the UIAlertView

Change your code to the following:

EDIT- Since UIAlertView is deprecated in iOS 8, I've modified the code so it'll work both on iOS 8 and on prior versions.

// Save string and check for error  
if (![newLocString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error]) {  
    NSLog(@"An Error occurred: %@", error.localizedDescription);  
} else {  

    // Here we are receiving a string which holds the iOS version
    NSString *iOSversion = [[UIDevice currentDevice] systemVersion];  

    // Here we are comparing the above string, to the string "7.2"  
    // Since both are string, and not numbers, we are using the option 'NSNumericSearch'  
    // I've randomly chosen version 7.2, since iOS 7 latest version is 7.1.2,  
    // Every version number below 7.2 will be prior to iOS 8, and above 7.2 will be iOS 8  
    // If I would've chosen the latest iOS 7 version, which is 7.1.2, or the first iOS 8 version  
    // which is 8.0, I would have needed to add code which my comparison results will be NSOrderedSame  
    // Note that the comparison just gives me the order in which the below items will be, compared to one another
    if([iOSversion compare:@"7.2" options:NSNumericSearch] == NSOrderedAscending) {
        UIAlertView *savedAlert = [[UIAlertView alloc] initWithTitle:@"File saved"  
                                                             message:@"File saved successfully"  
                                                             delegate:nil  
                                                    cancelButtonTitle:@"OK"  
                                                    otherButtonTitles:nil];  
        [savedAlert show];  
    } else {
        // Create the alert itself
        UIAlertController *savedAlert = [UIAlertController alertControllerWithTitle:@"File saved"  
                                                                            message:@"File saved successfully"  
                                                                     preferredStyle:UIAlertControllerStyleAlert];

        // Create the "OK" button 'Action'
        UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"OK"  
                                                                style:UIAlertActionStyleDefault  
                                                              handler:^(UIAlertAction * action) {}];

        // Add the 'Action' created above, to our alert (otherwise, we won't have any button in it)  
        [savedAlert addAction:defaultAction];

        // Presents the alert
        [self presentViewController:savedAlert animated:YES completion:nil];  
    }
}
AMI289
  • 1,098
  • 9
  • 10
  • Thanks, I did something like this but like mine I get 2 alerts so have to press "OK" twice. What do we use for IOS8? – Nicoll Nov 22 '14 at 13:01
  • You use `UIAlertController`, I'll edit my code in a second to also include implementation of `UIAlertController`. – AMI289 Nov 22 '14 at 13:06
  • Thanks so much for your help! So I have to make 2 versions IOS7 & IOS8 or will UIAlertController work in IOS7? Any idea why the alert is coming up twice? Oh maybe it's once for longitude & once for latitude, would you know how to fix this? Thanks again. – Nicoll Nov 22 '14 at 13:11
  • Hmmm...can you put a breakpoint to make sure the whole 'didUpdateToLocationFromLocation' don't get called twice? I believe that the second example would crash on iOS 7. the first example would still work on iOS 8, but deprecated means that Apple has stopped supporting it, and in it is very possible that in future iOS releases it won't work at all. you could use some `if` statement to check for device iOS version, and run the appropriate code. – AMI289 Nov 22 '14 at 13:25
  • http://stackoverflow.com/questions/3339722/how-to-check-ios-version this would help. – AMI289 Nov 22 '14 at 13:26
  • Yes your right, crashes IOS7, don't know about breakpoints yet but will learn. Thanks for you help M8. – Nicoll Nov 22 '14 at 13:33
  • I'll update the code in a sec so it'll be suitable for both iOS version. Breakpoints is when you click on the grey line on the left of where you write the code, and it puts like a little blue arrow. then, at runtime, when the executed code gets to the point you've set a breakpoint in, it pauses, and you can manually run it line by line. if a method gets called multiple times, your app will stop multiple times at that point (sorry for my bad english...). – AMI289 Nov 22 '14 at 13:41
  • Wow, so helpful friend, looking forward to see how you re-code it ;) Thank you so much for your time. I see in the debug area of Xcode it is indeed getting called twice! Oh boy! – Nicoll Nov 22 '14 at 13:45
  • I added the whole code to original post, maybe you can see why it's showing alert twice? – Nicoll Nov 22 '14 at 13:57
  • Your new code works great! Only thing now is the update getting called twice. THANK YOU! – Nicoll Nov 22 '14 at 14:18
  • Awesome...I'll try to have a look on the double call later. :-) – AMI289 Nov 22 '14 at 16:03
  • Thanks pal, I just posted the question here: http://stackoverflow.com/questions/27079216/why-is-this-code-updating-location-twice-every-time – Nicoll Nov 22 '14 at 16:17