0

我的程序通过 GPS 加载用户的当前位置并将其保存在 txt 文件中,以便通过电子邮件发送以用于统计目的。我的问题是:

  • 每次保存位置时,第一次尝试给你 15 秒的延迟:

    [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(locationManager:) userInfo:nil repeats:YES];

问题是这不起作用,也不知道是什么原因。

  • 我的另一个问题是:如果文件太大......为此,我想命名创建日期和每天不同的日期。我尝试了几件事,但我没有得到任何东西。

编码:

-(void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{

//Obtenemos las coordenadas.
latitud = newLocation.coordinate.latitude;
longitud = newLocation.coordinate.longitude;
precision = newLocation.horizontalAccuracy;

// Lo mostramos en las etiquetas
[latitudLabel setText:[NSString stringWithFormat:@"%0.8f",latitud]];
[longitudLabel setText:[NSString stringWithFormat:@"%0.8f",longitud]];
[precisionLabel setText:[NSString stringWithFormat:@"%0.8f",precision]];
tiempoLabel=[self.dateFormatter stringFromDate:newLocation.timestamp];
//NSLog(@"tiempo: %@",tiempoLabel);

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"textfile.txt"];
//[[NSFileManager defaultManager] removeItemAtPath:path error:nil];

// create if needed
if (![[NSFileManager defaultManager] fileExistsAtPath:path]){
    [[NSData data] writeToFile:path atomically:YES];}

NSString *contents = [NSString stringWithFormat:@"tiempo: %@ latitude:%+.6f longitude: %+.6f precisión: %f\n",tiempoLabel,latitud,longitud,precision];

NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:path];
[handle truncateFileAtOffset:[handle seekToEndOfFile]];    
[handle writeData:[contents dataUsingEncoding:NSUTF8StringEncoding]];}        

谢谢您的帮助。StackOverflow 对我的项目帮助很大

4

2 回答 2

1

你提出了两个不同的问题:

  1. 关于你的计时器,你有一个名为的方法locationManager:吗?你还没有展示这种方法,所以它看起来很可疑。如果你试图打电话给你的locationManager:didUpdateToLocation:fromLocation:,那是行不通的。@selectorfor 的参数NSTimer不能超过一个。您可以编写一个简单的计时器处理程序方法来调用您想要的任何方法,例如

    - (void)handleTimer:(NSTimer *)timer
    {
        // call whatever method you want here
    }
    

    然后你可以这样做:

    [NSTimer scheduledTimerWithTimeInterval:15.0 target:self selector:@selector(handleTimer:) userInfo:nil repeats:YES];
    

    请注意,重复计时器可能会导致保留周期,因此如果您计划在某个时候取消它,您可能希望保留对计时器的引用,以便invalidate以后可以使用它(例如 in viewDidDisappear)。

    话虽如此,我同意建议不要每 15 秒写入一次,而是使用desiredAccuracyanddistanceFilter来控制何时调用位置管理器委托方法。每x秒记录一次位置是消耗用户电池的好方法。有关其他电池节省指南,请参阅位置感知编程指南中的节省电池提示。

  2. 关于你的第二个问题,

    • 您不需要执行“根据需要创建”代码;和

    • 编写文件时,您不需要该NSFileHandle代码;您可以只使用NSString实例方法writeToFile:atomically:encoding:error:(顺便说一下,其中包含一个NSError参数,如果文件写入不成功,您可以检查该参数)。

于 2013-07-16T14:32:39.437 回答
0

您可能想放弃计时器并检查一定程度的准确性,这里有一些检查 gps 准确性的示例代码,需要修改或从中取一两行以满足您的需要

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    // test the age of the location measurement to determine if the measurement is cached
    // in most cases you will not want to rely on cached measurements
    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if (locationAge > 5.0) return;

    // test that the horizontal accuracy does not indicate an invalid measurement
    if (newLocation.horizontalAccuracy < 0) return;

    // test the measurement to see if it is more accurate than the previous measurement
    if (bestEffortAtLocation == nil || bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
        // store the location as the "best effort"
        self.bestEffortAtLocation = newLocation;

        // test the measurement to see if it meets the desired accuracy
        //
        // IMPORTANT!!! kCLLocationAccuracyBest should not be used for comparison with location coordinate or altitidue 
        // accuracy because it is a negative value. Instead, compare against some predetermined "real" measure of 
        // acceptable accuracy, or depend on the timeout to stop updating. This sample depends on the timeout.
        //
        if (newLocation.horizontalAccuracy <= locationManager.desiredAccuracy) {
            // we have a measurement that meets our requirements, so we can stop updating the location
            // 
            // IMPORTANT!!! Minimize power usage by stopping the location manager as soon as possible.
            //
            [self stopUpdatingLocation:NSLocalizedString(@"Acquired Location", @"Acquired Location")];

            // we can also cancel our previous performSelector:withObject:afterDelay: - it's no longer necessary
            [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(stopUpdatingLocation:) object:nil];
        }
    }
}

至于带有日期的文件,我被命名问题弄糊涂了,我假设标题的数字格式可以满足您的需求。尽管查看您的代码,您需要将发生的很多事情与您的 didUpdateLocation 方法分开,因为这平均每隔几秒钟就会调用一次,这会产生很多问题,而不会告诉您的程序等待或直到某个时间点才再次更新文件。

于 2013-07-16T14:35:44.560 回答