How to notify a change from a class to multiple ViewControllers? - ios

I'm writing because I'd like to know what's the best method to notify a change from a class to multiple ViewControllers. At the moment I'm using delegate method but I'm sure It's not the best one for this purpose. I created a class where I receive data and after a bit of processing I need to send the processed message to some ViewControllers (any one shows a piece of that message.). At the moment I have a singleton for the class and I assign its delegate to a different ViewController when I load it through a menu. What's your suggestion to do this job?
Here is an example of my actual code:
import Foundation
protocol MyClassDelegate {
func receivedData(_ sender: MyClass)
}
class MyClass: NSObject {
// create the var for delegate
var delegate: MyClassDelegate?
// save the single instance
static private var instance: MyClass {
return sharedInstance
}
private let sharedInstance = MyClass()
static func getInstance() -> MyClass {
return instance
}
func processData() {
// at the end of the process
delegate?.receivedData(self)
}
}
class Menu: UIViewController {
private var containerView: UIView!
private let myClass = Myclass.getInstance()
private var vcOne = VcOne()
private var vcTwo = VcTwo()
override func viewDidLoad() {
super.viewDidLoad()
containerView = UIVIew()
// set containerView position and dimensions
}
func selectViewController(previous: UIViewController, next: UIViewController) {
// remove actual loaded ViewController
previous.willMove(toParent: nil)
previous.view.removeFromSuperView()
previous.removeFromParent()
// assign the delegate
myClass.delegate = next
// add the new ViewController
self.addChild(next)
slef.addSubView(next.view)
next.didMove(toParent: self)
}
}
class VcOne: UIViewController, MyClassDelegate {
func receivedData(_ sender: MyClass) {
// data received
}
}
class VcTwo: UIViewController, MyClassDelegate {
func receivedData(_ sender: MyClass) {
// data received
}
}

You can use NotificationCenter https://developer.apple.com/documentation/foundation/notificationcenter to broadcast a message. or use KVO. Generally I consider notification center much easier.
simple example:
https://www.hackingwithswift.com/example-code/system/how-to-post-messages-using-notificationcenter

Related

How can I move a loadCategories() func from SomeViewController to SomeViewModel?

So I have the following function:
var categoryArray: [Category] = []
private func loadCategories() {
downloadCategoriesFromFirebase { (allCategories) in
self.categoryArray = allCategories
self.collectionView.reloadData()
}
}
that is currently in my SomeViewController. I need to move it to SomeViewModel.
Sorry if my question is not well formulated, please do ask if you need any more information since I am so new at all this.
Thanks in advance
Assuming you have a reference to SomeViewModel in your SomeViewController, you can move the code over there.
For example:
import UIKit
class ViewController: UIViewController {
private var viewModel: ViewModel!
override func viewDidLoad() {
super.viewDidLoad()
callToViewModel()
}
func callToViewModel() {
viewModel.loadCategories {
self.collectionView.reloadData()
}
// rest of your code
}
The ViewModel could look something like this:
import Foundation
class ViewModel: NSObject {
var categoryArray: [Category] = []
override init() {
super.init()
}
func loadCategories(completion: (() -> Void)?) {
downloadCategoriesFromFirebase { (allCategories) in
self.categoryArray = allCategories
completion?()
}
}
}
When reloading your data, make sure to refer to viewModel.categoryArray instead of self.categoryArray now.
Please notice that I'm making use of a completion handler to notify the ViewController the call in the ViewModel was finished. There are other (perhaps better) ways to do this, like the Combine framework.

Weak delegate becomes nil

In my app I'm using delegates, so that I can read the data when ever it's ready.
I'm calling a delegate from two classes. Here is my code
protocol MyDelegate: class {
func getData()
}
class MyDelegateCalss {
weak var delegate: MyDelegate?
func loadData() {
// doing some actions
if(self.delegate != nil){
self.delegate!.getData!()
}
}
}
In one class I'm loading this method in tableview numberOfSections delegate method.
class A: UIViewController, MyDelegate {
func somefunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// Doing some actions
}
}
This method I'm loading from another calss.
class B: UIViewController, MyDelegate {
open func testfunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// doing some other stuff
}
}
class C: UIViewController {
func testfunc(){
let b : B = B()
b.testfunc()
}
}
Here from class A my delegate is working fine. and I'm able to see getData method is calling .
from Class B, the delegate becomes nil and unable to see getData method is called
If I make the delegate reference its working fine. But that will cause memory leak.
How can handle this case ?
Your delegate var is declared as weak. If nothing keep a strong reference on the object you assign as the delegate (implementing MyDelegate), your delegate will pass to nil as soon as the object is released (eg. the end of the scope where you instantiate it).
Some good read: https://cocoacasts.com/how-to-break-a-strong-reference-cycle/

instantiated class is nil when called inside viewdidload()

I am trying to learn the VIPER architecture model and one thing I can't figure out is when I do the following:
Instantiate promotionPresenter class
Instantiate promotionsViewController
assign promotionsViewController.presenter = (instantiated promotionPresenter class from step 1)
try to access the instantiated presenter class from inside viewdidload() function within promotionviewController class.
presenter is nil.
Why is presenter nil? I already instantiated it.
import UIKit
/*
* The Router responsible for navigation between modules.
*/
class PromotionsWireframe : PromotionsWireframeInput {
// Reference to the ViewController (weak to avoid retain cycle).
var promotionsViewController: PromotionsViewController!
var promotionsPresenter: PromotionsPresenter!
var rootWireframe: RootWireframe!
init() {
let promotionsInteractor = PromotionsInteractor()
// Presenter is instantiated
promotionsPresenter = PromotionsPresenter()
promotionsPresenter.interactor = promotionsInteractor
promotionsPresenter.wireframe = self
promotionsInteractor.output = promotionsPresenter
}
func presentPromotionsIntefaceFromWindow(_ window: UIWindow) {
//view controller is instantiated
promotionsViewController = promotionsViewControllerFromStoryboard()
//presenter of view controller is assigned to instantiaed class
promotionsViewController.presenter = promotionsPresenter
promotionsPresenter.view = promotionsViewController
}
private func promotionsViewControllerFromStoryboard() -> PromotionsViewController {
let storyboard = UIStoryboard(name: "PromotionsStoryboard", bundle: nil )
let viewController = storyboard.instantiateViewController(withIdentifier: "promotionsViewController") as! PromotionsViewController
return viewController
}
}
import UIKit
class PromotionsViewController : UIViewController, PromotionsViewInterface {
// Reference to the Presenter's interface.
var presenter: PromotionsModuleInterface!
var promotions: [Promotion]!
/*
* Once the view is loaded, it sends a command
* to the presenter asking it to update the UI.
*/
override func viewDidLoad() {
super.viewDidLoad()
// getting error because presenter is unwrapped as nil
self.presenter.updateView()
}
func showPromotionsData(_ promotions: [Promotion]) {
// need to implement
}
}
import Foundation
class PromotionsPresenter : PromotionsModuleInterface, PromotionsInteractorOutput {
// Reference to the View (weak to avoid retain cycle).
var view: PromotionsViewInterface!
// Reference to the Interactor's interface.
var interactor: PromotionsInteractorInput!
var wireframe: PromotionsWireframe!
func updateView() {
self.interactor.fetchLocalPromotions()
}
func PromotionsFetched(_promotions: [Promotion]) {
// need to implement
}
}
I suggest you take this boilerplate (https://github.com/CheesecakeLabs/Boilerplate_iOS_VIPER) and read this post (https://www.ckl.io/blog/best-practices-viper-architecture/) in order to learn not only how to correctly initialize your VIPER modules, but also how to automate VIPER files creation and initiazlization

Duplicate codes in Controller

I am currently working on one project. It may potentially have duplicated codes in multiple controllers like below.
Controller A
class A: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
// about 50~70 lines of codes
#IBAction func scanButtonTapped {
// used self (as AVCaptureMetadataOutputObjectsDelegate)
// used view
// called presentViewController(...), which is a func in UIViewController
}
}
Controller B
class B: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
#IBAction func scanButtonTapped {
// will need same logic as in Controller A
}
}
My current solution is have another class C, and move the duplicated codes into it. However, if I do so, controller can cast to AVCaptureMetadataOutputObjectsDelegate, but not to UIViewController.
class C {
func btnTapped (view: UIView, controller: AnyClass) {
// logic is here
// controller can cast to AVCaptureMetadataOutputObjectsDelegate
// but controller cannot cast to UIViewController
}
}
so A and B will have
class A {
#IBAction func scanButtonTapped {
let c = C()
c.btnTapped(view, self)
}
}
My question is if it is possible to cast controller into UIViewController. OR is there another way to refactor the codes properly?
What about extend AVCaptureMetadataOutputObjectsDelegate protocol and create default implementation by protocol extension (POP approach)?
protocol ScanButtonClickable: AVCaptureMetadataOutputObjectsDelegate {
func btnTapped() // this line is optional
}
extension Clickable where Self: UIViewController {
func btnTapped() {
// logic is here
}
}
class A: UIViewController, ButtonClickable {
...
}
class B: UIViewController, ButtonClickable {
...
}
Try this:
//declare your default method to be used across classes
protocol MyProtocol {
func myFunc()
}
//provide the implementation of your default behavior here in myFunc()
extension MyProtocol {
func myFunc() {
print("Default behavior")
}
}
class A: MyProtocol {
}
class B: MyProtocol {
}
let a = A()
a.myFunc()
let b = B()
b.myFunc()
//prints
Default behavior
Default behavior

Call view controller method from custom class

I have a custom class and a view controller.
My custom class:
class ChatManager:NSObject {
func messageArrived() {
//When Message arrives I am handling it from here
//I need something like that: Viewcontroller.updateTable()
}
}
When message arrives from internet I need to update tableview in view controller. So I mean I have to call a view controller method from messageArrived method. How can I do this ?
Here is a simple example of using delegate:
declare the delegate before your chat manager class
protocol ChatManagerDelegate {
func manageMessage()
}
when the message arrived, call the delegate method to handle it.
class ChatManager: NSObject {
var delegate: ChatManagerDelegate?
func messageArrived() {
self.delegate!.manageMessage()
}
}
in your view controller, remember to set the delegate of the chat manager to self.
class ViewController: ChatManagerDelegate {
var manager = ChatManager()
manager.delegate = self
func manageMessage() {
self.updateTable()
}
}
This would be a possible implementation:
ViewController:
class ViewController: UIViewController,ChatManagerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let myChatManager = ChatManager()
myChatManager.delegate = self
}
func messageDidArrive() {
// Do Things here.
}
}
Chatmanager:
class ChatManager:NSObject {
var delegate:ChatManagerDelegate?
func messageArrived() {
//When Message arrives I am handling it from here
//I need something like that: Viewcontroller.updateTable()
}
}
Delegate-Protocol:
protocol ChatManagerDelegate{
func messageDidArrive()
}

Resources