美文网首页
NStimer 后台挂起

NStimer 后台挂起

作者: Mickey__chen | 来源:发表于2018-04-30 18:51 被阅读0次

    iOS为了让设备尽量省电,减少不必要的开销,保持系统流畅,因而对后台机制采用墓碑式的“假后台”。除了系统官方极少数程序可以真后台,一般开发者开发出来的应用程序后台受到以下限制:

    1.用户按Home之后,App转入后台进行运行,此时拥有180s后台时间(iOS7)或者600s(iOS6)运行时间可以处理后台操作

    2.当180S或者600S时间过去之后,可以告知系统未完成任务,需要申请继续完成,系统批准申请之后,可以继续运行,但总时间不会超过10分钟。

    3.当10分钟时间到之后,无论怎么向系统申请继续后台,系统会强制挂起App,挂起所有后台操作、线程,直到用户再次点击App之后才会继续运行。

    项目中我们需要定时器在后台持续运行一段时间,以保证我们的app正确运行,我们需要如下步骤

    步骤一:

    将plist文件中加入Required background modes 

    App registers for location updates 

    步骤二:

    - (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.

        UIApplication*  app = [UIApplication sharedApplication];

        __block    UIBackgroundTaskIdentifier bgTask;

        bgTask = [app beginBackgroundTaskWithExpirationHandler:^{

            dispatch_async(dispatch_get_main_queue(), ^{

                if (bgTask != UIBackgroundTaskInvalid)

                {

                    bgTask = UIBackgroundTaskInvalid;

                }

            });

        }];

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            dispatch_async(dispatch_get_main_queue(), ^{

                if (bgTask != UIBackgroundTaskInvalid)

                {

                    bgTask = UIBackgroundTaskInvalid;

                }

            });

        });

    }

    相关文章

      网友评论

          本文标题:NStimer 后台挂起

          本文链接:https://www.haomeiwen.com/subject/kictrftx.html