简体   繁体   English

backgroundTask在iOS中未完成

[英]backgroundTask not finishing in iOS

I have the following code which makes a call to the server, before the app is about to exit. 我有以下代码,该代码将在应用程序即将退出之前调用服务器。 My problem is, that the code sometimes works, sometimes not. 我的问题是,该代码有时有效,有时却无效。 Mostly not. 通常不是。 Here is the code: 这是代码:

//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;
        }];

    });

}

The first NSLog gets called everytime. 每次都会调用第一个NSLog。 However the second one does not. 但是第二个没有。 It seems as if the app does not even go into the dispatch_async method. 似乎该应用程序甚至都没有进入dispatch_async方法。

EDIT: So basically all I need to do is tell the server that a user has force quit the app, while that user was signed in. How could I do this? 编辑:因此,基本上我需要做的就是告诉服务器,该用户已登录时,用户已强制退出该应用程序。我该怎么办?

Any ideas? 有任何想法吗?

When your application is in the background, it is only allowed very little amount of processing, therefore using dispatch_async will not buy you much extra time. 当您的应用程序在后台运行时,只允许进行很少量的处理,因此使用dispatch_async不会为您节省很多时间。 Also, Apple does not want that. 另外, Apple也不想这么做。

applicationWillTerminate is the last method that get called before app is being terminated!! applicationWillTerminate是终止应用程序之前调用的最后一个方法! So, you can't do anything after that, if you want to perform something in background then begin that task when you performing your operation, you can't begin background task from applicationWillTerminate because your app will not be in background after this method call!! 因此,此后您将无法执行任何操作,如果您想在后台执行某项操作,然后在执行操作时开始执行该任务,则无法从applicationWillTerminate开始执行background task ,因为在此方法调用之后,您的应用程序将不会在后台运行!!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM