Ivan.Yang
Ivan.Yang

Reputation: 287

How to transfer data using delegate in VIPER structure

I have two pages, page one is loginPage, another is MainViewPage.

I wanna transfer userInfo (UserName and Password) from page one to two, I'm using VIPER structure.

I already get the userInfo in the second page, but when I'm using Presenter function to update UILabel in SecondPage, the progress is broken, it shows following error:

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value.

import Foundation
import UIKit

class MainViewModuleView: UIViewController, MainViewModuleViewProtocol
{
    var presenter: MainViewModulePresenterProtocol?
    
    @IBOutlet weak var userInfo: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
//        print(NSHomeDirectory()as NSString)
    }
    
    func updateLabel(text:String){
        print(text)
        userInfo.text = text
    }
}

Here is my Presenter:

import Foundation

class MainViewModulePresenter: MainViewModulePresenterProtocol, MainViewModuleInteractorOutputProtocol
{
    weak var view: MainViewModuleViewProtocol?
    var interactor: MainViewModuleInteractorInputProtocol?
    var wireFrame: MainViewModuleWireFrameProtocol?
    var delegate: MainModuleDelegate?
    
    init() {}    
}

extension MainViewModulePresenter: MainModuleDelegate{
    
    func sendLoginUser(userName: String) {
        print("MainViewModulePresenter?.sendLoginUser: " + userName)
        let text = userName
        view?.updateLabel(text: text)
    }
}

The text in both Presenter and MainView has value, but when it call updateLabel function, the progress was broken. The Code of this Demo in this repository

Upvotes: 1

Views: 459

Answers (2)

Amol Prakash
Amol Prakash

Reputation: 257

Your label is uninitialized during the assignment. I think your method is being called before viewDidLoad.

Upvotes: 0

Scott McKenzie
Scott McKenzie

Reputation: 16242

I think it's a case of the MainViewModuleView not being loaded/instantiated from the storyboard.

It seems to lose its connection with the storyboard shortly afterwards.

Upvotes: 1

Related Questions