(Swift) 如何在 TabBarController 之間傳送資料 (使用 Notification)

目的:即時同步顯示 shop 頁面最愛的商品 到 favorite 頁面中

主要做法

使用 Notification 不斷發送通知,當 favorite 頁面不斷收到通知後,不斷讀取 UserDefault 中的最新資料來更新表格

第一步

新增一個 Notification 的 Swift File

並新增以下程式碼

import Foundation

struct AllNotification {
static let favoritupdate = Notification.Name("favoritupdate")
static let favoriteInfo = "favoriteInfo"
}

第二步

在 shop 頁面中,只要有最愛的商品新增,就發布一次通知

var AllButtonState:[Bool] = [] {
didSet {
userDefault.set(AllButtonState, forKey: "favorite")
// 發布通知
NotificationCenter.default.post(name: AllNotification.favoritupdate, object: nil)
}
}

第三步

在 favorite 頁面中新增接收通知,並且同步即時的資料

override func viewDidLoad() {
super.viewDidLoad()
...
// 接收通知
NotificationCenter.default.addObserver(self, selector: #selector(updatefavorite(noti: )), name: AllNotification.favoritupdate, object: nil)

}

@objc func updatefavorite(noti: Notification) {
// 刪除舊的資料
counts = 0
DisplayProdicts = []

// 讀取存在 userDefault 的資料
// 並同步到 DisplayProdict
DisplayProdictBool = userDefault.array(forKey: "favorite") as! [Bool]

// 計算 true 的數量
for i in DisplayProdictBool where i == true {
counts += 1
}

// 找出對應為 true 的資料,並加入到顯示的 Array 中
for i in 0...AllProdict.count - 1 where DisplayProdictBool[i] == true {
DisplayProdicts.append(AllProdict[i])

}
tableView.reloadData()

}

以上就是如何使用 Notification 讓 TabBarController 之間的 Controller 溝通並傳送資料,中間省略了 favorite 中顯示表格的數量及資料方式,大家有興趣的可以看完整的檔案就能了解,若有問題歡迎提出討論謝謝

GitHub

--

--