[英]How to call protocol function correctly?
因此,我需要為我的應用程序從服務器收到的每個通知創建通知處理程序類。 為此,我進行如下課程:
protocol NotificationHandlerDelegate: class {
func receiveNotification(content: Any)
}
class NotificationHandler{
var delegate : NotificationHandlerDelegate!
func handleTransactionNotif(content: Any, rootVC: UIViewController){
delegate?.receiveNotification(content: content)
((rootVC as! UINavigationController).viewControllers[0] as! UITabBarController).selectedIndex = 3
}
}
下面是我如何在視圖控制器上調用它:
class TransactionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TransactionsCellDelegate, NotificationHandlerDelegate{
override func viewWillAppear(_ animated: Bool) {
let nh = NotificationHandler()
nh.delegate = self
self.navigationController?.navigationBar.isHidden = true
}
func receiveNotification(content: Any) {
print("called: \(content)")
let contentJSON = JSON(content)
goToScreenAccording(to: "\(contentJSON["status"])", selectedData: content as! [String: Any])
}
}
問題是,每當我收到通知時都不會調用receiveNotification 。 難道我做錯了什么?
將NotificationHandler用作單例,因此您可以引用同一實例:
class NotificationHandler {
weak var delegate: NotificationHandlerDelegate?
static let shared = NotificationHandler()
private init(){}
func handleTransactionNotif(content: Any, rootVC: UIViewController){
delegate?.receiveNotification(content: content)
((rootVC as! UINavigationController).viewControllers[0] as! UITabBarController).selectedIndex = 3
}
}
class TransactionsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, TransactionsCellDelegate, NotificationHandlerDelegate{
override func viewWillAppear(_ animated: Bool) {
let nh = NotificationHandler.shared
nh.delegate = self
self.navigationController?.navigationBar.isHidden = true
}
//...
}
並記住也要在AppDelegate中使用NotificationHandler.shared。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.