如何在iOS應用程序中每n分鐘更新一次背景位置?我正在尋找一種方法,以獲得一個背景位置更新每n分鐘在我的iOS應用程序。我使用的是iOS 4.3,這個解決方案應該適用于非越獄iPhone。我嘗試/考慮了以下選擇:CLLocationManager startUpdatingLocation/startMonitoringSignificantLocationChanges:根據配置的屬性在后臺按預期工作,但似乎不可能強迫它每n分鐘更新一次位置。NSTimer:應用程序在前臺運行時是否工作,但似乎不是為后臺任務設計的本地通知:本地通知可以每n分鐘調度一次,但是不可能執行一些代碼來獲得當前位置(用戶不必通過通知啟動應用程序)。這種方法似乎也不是一種干凈的方法,因為這不是應該使用的通知。UIApplication:beginBackgroundTaskWithExpirationHandler據我所知,當一個應用程序被移到后臺而不是實現“長期運行”后臺進程時,應該使用它來完成背景中的一些工作(也是有限的時間)。如何實現這些定期的背景位置更新?
3 回答
隔江千里
TA貢獻1906條經驗 獲得超10個贊
指定 location background mode創建一個 NSTimer在背景中 UIApplication:beginBackgroundTaskWithExpirationHandler:什么時候 n是 較小
比 UIApplication:backgroundTimeRemaining一切都會好起來的。什么時候 n是 更大
, location manager在沒有時間避免后臺任務被殺死之前,應該再次啟用(并禁用)。
這是因為位置是允許的三種背景執行類型之一。.
注意:我浪費了一些時間在模擬器中測試它不起作用。然而,它在我的手機上工作得很好。
慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
轉到Project->Capability->后臺模式->選擇位置更新 轉到Project->Info->添加一個鍵NSLocationAlwaysUsageDescription和空值(或者任意文本) 要使位置在后臺工作,并將坐標發送到Web服務或每5分鐘對它們執行任何操作,請按照下面的代碼執行。
@interface LocationManager () <CLLocationManagerDelegate>@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;@end@implementation LocationManager+ (instancetype)sharedInstance{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
LocationManager *instance = sharedInstance;
instance.locationManager = [CLLocationManager new];
instance.locationManager.delegate = instance;
instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
// you can use kCLLocationAccuracyHundredMeters to get better battery life
instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
});
return sharedInstance;}- (void)startUpdatingLocation{
CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
if (status == kCLAuthorizationStatusDenied)
{
NSLog(@"Location services are disabled in settings.");
}
else
{
// for iOS 8
if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
{
[self.locationManager requestAlwaysAuthorization];
}
// for iOS 9
if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
{
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
}
[self.locationManager startUpdatingLocation];
}}- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
CLLocation *mostRecentLocation = locations.lastObject;
NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));
NSDate *now = [NSDate date];
NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;
if (!self.lastTimestamp || interval >= 5 * 60)
{
self.lastTimestamp = now;
NSLog(@"Sending current location to web service.");
}}@end- 3 回答
- 0 關注
- 631 瀏覽
添加回答
舉報
0/150
提交
取消
