seong_hye, the developer

Swift) 백그라운드 실행(Background Execution) 본문

IOS

Swift) 백그라운드 실행(Background Execution)

seong_hye 2022. 8. 2.

📘Swift) Background Execution

어떤 경우 앱이 백그라운드 상태로 들어가도 내용이 진행되고 상태를 받아온다

그런 경우는 어떻게 진행되는 걸까?


🔹 백그라운드 실행 ( Background Execution )

앱이 화면에 보이지 않더라도 작업을 계속 수행하거나 완료할 수 있도록 하는 기능

iOS는 리소스 절약을 위해 앱이 백그라운드로 가면 대부분의 실행을 중지시키므로,

특정 조건과 방식에 따라 백그라운드에서도 작업을 지속할 수 있도록 해야 함


🔹 iOS에서 백그라운드 실행 가능한 주요 케이스

iOS는 백그라운드 작업을 허용하는 제한된 기능만 공식적으로 지원함

유형 설명
백그라운드 오디오 음악 / 음성 등 재생 유지
백그라운드 위치 추적 GPS나 위치 업데이트 지속
VolP 인터넷 전화 대기 (iOS 13 이후 제한됨)
백그라운드 다운로드/업로드 URLSession의 백그라운드 세션
백그라운드 작업 처리 앱 전환 시 짧은 시간 (최대 30초) 유예 시간 제공
푸시 알림 응답 처리 푸시 수신 시 특정 로직 처리 가능

🔹 일반 앱에서의 백그라운드 실행 전략

✅ 1. beginBackgroundTask(expirationHandler:)

앱이 백그라운드로 전환될 때, 일시적으로 실행을 연장하고 싶을 때 사용

var backgroundTask: UIbackgroundTaskIdentifier = .invalid

func startBackgroundTask() {
	backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "MyTask") {
    	//시간이 다 되었을 때 호출
        UIApplication.shared.endBackgroundTask(self.backgroundTask)
        self.backgroundTask = .invalid	
	}
    
    //백그라운드에서 수행할 작업
    DispatchQueue.global().async {
    	for i in 0..<10 {
        	print("백그라운드 작업 중 : \(i)")
            sleep(1)
        }
        
        UIApplication.shared.endBackgroundTask(self.backgroundTask)
        self.backgroundTask = .invalid
	}
}

- 일반적으로 30초 ~ 3분 정도 시간이 부여됨 (애플 내부 정책에 따라 다름)

- 반드시 endBackgroundTask 호출해야 함!

 

✅ 2. URLSession을 통한 백그라운드 다운로드

let config = URLSessionConfiguration.background(withIdentifier: "com.example.download")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

- 앱이 종료되었거나 백그라운드에 있어도 다운로드/업로드가 계속됨

- delegate 기반으로 이벤트 처리

 

✅ 3. 백그라운드 위치 추적

Info.plist에 다음 항목 추가

<key>UIBackgroundModes</key>
<array>
	<string>location</string>
</array>

- CLLocationManager를 적절히 설정하면 백그라운드에서도 위치 추적 가능

- 배터리 소모가 많아 애플 심사 시 주의 필요


🔹 SwiftUI에서는?

SwiftUI 자체적으로는 백그라운드 작업 API가 없고, UIKit 기반 API를 함께 사용해야 함

@main
struct MyApp: App {
	@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
    	WindowGroup {
        	ContentView()
        }
    }
}

class AppDelegate: NSObject, UIApplicationDelegate {
	func applicationDidEnterBackground(_ application: UIApplication) {
    	//작업 시작
    }
}

🔹 백그라운드 유지 팁 & 주의사항

- DispatchSourceTimer는 백그라운드 진입 시 자동으로 중지됨 -> beginBackgroundTask와 함께 써야 유효

- 무한 루프 금지: 리소스 남용 시 앱 강제 종료- UIApplication.shared.isIdleTimerDisabled = true -> 화면 꺼짐 방지


🔹목적에 따라 사용할 수 있는 기술

목적 사용할 기술
단기 작업 유지 (30초 ~ 3분) beginBackgroundTask
대용량 다운로드 URLSession background
위치 추적 CLLocationManager + background mode
음성 재생 AVAUdioSession + background mode

'IOS' 카테고리의 다른 글

Swift) WidgetKit이란?  (0) 2022.08.02
Swift) 문법 정리 - COW(Copy-On-Write)  (0) 2022.08.02
Swift) DispatchSourceTimer이란?  (0) 2022.08.02
Swift) NotificationCenter이란?  (0) 2022.07.26
Swift) Class vs Struct  (0) 2022.07.26
Comments