前段時(shí)間,公司項(xiàng)目有個(gè)需求要求實(shí)現(xiàn)任務(wù)倒計(jì)時(shí),頭疼死我了,折騰了我老半天,先看最終的實(shí)現(xiàn)效果,如下圖。當(dāng)時(shí)的需求有兩點(diǎn)要求:1、要求在當(dāng)前任務(wù)關(guān)卡實(shí)現(xiàn)倒計(jì)時(shí)計(jì)算;2、要求在彈出來(lái)的tips頁(yè)面同時(shí)也進(jìn)行倒計(jì)時(shí)。
一想到倒計(jì)時(shí),我們可能想到的解決方案有三種;1、NStimer,2、GCD,3、NSOperation。
1、NSTimer實(shí)現(xiàn)倒計(jì)時(shí)
NSTimer實(shí)現(xiàn)計(jì)時(shí)需要注意,他默認(rèn)是在runloop中的NSDefaultRunLoopMode
計(jì)時(shí),在這個(gè)模式下面,有滑動(dòng)事件,計(jì)時(shí)將失效,此時(shí)我們需要在將timer添加到runloop中的NSRunLoopCommonModes
,這樣就不會(huì)有任何影響
let animationTimer = NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: #selector(WeeklyMissionViewController.runanimation), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(animationTimer!, forMode: NSRunLoopCommonModes)
animationTimer!.fire()
2、GCD實(shí)現(xiàn)倒計(jì)時(shí)
GCD實(shí)現(xiàn)計(jì)時(shí)需要注意的是let _timer: dispatch_source_t
必須存儲(chǔ)為全局變量timer = _timer
private func setGCDTimer(weeklyMission: MissionList, type: Int) {
// 計(jì)算倒計(jì)時(shí)
let nowDate = NSDate()
let nowUnix = nowDate.timeIntervalSince1970
let count = (weeklyMission.createdAt)! + 24 * 3600 - Int(nowUnix)
var _timeout: Int = count
let _queue: dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let _timer: dispatch_source_t = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, _queue)
timer = _timer
// 每秒執(zhí)行
dispatch_source_set_timer(_timer, dispatch_walltime(nil, 0), 1 * NSEC_PER_SEC, 0)
printLog("----_timer-----")
dispatch_source_set_event_handler(_timer) { () -> Void in
if _timeout <= 0 {
// 倒計(jì)時(shí)結(jié)束
dispatch_source_cancel(_timer)
dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
// 如需更新UI 代碼請(qǐng)寫在這里
})
} else {
print("cell:\(weeklyMission.mission)---\(_timeout)")
_timeout -= 1
let hours = _timeout / 3600
let hoursSec = hours * 3600
let minutes = (_timeout - hoursSec) / 60
let seconds = _timeout - hoursSec - minutes * 60
dispatch_async(dispatch_get_main_queue(), { [unowned self] in
let timeText = "\(String(format: "%.2d",hours)):\(String(format: "%.2d",minutes)):\(String(format: "%.2d",seconds))"
// 如需更新UI 代碼請(qǐng)寫在這里
})
}
}
dispatch_resume(_timer)
}
3、NSOperation實(shí)現(xiàn)倒計(jì)時(shí)
以上兩種實(shí)現(xiàn)的計(jì)時(shí),有個(gè)很明顯的缺點(diǎn)就是,不可控!他們二者開(kāi)啟一個(gè)計(jì)時(shí)器之后,沒(méi)法方便的控制他停止,繼續(xù);但是NSOperation不同,他有cancel方法,我們可以拿到對(duì)應(yīng)的operation,然后操作他,可控性好。
主要代碼如下:
//
// TimeCountDownManager.swift
// leapParent
//
// Created by romance on 16/9/19.
// Copyright ? 2016年 Firstleap. All rights reserved.
//
import UIKit
/// 計(jì)時(shí)中回調(diào)
typealias TimeCountingDownTaskBlock = (timeInterval: NSTimeInterval) -> Void
// 計(jì)時(shí)結(jié)束后回調(diào)
typealias TimeFinishedBlock = (timeInterval: NSTimeInterval) -> Void
private var shareInstance = TimeCountDownManager()
final class TimeCountDownManager: NSObject {
// 單利
class var sharedInstance : TimeCountDownManager {
return shareInstance
}
var pool: NSOperationQueue
override init() {
pool = NSOperationQueue()
super.init()
}
/**
* 開(kāi)始倒計(jì)時(shí),如果倒計(jì)時(shí)管理器里具有相同的key,則直接開(kāi)始回調(diào)。
*
* @param Key 任務(wù)key,用于標(biāo)示唯一性
* @param timeInterval 倒計(jì)時(shí)總時(shí)間,
* @param countingDown 倒計(jì)時(shí)時(shí),會(huì)多次回調(diào),提供當(dāng)前秒數(shù)
* @param finished 倒計(jì)時(shí)結(jié)束時(shí)調(diào)用,提供當(dāng)前秒數(shù),值恒為 0
*/
func scheduledCountDownWith(key: String, timeInteval: NSTimeInterval, countingDown:TimeCountingDownTaskBlock?,finished:TimeCountingDownTaskBlock?) {
var task: TimeCountDownTask?
if coundownTaskExistWith(key, task: &task) {
task?.countingDownBlcok = countingDown
task?.finishedBlcok = finished
if countingDown != nil {
countingDown!(timeInterval: (task?.leftTimeInterval) ?? 60)
}
} else {
task = TimeCountDownTask()
task?.leftTimeInterval = timeInteval
task?.countingDownBlcok = countingDown
task?.finishedBlcok = finished
task?.name = key
pool.addOperation(task!)
}
}
/**
* 查詢倒計(jì)時(shí)任務(wù)是否存在
*
* @param akey 任務(wù)key
* @param task 任務(wù)
* @return YES - 存在, NO - 不存在
*/
func coundownTaskExistWith(key: String,inout task: TimeCountDownTask? ) -> Bool {
var taskExits = false
for (_, obj) in pool.operations.enumerate() {
let temptask = obj as! TimeCountDownTask
if temptask.name == key {
task = temptask
taskExits = true
// print("coundownTaskExistWith#####\(temptask.leftTimeInterval)")
break
}
}
return taskExits
}
/**
* 取消所有倒計(jì)時(shí)任務(wù)
*/
func cancelAllTask() {
pool.cancelAllOperations()
}
/**
* 掛起所有倒計(jì)時(shí)任務(wù)
*/
private func suspendAllTask() {
pool.suspended = true
}
}
final class TimeCountDownTask: NSOperation {
var leftTimeInterval: NSTimeInterval = 0
var countingDownBlcok: TimeCountingDownTaskBlock?
var finishedBlcok: TimeFinishedBlock?
override func main() {
if self.cancelled {
return
}
while leftTimeInterval > 0 {
print("leftTimeInterval----\(leftTimeInterval)")
if self.cancelled {
return
}
leftTimeInterval -= 1
dispatch_async(dispatch_get_main_queue(), {
if self.countingDownBlcok != nil {
self.countingDownBlcok!(timeInterval: self.leftTimeInterval)
}
})
NSThread.sleepForTimeInterval(1)
}
dispatch_async(dispatch_get_main_queue()) {
if self.cancelled {
return
}
if self.finishedBlcok != nil {
self.finishedBlcok!(timeInterval: 0)
}
}
}
}
稍微解析下以上代碼,TimeCountDownManager
是定時(shí)器管理類,是個(gè)單利,可以管理app中所有需要倒計(jì)時(shí)的task,TimeCountDownTask
是具體的用來(lái)處理倒計(jì)時(shí)的NSOperation子類,大家還可以在我的基礎(chǔ)上進(jìn)行完善,比如cancel具體taskIdentifier的task,suspended具體的task,等等!
整個(gè)demo代碼的GitHub地址,希望對(duì)大家有用,喜歡的希望大家點(diǎn)贊,評(píng)論,轉(zhuǎn)發(fā),關(guān)注我啊!讓文章下面的??點(diǎn)亮哦!