ios Push

quokka·2021년 3월 26일
0

iOS

목록 보기
11/27
//푸시 권한요청을 보내준다.
func application(_ application: UIApplication, 
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
//launchOptions: 앱이 시작된 이유를 나타내는 사전입니다 (있는 경우).
//사용자가 앱을 직접 시작한 상황에서는이 사전의 내용이 비어있을 수 있습니다.

UNUserNotificationCenter.current().requestAuthorization( options: [.alert, .badge, .sound],
completionHandler: { _, error in

            if error != nil {
                print(error)
            } else {
                DispatchQueue.main.async {
                    UIApplication.shared.registerForRemoteNotifications()
                    //푸시 등록 시작
                    // 등록 성공시 이 메서드를 호출하고 디바이스 토큰을 전달한다.application (_ : didRegisterForRemoteNotificationsWithDeviceToken :)
                    // 등록 실패시 이 메서드를 호출한다. application (_ : didFailToRegisterForRemoteNotificationsWithError :) 
                }
            }
        })

UNUserNotificationCenter.current().delegate = self 
// delegate채택

if let _: = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification]
            as? [AnyHashable: Any] {
           	//푸시 왔을때 code
        }

extension AppDelegate: UNUserNotificationCenterDelegate {
// 앱이 현재 화면에서 실행되고 있을때
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .banner, .sound])
        
    }
    
// 앱이 화면에 없지만 백그라운드에서 실행중일때
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        completionHandler()
        //response를 이용하여 푸시메시지 분석가능
    }
}

출처
https://zeddios.tistory.com/157
https://g-y-e-o-m.tistory.com/74
https://g-y-e-o-m.tistory.com/87

profile
iOS를 공부하는 개발자입니다~ㅎㅎ

0개의 댓글