前段時間弃衍,公司項目有個需求要求實現(xiàn)任務(wù)倒計時,頭疼死我了坚俗,折騰了我老半天镜盯,先看最終的實現(xiàn)效果,如下圖猖败。當(dāng)時的需求有兩點要求:1速缆、要求在當(dāng)前任務(wù)關(guān)卡實現(xiàn)倒計時計算;2恩闻、要求在彈出來的tips頁面同時也進行倒計時艺糜。
一想到倒計時,我們可能想到的解決方案有三種幢尚;1破停、NStimer,2侠草、GCD辱挥,3、NSOperation边涕。
1晤碘、NSTimer實現(xiàn)倒計時
NSTimer實現(xiàn)計時需要注意,他默認(rèn)是在runloop中的NSDefaultRunLoopMode
計時功蜓,在這個模式下面园爷,有滑動事件,計時將失效式撼,此時我們需要在將timer添加到runloop中的NSRunLoopCommonModes
,這樣就不會有任何影響
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實現(xiàn)倒計時
GCD實現(xiàn)計時需要注意的是let _timer: dispatch_source_t
必須存儲為全局變量timer = _timer
private func setGCDTimer(weeklyMission: MissionList, type: Int) {
// 計算倒計時
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 {
// 倒計時結(jié)束
dispatch_source_cancel(_timer)
dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
// 如需更新UI 代碼請寫在這里
})
} 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 代碼請寫在這里
})
}
}
dispatch_resume(_timer)
}
3、NSOperation實現(xiàn)倒計時
以上兩種實現(xiàn)的計時著隆,有個很明顯的缺點就是扰楼,不可控!他們二者開啟一個計時器之后美浦,沒法方便的控制他停止弦赖,繼續(xù);但是NSOperation不同浦辨,他有cancel方法蹬竖,我們可以拿到對應(yīng)的operation,然后操作他,可控性好币厕。
主要代碼如下:
//
// TimeCountDownManager.swift
// leapParent
//
// Created by romance on 16/9/19.
// Copyright ? 2016年 Firstleap. All rights reserved.
//
import UIKit
/// 計時中回調(diào)
typealias TimeCountingDownTaskBlock = (timeInterval: NSTimeInterval) -> Void
// 計時結(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()
}
/**
* 開始倒計時列另,如果倒計時管理器里具有相同的key,則直接開始回調(diào)旦装。
*
* @param Key 任務(wù)key页衙,用于標(biāo)示唯一性
* @param timeInterval 倒計時總時間,
* @param countingDown 倒計時時同辣,會多次回調(diào)拷姿,提供當(dāng)前秒數(shù)
* @param finished 倒計時結(jié)束時調(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!)
}
}
/**
* 查詢倒計時任務(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
}
/**
* 取消所有倒計時任務(wù)
*/
func cancelAllTask() {
pool.cancelAllOperations()
}
/**
* 掛起所有倒計時任務(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
是定時器管理類棒妨,是個單利踪古,可以管理app中所有需要倒計時的task,TimeCountDownTask
是具體的用來處理倒計時的NSOperation子類券腔,大家還可以在我的基礎(chǔ)上進行完善伏穆,比如cancel具體taskIdentifier的task,suspended具體的task纷纫,等等枕扫!
整個demo代碼的GitHub地址,希望對大家有用辱魁,喜歡的希望大家點贊烟瞧,評論,轉(zhuǎn)發(fā)染簇,關(guān)注我安蔚巍!讓文章下面的??點亮哦锻弓!