macOS, iOS
[iOS] AppDelegate에서 푸시 받아서 SceneDelegate에서 뷰 세팅해주기
SweetDev
2021. 6. 4. 09:39
extension AppDelegate: UNUserNotificationCenterDelegate{
// This function will be called right after user tap on the notification
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// tell the app that we have finished processing the user’s action / response
completionHandler()
}
}
여기서 푸시를 받아온다! 근데 iOS 13부터는 SceneDelegate가 생겨서... 굉장히 애매해졌다.
window.rootViewController가 AppDelegate에서 접근 가능하게만 바꿔주면 된다.
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void)
{
let userInfo = response.notification.request.content.userInfo
guard var rootViewController = (UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate)?.window?.rootViewController else {
return
}
// change your view controller here
rootViewController = UIViewController()
print("====userInfo====")
print(userInfo)
....
}
이렇게 써주고 userInfo에 따라서 분기 타서 푸시 해주면 된다.
아예 처음 앱을 켜서 들어온 경우는,
이 코드를 application(_:didFinishLaunchingWithOptions:) 에 넣어주면 된다.
// Check if launched from notification
let notificationOption = launchOptions?[.remoteNotification]
// 1
if
let notification = notificationOption as? [String: AnyObject],
let aps = notification["aps"] as? [String: AnyObject] {
// 2
NewsItem.makeNewsItem(aps)
// 3
(window?.rootViewController as? UITabBarController)?.selectedIndex = 1
}