Swift - 透過 NotificationCenter 監聽特定的事件同時傳值

約翰:「哼哼~~用了NotificationCenter,不管頁面傳值還是監聽叫起特定的Func都超好用的啦~~~哈哈哈哈」

「彷彿山頂洞人已知用火…孩只的教育不能等」前輩一邊搖頭一邊碎念著什麼…

這次遇到的問題是,讓會員在系統中綁定 LINE Pay,正常來說希望綁定成功與失敗在 APP 裡要跳出 Alert,

但 LINE Pay 的綁定是在 APP 之外,所以當會員綁定成功,我們透過綁定成功的網頁打開 APP ,帶一個 Scheme 讓 APP 知道要進入某一頁顯示 Alert

由於 AppDelegate 已經有其它判斷事件,在不影響原有邏輯情況下

我先在新增綁定的按鈕按下時註冊監聽 "UIApplicationDidBecomeActive"(當 APP 變成前景狀態時)去執行某個 Function

但這樣一來,如果使用者切回 APP 時畫面不是我註冊監聽的畫面時,是無法顯示任何View的,

所以,我接著在 AppDelegate 裡面原本就有的UIApplicationDidBecomeActive事件裡去判斷,如果顯示畫面不是在我想要的那個畫面時

我就把它放到currentPresent裡,並在 Complete 時做我原本該做的事,也就是把結果的 Alert 給秀出來。

以下是部分的程式內容:


 
// 監聽自定義的事件
// 說明:
    override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(想觸發的函式(notification:)), name: NSNotification.Name("監聽訊號名稱") , object: nil)
    }

// 範例 1 
// 說明:當這個事件"OpenAddLinePayNVC"被觸發時,我希望能執行這個函式"catchOpenNVCNotification"
    NotificationCenter.default.addObserver(forName: Notification.Name(rawValue: "OpenAddLinePayNVC"), object: nil, queue: nil, using: catchOpenNVCNotification)

    func catchOpenNVCNotification(notification:Notification) -> Void {
        // 取得傳入的參數
        guard let userInfo = notification.userInfo,
            let message  = userInfo["message"] as? String,
            let date     = userInfo["date"]    as? Date else {
            print("No userInfo found in notification")
            return
        }
        // 執行一次就好,所以把這個監聽移掉
        NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "OpenAddLinePayNVC"), object: nil)
        // do something you want...

    }
    
    // 手動在特定的時間點觸發這個事件,並傳入相關的參數
    @IBAction func onMyButtonTapped(_ sender: Any) {
        self.dismiss(animated: true, completion: {
            NotificationCenter.default.post(name: Notification.Name(rawValue: "OpenAddLinePayNVC"), object: nil, userInfo: ["message":"OpenAddLinePayNVC","date":Date()])
        })
    }

// 範例 2
// 說明:當App正進入Active時,本來就會觸發"UIApplicationDidBecomeActive",我希望同時也執行這個函式"applicationDidBecomeActive"
    override func viewDidLoad() {
        NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: Notification.Name.UIApplicationDidBecomeActive, object: nil)
    }

// 不需要額外像範例1 去打post,iOS會先叫起AppDelegate的"applicationDidBecomeActive",接著才會進入我寫在某個ViewController的"applicationDidBecomeActive"