본문 바로가기

iOS/Swift

UIBackgroundTaskIdentifier

A unique token that identifiers a request to run in the background

  • 백그라운드에서 실행할 요청을 식별하는 고유 토큰

Identifier

static let invalid: UIBackgroundTaskIdentifier
  • A token that indicates an invalid task request
  • 작업 요청을 invalid 시키는 것을 나타내는 토큰

예제

import UIKit

class CounterTimer {
    
    private var countdownValue = 180
    
    let counterPublisher: PassthroughSubject<Int, Never> = .init()
    
    private var cancellables: Set<AnyCancellable> = []
    private var backgroundTask: UIBackgroundTaskIdentifier = .invalid
    
    init(countdownValue: Int = 180) {
        self.countdownValue = countdownValue
    }
    
}

extension CounterTimer {
    
    func startCounter() {
        setBackgroundTast()
        Timer.publish(every: 1, on: .main, in: .common)
           .autoconnect()
           .scan(countdownValue) { (countDown, _) in
               max(0, countDown - 1)
           }
           .sink(receiveValue: { [weak self] result in
               print(result)
               let state = UIApplication.shared.applicationState
               if state == .background {
                   print("App in Background")
               } else if state == .active {
                   print("App in Foreground or Active")
               }
               if result == 0 {
                   self?.backgroundTask = .invalid
                   self?.stopTimer()
               }
               self?.counterPublisher.send(result)
           })
           .store(in: &self.cancellables)
    }
    
    func resetCounter() {
        self.cancellables = []
        self.startCounter()
    }
    
}

private extension CounterTimer {
    
    func stopTimer() {
        self.cancellables = []
    }
    
    func setBackgroundTast() {
        self.backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "CounterTimer") {
            self.endBackgroundTask()
        }
    }
    
    func endBackgroundTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundTask)
    }
    
}

  • withName 식별자로 태스크를 정의하고 백그라운드 작업이 필요한 곳에 선언해준다.

작업의 종료 시점에는 UIApplication.shared.endBackgroundTask(self.backgroundTask)로 백그라운드 작업을 종료 시켜야 한다.

  • 만료 작업 처리를 하지 않는 경우 뜨는 warning
 Background task still not ended after expiration handlers were called: <UIBackgroundTaskInfo: 0x600001714640>: taskID = 2, taskName = CounterTimer, creationTime = 93275 (elapsed = 59). This app will likely be terminated by the system. Call UIApplication.endBackgroundTask(:) to avoid this.
  • 해당 백그라운드 작업은 30초 동안만 유지 된다.
Background Task 2 ("CounterTimer"), was created over 30 seconds ago. In applications running in the background, this creates a risk of termination. Remember to call UIApplication.endBackgroundTask(_:) for your task in a timely manner to avoid this.

 

참조

https://developer.apple.com/documentation/uikit/uibackgroundtaskidentifier

https://zetal.tistory.com/entry/UIBackgroundTaskIdentifier-vs

'iOS > Swift' 카테고리의 다른 글

UnsafePointer  (0) 2024.05.08
NWPathMonitor  (0) 2024.05.08
UnsafePointer  (0) 2024.04.29
Singleton Pattern  (0) 2024.04.15
CombineLatest Vs Zip  (0) 2024.04.08