[swift] 비동기 작업의 처리 상태와 진행률 모니터링 방법

Swift 언어를 사용하여 비동기 작업을 수행할 때, 작업의 진행 상태와 결과를 추적하고 모니터링하는 것은 매우 중요합니다. 이번 글에서는 Swift에서 비동기 작업 진행 상태를 모니터링하는 방법에 대해 알아보겠습니다.

진행 상태 모니터링을 위한 Key Paths 활용

Swift 5.1부터는 Key Paths API를 사용하여 비동기 작업의 진행 상태를 모니터링할 수 있습니다. Key Paths를 사용하면 작업의 진행률을 추적하고 적절한 UI 업데이트를 수행할 수 있습니다.

class ProgressTracker {
    @objc dynamic var progress: Float = 0.0
}

let tracker = ProgressTracker()

let observation = tracker.observe(\.progress, options: [.new]) { object, change in
    if let newValue = change.newValue {
        print("Progress updated: \(newValue)")
        // Update UI with newValue
    }
}

// 비동기 작업 수행
DispatchQueue.global().async {
    for i in 0..<100 {
        tracker.progress = Float(i) / 100
        Thread.sleep(forTimeInterval: 0.1)
    }
}

위 코드에서 ProgressTracker 클래스는 @objc dynamic var progress를 통해 진행 상태를 모니터링합니다. observe 메서드를 사용하여 진행률의 변경을 감지하고, 변경이 발생할 때마다 UI를 업데이트할 수 있습니다.

Combine 프레임워크 활용

Swift의 Combine 프레임워크를 사용하면 비동기 작업을 보다 효율적으로 처리하고 진행 상태를 모니터링할 수 있습니다. CurrentValueSubject를 이용하여 진행 상태를 추적하고, receive(on:)을 사용하여 작업의 결과를 메인 스레드에서 처리할 수 있습니다.

import Combine

class ProgressPublisher {
    var progress = CurrentValueSubject<Float, Never>(0.0)
}

let progressPublisher = ProgressPublisher()

let cancellable = progressPublisher.progress.sink(receiveValue: { value in
    print("Progress updated: \(value)")
    // Update UI with value
})

// 비동기 작업 수행
DispatchQueue.global().async {
    for i in 0..<100 {
        progressPublisher.progress.send(Float(i) / 100)
        Thread.sleep(forTimeInterval: 0.1)
    }
}

위 코드에서 ProgressPublisher 클래스는 Combine 프레임워크의 CurrentValueSubject를 이용하여 진행 상태를 추적합니다. sink를 통해 해당 진행 상태를 구독하고, 변경이 발생할 때마다 UI를 업데이트할 수 있습니다.

결론

Swift에서 비동기 작업의 진행 상태를 모니터링하기 위해 Key Paths와 Combine 프레임워크를 사용하는 방법을 살펴보았습니다. 이러한 방법을 통해 작업의 진행 상태를 효율적으로 추적하고 UI를 업데이트할 수 있습니다.