我想在应用程序处于后台时发送用户位置。在应用程序中,用户可以设置一个计时器,从 1 分钟到 24 小时。我试图让应用程序在后台运行,它只运行了十分钟。如果我将计时器设置为超过十分钟,然后将应用程序后台运行,该应用程序不会在后台运行超过十分钟。是否可以让应用程序运行超过十分钟?最多至少两个小时?
这是我尝试过的:
我将此添加到我的 plist 中:
我将此添加到我的applicationDidEnterBackground:
方法中:
__weak BADAppDelegate * weakSelf = self;
self.backgroundTaskIdentifier =
[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
int timeTilDone = timerSeconds;// two hours
self.bgTimer =
[NSTimer timerWithTimeInterval:timeTilDone
target:weakSelf
selector:@selector(startTrackLocation)
userInfo:nil
repeats:NO];
[[NSRunLoop mainRunLoop] addTimer:self.bgTimer
forMode:NSDefaultRunLoopMode];
self.testTimer =
[NSTimer timerWithTimeInterval:60
target:weakSelf
selector:@selector(playSilentSound)
userInfo:nil
repeats:YES];
[[NSRunLoop mainRunLoop] addTimer:self.testTimer
forMode:NSDefaultRunLoopMode];
});
我试图通过每分钟播放一个声音来强迫它活着
-(void)playSilentSound
{
if(self.silentSnd == nil)
{
NSString *soundFile;
if ((soundFile = [[NSBundle mainBundle] pathForResource:@"halfsec" ofType:@"caf"]))
{
NSURL *url = [[NSURL alloc] initFileURLWithPath:soundFile];
self.silentSnd = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:NULL];
self.silentSnd.delegate = self;
[self.silentSnd setNumberOfLoops:1];
}
}
[self.silentSnd prepareToPlay];
[self.silentSnd play];
}
但这无济于事。
谢谢!
更新:
这是我的 locationManager 初始化代码:
NSLog(@"StartTrackLocation");
if(self.locationManager == nil)
{
self.locationManager = [[CLLocationManager alloc] init];
}
self.locationManager.delegate = self;
self.locationManager.distanceFilter = kCLDistanceFilterNone;
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
self.locationManager.pausesLocationUpdatesAutomatically = NO;
[self.locationManager startUpdatingLocation];