backgroundTask 未在 iOS 内完成

backgroundTask not finishing in iOS

我有以下代码,它在应用程序即将退出之前调用服务器。我的问题是,代码有时有效,有时无效。大多数情况下不是。这是代码:

//Set the user as in-active if app is force closed
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.

    NSLog(@"called");

    bgTask = [application beginBackgroundTaskWithName:@"setInActive" expirationHandler:^{
        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;

    }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        NSLog(@"disp called");

        //If the app is about to exit make the user inactive
        [[APIManager sharedInstance] setInActiveOnCompletion:^(BOOL finished){
            [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;
        }];

    });

}

每次都会调用第一个 NSLog。但是第二个没有。似乎该应用程序甚至没有进入 dispatch_async 方法。

编辑: 所以基本上我需要做的就是告诉服务器用户已强制退出应用程序,而该用户已登录。我该怎么做?

有什么想法吗?

当您的应用程序在后台时,它只允许进行很少量的处理,因此使用 dispatch_async 不会给您带来太多额外时间。此外,Apple 不希望这样。

applicationWillTerminate 是应用程序终止前调用的最后一个方法!!所以,在那之后你不能做任何事情,如果你想在后台执行某些事情然后在你执行你的操作时开始那个任务,你不能从 background task 开始 applicationWillTerminate 因为你的应用程序不会在此方法调用后处于后台!!