Чтобы создать таймер обратного отсчета с помощью Swift, вы можете использовать различные методы и подходы. Вот несколько примеров:
Метод 1: DispatchTimer
import Dispatch
func startCountdown(seconds: Int, completion: @escaping () -> Void) {
var counter = seconds
let timer = DispatchSource.makeTimerSource(queue: DispatchQueue.global())
timer.schedule(deadline: .now(), repeating: .seconds(1))
timer.setEventHandler {
counter -= 1
if counter <= 0 {
timer.cancel()
completion()
}
}
timer.resume()
}
// Example usage
startCountdown(seconds: 60) {
print("Countdown completed!")
}
Метод 2: Таймер
import Foundation
func startCountdown(seconds: Int, completion: @escaping () -> Void) {
var counter = seconds
let timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
counter -= 1
if counter <= 0 {
timer.invalidate()
completion()
}
}
timer.fire()
}
// Example usage
startCountdown(seconds: 60) {
print("Countdown completed!")
}
Метод 3: CADisplayLink
import UIKit
func startCountdown(seconds: Int, completion: @escaping () -> Void) {
var counter = seconds
let startTime = CFAbsoluteTimeGetCurrent()
let displayLink = CADisplayLink(target: self, selector: #selector(updateCounter))
displayLink.add(to: .current, forMode: .common)
@objc
func updateCounter() {
let elapsedTime = CFAbsoluteTimeGetCurrent() - startTime
if elapsedTime >= Double(counter) {
displayLink.invalidate()
completion()
}
}
}
// Example usage
startCountdown(seconds: 60) {
print("Countdown completed!")
}
Это всего лишь несколько примеров того, как можно реализовать таймер обратного отсчета в Swift. Каждый метод имеет свои преимущества и может подойти для разных сценариев. Не стесняйтесь выбирать тот, который соответствует вашим конкретным требованиям.