后台任务未运行

时间:2013-06-10 17:48:50

标签: ios background-process

我试图在用户退出应用后运行一些后台任务。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    if ([[UIDevice currentDevice] respondsToSelector:@selector(isMultitaskingSupported)]) { //Check if our iOS version supports multitasking I.E iOS 4
        if ([[UIDevice currentDevice] isMultitaskingSupported]) { //Check if device supports mulitasking
            UIApplication *application = [UIApplication sharedApplication]; //Get the shared application instance
            __block UIBackgroundTaskIdentifier background_task; //Create a task object
            background_task = [application beginBackgroundTaskWithExpirationHandler: ^ {
                [application endBackgroundTask: background_task]; //Tell the system that we are done with the tasks
                background_task = UIBackgroundTaskInvalid; //Set the task to be invalid
                //System will be shutting down the app at any point in time now
            }];
            //Background tasks require you to use asyncrous tasks
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                //Perform your tasks that your application requires
                NSLOG(@"test1");
                [self performSelector:@selector(checkActivityCount) withObject:nil afterDelay:3];
                [application endBackgroundTask: background_task]; //End the task so the system knows that you are done with what you need to perform
                background_task = UIBackgroundTaskInvalid; //Invalidate the background_task
            });
        }
    }
}


-(void)checkActivityCount{
    NSLog(@"test");
    NSString *urlstring = @"https://exampleapp.com/api/v1/postactivity/?unreadfeedcount=yes";
    NSURL *url = [NSURL URLWithString:urlstring];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
        BOOL success = [[JSON objectForKey:@"success"] boolValue];
        if (success) {
            if (![JSON[@"unread_activity_count"] isEqualToString:@"0"]) {
                // Schedule the notification
                UILocalNotification* localNotification = [[UILocalNotification alloc] init];
                localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:2];
                localNotification.alertBody = [NSString stringWithFormat:@"You have %@ unread activities.",JSON[@"unread_activity_count"]];
                localNotification.alertAction = @"Show me the item";
                localNotification.timeZone = [NSTimeZone defaultTimeZone];
                localNotification.applicationIconBadgeNumber = [[UIApplication sharedApplication] applicationIconBadgeNumber] + 1;

                [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];

                // Request to reload table view data
                [[NSNotificationCenter defaultCenter] postNotificationName:@"reloadData" object:self];
            }
        }
    } failure:nil];
    [operationQueue addOperation:operation];

    [self performSelector:@selector(checkActivityCount) withObject:nil afterDelay:3000];

}

现在test1被记录,但测试从未记录。我在代码中做错了吗?

1 个答案:

答案 0 :(得分:1)

使用performSelector:withObject:afterDelay:将请求推送到线程的队列中。它不等待它。所以在你这样做之后立即(即使某些东西会在3秒内从队列中选择项目),你告诉应用程序后台任务已经完成,应用程序也会关闭。

我没有试过像这样暂停,但尝试更像:

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    [self checkActivityCount];
    [application endBackgroundTask: background_task];
    background_task = UIBackgroundTaskInvalid;
});