gpt4 book ai didi

ios - 使用 iOS 每 x 分钟发送一次 GPS 坐标 - Core Location 不会停止更新

转载 作者:塔克拉玛干 更新时间:2023-11-02 10:08:50 28 4
gpt4 key购买 nike

我正在尝试大约每 5 分钟向我们的服务器发送一次 GPS 数据信息,无论该应用程序是否正在运行或是否在后台运行。我可以让它运行,但它似乎一直在运行。我设置了一个计时器,每 10 秒发送一次进行测试,但它一直在发送。我不认为这是错误的计时器,我相信 locationManager 没有停止,我不知道为什么。

这是我的代码

- (void)applicationDidEnterBackground:(UIApplication *)application
{

NSLog(@"Went to Background");

UIApplication *app = [UIApplication sharedApplication];

bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
[app endBackgroundTask:bgTask];
bgTask = UIBackgroundTaskInvalid;
}];

[self.locationManager startUpdatingLocation];
self.timer = [NSTimer scheduledTimerWithTimeInterval:10 target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.delegate = self;

[self.locationManager startUpdatingLocation];

[NSTimer scheduledTimerWithTimeInterval:10 target:self.locationManager selector:@selector(startUpdatingLocation) userInfo:nil repeats:YES];
}

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
if (newLocation.horizontalAccuracy <= 100.0f) {
// Use json and send data to server
...
...

[self.locationManager stopUpdatingLocation];
self.locationManager = nil;
self.locationManager.delegate = nil;
}
}

无论在后台还是前台,它都做同样的事情。我还需要做些什么来阻止 locationManager 更新吗?

最佳答案

要定期将位置发送到服务器,您需要存储和比较收到更新的日期,不要使用计时器,因为它们不可靠 when the app is in the background .

@implementation
{
NSDate* _lastSentUpdateAt;
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSLog(@"Went to Background");
// Update in 5 minutes.
_lastSentUpdateAt = [NSDate date];
[self.locationManager startUpdatingLocation];
}
// ...

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{
// Accuracy is good & 5 minutes have passed.
if (newLocation.horizontalAccuracy <= 100.0f && [_lastSentUpdateAt timeIntervalSinceNow] < -5 * 60) {
// Set date to now
_lastSentUpdateAt = [NSDate date];

// Use json and send data to server
...
...
}
}
@end

关于ios - 使用 iOS 每 x 分钟发送一次 GPS 坐标 - Core Location 不会停止更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18828881/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com