티스토리 뷰

이번 시간에는 Push 알림 메시지가 도착했을 때, 앱의 여러 뷰 중 특정 뷰를 오픈하는 법에 대해 작성해봅니다.

 

해당 예제는 5개의 탭으로 구성되어 있는 StoryBoard에서 네번째 탭을 열고, 네번째 탭에서 secondVC를 modal이 아닌 Push 형식으로 전환하는 방법을 담고 있습니다.

 

따라서 네번째 탭을 먼저 navigationController를 연결, navigationController의 rootView로 secondVC를 연결하는 선행 과정이 필요합니다.

// 1. AppDelegate 속에 didReceive 메서드 구현

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        
        // 해당 Notification의 content로 메시지 별 분기 가능
        
        if response.notification.request.content.title == "해당 컨텐츠의 타이틀 입력" {
        
	        // 5개의 탭을 가지고 있는 TabBarController 중 4번째 뷰(Index = 3)을 띄우기 위해 노티를 보냄
            NotificationCenter.default.post(name: Notification.Name("이름 설정"), object: nil, userInfo: ["index":3])
        }
}

// 2. TabBarController에서 노티 수신하기 (해당 탭바에 Cocoa Touch Class 연결 필수)

class tabBarVC: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 노티 수신
        NotificationCenter.default.addObserver(self, selector: #selector(showPage(_:)), name: NSNotification.Name("이름 설정"), object: nil)
    }
    
    @objc func showPage(_ notification:Notification) {
        if let userInfo = notification.userInfo {
            if let index = userInfo["index"] as? Int {
            
            	// 네번째 탭의 VC는 NavigationBar를 가지고 있어서 UINavigationController로 다운 캐스팅을 해주기
                let navigationController = self.children[index] as? UINavigationController
                
                // 받아온 인덱스(3, 네번째 탭을 의미)에 해당하는 VC를 띄우고,
                self.selectedIndex = index
                
                // navigationController에 연결되어 있는 secondVC를 push 형식으로 전환
                guard let secondVC = storyboard?.instantiateViewController(withIdentifier: "secondVC") as? secondVC else { return }
                navigationController?.pushViewController(secondVC, animated: true)
                
                // Modal로 띄우고 싶으면 NavigationController를 연결하는 선행 과정 없이 present 메서드를 사용하면 됨.
            }
            
        }
    }
}

 

 

 

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함