GCD使用:让程序在后台较长久的运行(UIBackgroundTaskIdentifier )

在没有使用GCD时,当app被按home键退出后,app仅有最多5秒钟的时候做一些保存或清理资源的工作。但是在使用GCD后,app最多有10分钟的时间在后台长久运行。这个时间可以用来做清理本地缓存,发送统计数据等工作。

Declaration

SWIFT

typealias UIBackgroundTaskIdentifier = Int

OBJECTIVE-C

typedef NSUInteger UIBackgroundTaskIdentifier;

Import Statement

OBJECTIVE-C

@import UIKit;

SWIFT

import UIKit

Availability

Available in iOS 4.0 and later.


代码例子:

- (void)applicationDidEnterBackground:(UIApplication *)application {



__block UIBackgroundTaskIdentifier bgTask;



bgTask
= [application 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(),
^{

NSLog(
@"555555");



});



});

}

代码例子:

后台播放音乐

+ (UIBackgroundTaskIdentifier)backgroundPlayerID:(UIBackgroundTaskIdentifier)backTaskId

{

    // 1. 设置并激活音频会话类别

       AVAudioSession *session = [AVAudioSession sharedInstance];

    [session AVAudioSessionCategoryPlayback error:nil];

    [session setActive:YES error:nil];

    // 2. 允许应用程序接收远程控制

    [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

    // 3. 设置后台任务ID

      UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;

    newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil];

    if (newTaskId != UIBackgroundTaskInvalid && backTaskId != UIBackgroundTaskInvalid) {

        [[UIApplication sharedApplication] endBackgroundTask:backTaskId];

    }

    return newTaskId;

}


代码例子:
/ AppDelegate.h文件
@property (assign, nonatomic) UIBackgroundTaskIdentifier backgroundUpdateTask;

// AppDelegate.m文件
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self beingBackgroundUpdateTask];
    // 在这里加上你需要长久运行的代码
    [self endBackgroundUpdateTask];
}

- (void)beingBackgroundUpdateTask
{
    self.backgroundUpdateTask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
        [self endBackgroundUpdateTask];
    }];
}

- (void)endBackgroundUpdateTask
{
    [[UIApplication sharedApplication] endBackgroundTask: self.backgroundUpdateTask];
    self.backgroundUpdateTask = UIBackgroundTaskInvalid;
}

 
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值