๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
iOS

[iOS] ํ‘ธ์‹œ์•Œ๋ฆผ ๋ฐ›์•„์„œ ์ฒ˜๋ฆฌํ•˜๊ธฐ

by yangsubinn 2022. 10. 12.

ํ‘ธ์‹œ์•Œ๋ฆผ์„ ํ†ตํ•ด ์•ฑ์— ๋“ค์–ด์˜ค๋Š” ๊ฒฝ์šฐ๋Š” ํฌ๊ฒŒ ๋‘๊ฐ€์ง€๋กœ ๋‚˜๋‰  ์ˆ˜ ์žˆ์Šด๋‹ˆ๋‹ค

  1. ์•ฑ์ด ์™„์ „ํžˆ ์ข…๋ฃŒ๋œ ์ƒํƒœ
  2. inactive/active/background ์ƒํƒœ

 

1๏ธโƒฃ ์•ฑ์ด ์™„์ „ํžˆ ์ข…๋ฃŒ๋œ ์ƒํƒœ์—์„œ ํ‘ธ์‹œ์•Œ๋ฆผ์„ ํ†ตํ•ด ์•ฑ์— ๋“ค์–ด์˜ค๋Š” ๊ฒฝ์šฐ

SceneDelegate์˜ willConnectTo์—์„œ ์ฒ˜๋ฆฌ

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

		...
    
    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        
				...
        
				// ์•ฑ ์ข…๋ฃŒ ์ƒํƒœ์—์„œ ํ‘ธ์‹œ์•Œ๋ฆผ์„ ํ†ตํ•ด ์•ฑ์— ์ ‘์†ํ•˜๋Š” ๊ฒฝ์šฐ
        if let notification = connectionOptions.notificationResponse {
						// notification์— ํฌํ•จ๋˜์–ด ์ „๋‹ฌ๋˜๋Š” content๋Š” ์•„๋ž˜์™€ ๊ฐ™์ด ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค
            let content = notification.notification.request.content
						// dictionary ํ˜•ํƒœ๋กœ, userInfo["key๊ฐ’"] ์œผ๋กœ ์ ‘๊ทผ ๊ฐ€๋Šฅ
            let userInfo = content.userInfo
            guard let recordId: String = userInfo["recordId"] as? String else { return }
						// ์›ํ•˜๋Š” ๋ทฐ๋กœ ์ „ํ™˜
        }
    }
		...
}

 

2๏ธโƒฃ ์•ฑ์ด ์™„์ „ ์ข…๋ฃŒ๋˜์ง€ ์•Š์€ ์ƒํƒœ์—์„œ ํ‘ธ์‹œ์•Œ๋ฆผ์„ ํ†ตํ•ด ์•ฑ์— ๋“ค์–ด์˜ค๋Š” ๊ฒฝ์šฐ (background / inactive / active)

์ด๋Ÿฐ ์ƒํƒœ์—์„œ ์•ฑ์„ ์ ‘์†ํ•˜๋Š” ๊ฒฝ์šฐ, ์Šคํ”Œ๋ž˜์‹œ๋ฅผ ๊ฑฐ์น˜์ง€ ์•Š๊ณ  ๋งˆ์ง€๋ง‰์œผ๋กœ ์•ฑ์„ ์‚ฌ์šฉํ–ˆ์„๋•Œ ๋ณธ ๋ทฐ๊ฐ€ ์œ ์ง€๋˜์–ด ์žˆ์Šต๋‹ˆ๋‹ค.

AppDelegate์˜ didReceive ์—์„œ ์ฒ˜๋ฆฌ

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
				...
				
				// active / inactive / background
        let applicationState = UIApplication.shared.applicationState
        
				// ์ƒํƒœ์— ๋”ฐ๋ผ ์›ํ•˜๋Š” ๋ทฐ๋กœ ์ „ํ™˜
        if applicationState == .active || applicationState == .inactive {
            // active ๋˜๋Š” inactive ์ƒํƒœ์—์„œ ํ‘ธ์‹œ์•Œ๋ฆผ์„ ๋ˆ„๋ฅธ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ
        } else if applicationState == .background {
						// background ์ƒํƒœ์—์„œ ํ‘ธ์‹œ์•Œ๋ฆผ์„ ๋ˆ„๋ฅธ ๊ฒฝ์šฐ ์ฒ˜๋ฆฌ
				}
}