ios开发教程之申请更多后台时间

  在ios应用及游戏开发过程中,我们很多时候需要在用户切换到后台工作的时候做一些操作,例如清除内存或者保存用户数据之类的。这些操作一般都在

AppDelagate的applicationDidEnterBackground:(UIApplication *)application中进行(当然我们也可以通过接收应用程序发送的通知UIApplicationDidEnterBackgroundNotification来触发处理)。但是这些工作系统只给我们分配了5秒的时间去处理,否则系统将会将应用强制退出。所以在很多时候我们需要申请更多的时间来处理相关后台操作。

  现在我们就来看一下如何申请更多的后台时间.代码如下

- (void)applicationDidEnterBackground:(UIApplication *)application

{

    UIApplication *app=[UIApplicationsharedApplication];

    //一个后台任务标识符 

    __blockUIBackgroundTaskIdentifier taskId;

//    申请后台运行更多时间  

    taskId=[app beginBackgroundTaskWithExpirationHandler:^(void){

//      超出系统延长的时间执行

        NSLog(@"Background task ran out of time and was termined.");

        [app endBackgroundTask:taskId];

    }];

//    申请失败  

    if(taskId==UIBackgroundTaskInvalid){

        NSLog(@"Fail to start background task!");

        return;

    }

    NSLog(@"Starting background task with %f seconds remaining",app.backgroundTimeRemaining);

    while (true) {

    [NSThreadsleepForTimeInterval:1];

    NSLog(@"小丁在后台");

    }

}

我想代码已经注释的很清楚了 ,运行代码我们会发现,系统给我们延长的时间接近于600s。当然这对我们清理内存和保存用户信息来说已经足够了。

 

posted @ 2013-01-06 14:25  丁昌兴  阅读(1095)  评论(0编辑  收藏  举报