您的位置:首页 > 其它

GCD实现倒计时且后台运行不影响计数

2016-03-29 15:53 495 查看
利用苹果给出的三种类型的程序可以保持在后台运行:音频播放类AVFoundation 在Build Phases添加依赖库

1、步骤一:在Info.plist中,添加"Required background modes"键,value为:App plays audio
or streams audio/video using AirPlay

2、步骤二:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
NSError *setCategoryErr = nil;
NSError *activationErr  = nil;
[[AVAudioSession sharedInstance]
setCategory: AVAudioSessionCategoryPlayback
error: &setCategoryErr];
[[AVAudioSession sharedInstance]
setActive: YES
error: &activationErr];
self.window.backgroundColor = [UIColor whiteColor];
[self.window makeKeyAndVisible];
return YES;
}


3、步骤三:将以下代码添加到appDelegate文件中的- (void)applicationDidEnterBackground:(UIApplication *)application函数,也可添加到在具体类中注册的应用进入后台后的通知方法

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

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;
}
});
});
}


完成以上步骤你会发现,程序进入后台后仍可运行定时器!

附带GCD实现倒计时方法:

__block NSInteger timeout = totalTimeInterval;

// 拿到一个队列

dispatch_queue_t queue =
dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,
0);

// 创建一个_timer放到队列里

_timer =
dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,
0, 0, queue);

// 设置_timer的首次执行时间、执行时间间隔、精确度

dispatch_source_set_timer(_timer,
dispatch_walltime(NULL,
0),
1.0 * NSEC_PER_SEC,
0);

// 设置_timer执行的事件

typeof(self)
__weak wself = self;

dispatch_source_set_event_handler(_timer, ^{

if (timeout <=
0) {

// 倒计时结束,取消_timer

dispatch_source_cancel(_timer);

dispatch_async(dispatch_get_main_queue(), ^{

// 重置ItemContainer

if (_infiniteLoop) {

[wself setInfiniteCycleFromCurrentTime];

}

else {

[wself reloadItemsWithTimes:nil];

}

// 调用代理事件

if ([wself.delegate respondsToSelector:@selector(RBCountDownViewDidStopCounting:)]) {

[wself.delegate RBCountDownViewDidStopCounting:wself];

}

});

}

else {

// 计算显示时间数组

NSArray *times = [wself
calculateTimesWithTotalTimeInterval:timeout];

dispatch_async(dispatch_get_main_queue(), ^{

[wself reloadItemsWithTimes:times];

});

timeout--;

}

});

// 激活_timer

dispatch_resume(_timer);

参考文章:
http://blog.csdn.net/u013009873/article/details/50979415 http://jingyan.baidu.com/article/d8072ac47d3c00ec94cefd5b.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: