How can i send data from Module A to Module B in VIPER? I use router A, which has information for Module B, and try to send this information to view controller B or presenter B. What is the best way to do it?
Can not send data to another module in VIPER
Asked Answered
In that case my workflow is:
- Usually the user interface (
view
) in module A launches an event that triggers the module B. - The event reaches the
presenter
in module A. Thepresenter
knows it has to change module and notifieswireframe
who knows how to make the change. - The
wireframe
in module A notifies towireframe
in module B. In this call sends all data needed - The
wireframe
in module B continues its normal execution, transferring the information to thepresenter
wireframe
in module A must knowwireframe
B
Use delegates to send data between VIPER modules:
// 1. Declare which messages can be sent to the delegate
// ProductScreenDelegate.swift
protocol ProductScreenDelegate {
//Add arguments if you need to send some information
func onProductScreenDismissed()
func onProductSelected(_ product: Product?)
}
// 2. Call the delegate when you need to send him a message
// ProductPresenter.swift
class ProductPresenter {
// MARK: Properties
weak var view: ProductView?
var router: ProductWireframe?
var interactor: ProductUseCase?
var delegate: ProductScreenDelegate?
}
extension ProductPresenter: ProductPresentation {
//View tells Presenter that view disappeared
func onViewDidDisappear() {
//Presenter tells its delegate that the screen was dismissed
delegate?.onProductScreenDismissed()
}
}
// 3. Implement the delegate protocol to do something when you receive the message
// ScannerPresenter.swift
class ScannerPresenter: ProductScreenDelegate {
//Presenter receives the message from the sender
func onProductScreenDismissed() {
//Presenter tells view what to do once product screen was dismissed
view?.startScanning()
}
...
}
// 4. Link the delegate from the Product presenter in order to proper initialize it
// File ScannerRouter.swift
class ProductRouter {
static func setupModule(delegate: ProductScreenDelegate?) -> ProductViewController {
...
let presenter = ScannerPresenter()
presenter.view = view
presenter.interactor = interactor
presenter.router = router
presenter.delegate = delegate // Add this line to link the delegate
...
}
}
For more tips, check this post https://www.ckl.io/blog/best-practices-viper-architecture/
Does wireframe have reference to presenter? This version of VIPER which i use
The router knows about another module and tells view to open it. Assembly combines all parts of module.
© 2022 - 2024 — McMap. All rights reserved.