代码之家  ›  专栏  ›  技术社区  ›  Zigglzworth

iPhone后台任务在某个点停止运行

  •  2
  • Zigglzworth  · 技术社区  · 14 年前

    在我的iPhone应用程序中,我有一个后台任务,当应用程序进入后台状态时开始运行。

    快跑。

    等。

    以下是后台任务代码:

    - (void)applicationDidEnterBackground:(UIApplication *)application {    
    NSLog(@"Application entered background state.");
    
    if ([[NSUserDefaults standardUserDefaults] boolForKey:@"bgCheckSwitch"] == YES) {
    
        //UIApplication*    app = [UIApplication sharedApplication];
    
    
    
        // Request permission to run in the background. Provide an
    
        // expiration handler in case the task runs long.
    
        NSAssert(bgTask == UIBackgroundTaskInvalid, nil);
    
    
    
        bgTask = [application beginBackgroundTaskWithExpirationHandler:^{
    
            // Synchronize the cleanup call on the main thread in case
    
            // the task actually finishes at around the same time.
    
            dispatch_async(dispatch_get_main_queue(), ^{
    
                if (bgTask != UIBackgroundTaskInvalid)
    
                {
    
                    [application endBackgroundTask:bgTask];
    
                    bgTask = UIBackgroundTaskInvalid;
    
                }
    
            });
    
        }];
    
    
    
        // Start the long-running task and return immediately.
    
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
    
    
            // Do the work associated with the task.
    
            [someClass doSomeThing]; //The actual method performed by the task. The looping is in the method.
    
    
            dispatch_async(dispatch_get_main_queue(), ^{
    
                if (bgTask != UIBackgroundTaskInvalid)
    
                {
    
                    [application endBackgroundTask:bgTask];
    
                    bgTask = UIBackgroundTaskInvalid;
    
                }
    
            });
    
        });
    
    
    }
    
    }
    
    1 回复  |  直到 14 年前
        1
  •  2
  •   jer    14 年前