我如何每20秒写入文件

时间:2014-11-25 10:12:09

标签: objective-c

我如何让这段代码每20秒写一次纬度/经度?谢谢。

// Save the longitude & latitude to file & check for errors
NSString *newLocString = [NSString stringWithFormat:@"%s%f\n%s%f","Lat=",currentLocation.coordinate.latitude,"Long=",currentLocation.coordinate.longitude];

NSString *path = @"var/Coordinates/myLocation.txt";
NSError *error = nil;

BOOL success = [newLocString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSString *status = success ? @"Success" : @"Failure";
if(success){

    UIAlertView *savedAlert = [[UIAlertView alloc] initWithTitle:@"Success!"message:@"The myLocation.txt file was updated." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [savedAlert show];

    NSLog(@"Done Writing: %@",status);
}
else{
    NSLog(@"Done Writing: %@",status);
    NSLog(@"Error: %@",[error localizedDescription]);
}

1 个答案:

答案 0 :(得分:3)

使用每20秒触发一次的NSTimer

NSTimer *timer = [NSTimer timerWithTimeInterval:20
                                         target:self
                                       selector:@selector( yourFunctionThatWritesToFile )
                                       userInfo:nil
                                        repeats:YES];
[timer fire];