【发布时间】:2020-06-02 07:56:30
【问题描述】:
我在 iOS 项目中使用 MVVM 设计模式。我正在尝试从 viewmodel 调用 viewcontroller 中的方法。
import Foundation
class NotificationViewModel {
var onCompletion: ((_ success: Bool) -> ())?
func saveNotification(notification: Dictionary<String, Any>) {
print("notification save")
//other logic
onCompletion?(true)
}
}
收到通知时从appdelegate调用“saveNotification”方法
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
guard
let aps = userInfo[AnyHashable("aps")] as? NSDictionary,
let alert = aps["alert"] as? NSMutableDictionary
else {
// handle any error here
return
}
NotificationViewModel().saveNotification(notification: alert as! Dictionary<String, Any>)
}
在“saveNotification”触发时尝试调用视图控制器中的方法
class AlertViewController: BaseViewController{
var viewModel = NotificationViewModel()
override func viewDidLoad() {
super.viewDidLoad()
self.viewModel.onCompletion = { success in
// this should be executed when `saveNotification()` will be called
// **** this is never getting called ******
print("calling from viewmodel")
methodToCall()
}
}
func methodToCall(){
//logic
}
}
但是 viewdidload 中的方法不会随时被调用。
请建议是否可能或任何其他方式来实现这一目标? 感谢您的帮助
【问题讨论】: