看起来这个问题好像被问了好几次,但我面临一个奇怪的问题。
我已将服务器配置为使用content-available = 1
标志发送推送通知。
我已将我的应用配置为Background Modes
,Location Update
和Background fetch
的后台Remote Notifications
。
此外,我已经实现了所有必要的代码,以便在后台接收推送通知并启动后台任务。
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
__block UIBackgroundTaskIdentifier bg_task = background_task;
background_task = [application beginBackgroundTaskWithExpirationHandler:^ {
//Clean up code. Tell the system that we are done.
[application endBackgroundTask: bg_task];
bg_task = UIBackgroundTaskInvalid;
}];
//### background task starts
[self updateLocationToServer];
//#### background task ends
completionHandler(UIBackgroundFetchResultNewData);
}
- (void)updateLocationToServer{
[locationManager updateLocationWithCompletionHandler:^(CLLocation *location, NSError *error, BOOL locationServicesDisabled) {
if (error)
{
// Handle error here
if (locationServicesDisabled) {
// Location services are disabled, you can ask the user to enable them for example
}
}
else
{
// Do whatever you want with the current user's location
NSString *deviceID = [userDefs objectForKey:@"deviceID"];
isConnected = [[userDefs objectForKey:@"connected"] boolValue];
if (isConnected) {
if (deviceID) {
[self sendLocation:deviceID];
}
}
localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [NSDate dateWithTimeIntervalSinceNow:0.1];
localNotif.timeZone = [NSTimeZone defaultTimeZone];
localNotif.alertBody = [NSString stringWithFormat:@"Lat: %@ Long:%@",[NSNumber numberWithFloat:location.coordinate.latitude],[NSNumber numberWithFloat:location.coordinate.longitude]];
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
NSLog(@"Lat: %@ Long:%@",[NSNumber numberWithFloat:location.coordinate.latitude],[NSNumber numberWithFloat:location.coordinate.longitude]);
//Clean up code. Tell the system that we are done.
[[UIApplication sharedApplication] endBackgroundTask: background_task];
background_task = UIBackgroundTaskInvalid;}}];}
编辑:添加了我结束后台任务的代码。 background_task变量是全局的。
该应用程序正常接收后台推送,直到它进入暂停模式。问题是,在后台任务结束后,应用程序进入挂起模式时,它会在收到推送通知时再次运行代码,但不会调用didReceiveRemoteNotification: fetchCompletionHandler:
。但是当我打开应用程序并退出主页按钮时,它会在“那个”3分钟内再次运行,直到它进入暂停模式。