【发布时间】:2020-06-02 06:22:02
【问题描述】:
我在 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 中的方法不会随时被调用。
请建议是否可能或任何其他方式来实现这一目标? 感谢您的帮助
【问题讨论】:
-
从您的代码中,它将是
func someButtonTapped () { ... viewModel.saveNotificationnotification: ...) }。 -
@Larme 对不起,它只是错字..更正
-
这不会破坏 MVVM 吗?
-
@JoakimDanielson 在 viewcontroller 的那个方法中我想重新加载 tableview.. 我不知道如何通过 viewmodel 实现这一点
-
您面临的问题是什么?你没有提到那个。没有打印“从视图模型调用”吗?