How to receive same callback in two ViewControllers when one is opened? - ios

I want to receive the same callback in the ViewController that is opened at in the time that server response in my Swift Application.
I have two ViewControllers. The first ViewController registers a callBack from a class "NetworkService".
The second ViewController is Opened from the first ViewController and the second receives the "NetworkService" from the firstViewController initialized in a variable, and then registers the same callBack.
When I try to receive the callback from the server, if the first ViewController is opened I get the response. If I open the second ViewController and I resend the response I get this correctly in the second ViewController.
BUT if I return to the first ViewController and I get the response, its' only received on the Second ViewController all times.
class NetworkService {
var onFunction: ((_ result: String)->())?
func doCall() {
self.onFunction?("result")
}
}
class MyViewController: UIViewController {
let networkService = NetworkService()
override func viewDidLoad() {
super.viewDidLoad()
networkService.onFunction = { result in
print("I got \(result) from the server!")
}
}
}
I open the secondViewController like:
let vc = self.storyboard!.instantiateViewController(withIdentifier: "second") as! SecondViewController
vc. networkService = networkService
self.navigationController?.pushViewController(vc, animated: true)
And the Second ViewController:
class SecondViewController: UIViewController {
var networkService: NetworkService?
override func viewDidLoad() {
super.viewDidLoad()
networkService!.onFunction = { result in
print("I got \(result) from the server!")
}
}
}
How would it be possible to receive the response in the first ViewController again, then return to first ViewController from the second calling the popViewController?
self.navigationController?.popViewController(animated: false)

How about calling the function within viewDidAppear on both ViewControllers so that you get your response every time you switch between the two views? You wouldn't need to pass networkService between the ViewControllers.
override func viewDidAppear(_ animated: Bool) {
networkService!.onFunction = { result in
print("I got \(result) from the server!")
}
}

You can use notification but you will have to register and deregister VC as you switch between views. Other option is to use delegate, you will need to share NetworkService instance. Quick example of how this could work with protocol.
protocol NetworkServiceProtocol {
var service: NetworkService? { get }
func onFunction(_ result: String)
}
class NetworkService {
var delegate: NetworkServiceProtocol?
func doCall() {
self.delegate?.onFunction("results")
}
func update(delegate: NetworkServiceProtocol) {
self.delegate = delegate
}
}
class VC1: UIViewController, NetworkServiceProtocol {
var service: NetworkService?
init(service: NetworkService? = nil) {
self.service = service
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.service?.update(delegate: self)
}
func onFunction(_ result: String) {
print("On Function")
}
}

Related

use popToRootViewController and pass Data

I'm applying for a junior developer position and I've got a very specific task, that already took me 3 days to complete. Sounds easy - pass data to rootViewController.
That's what I've done:
1)
private func userDefaultsToRootController() {
let input = textField.text!
defaults.set(input, forKey: "SavedLabel")
navigationController?.popViewController(animated: true)
}
private func segueToRootViewController() {
let destinationVC = MainScreen1()
let input = textField.text!
if input == "" { self.navigationController?.popToRootViewController(animated: true) }
destinationVC.input = input
navigationController?.pushViewController(destinationVC, animated: true)
}
private func popToNavigationController() {
let input = textField.text!
if let rootVC = navigationController?.viewControllers.first as? MainScreen1 {
rootVC.input = input
}
navigationController?.popToRootViewController(animated: true)
}
I've used CoreData
But here is the difficult part - I've got an email, that all these methods are not good enough and I need to use delegate and closure. I've done delegation and closures before, but when I popToRootViewController delegate method passes nil. Could you at least point where to find info about this?
** ADDED **
There are 2 View Controllers: Initial and Second one.
That's what I have in the Initial View Controller:
var secondVC = MainScreen2()
override func viewDidLoad() {
super.viewDidLoad()
secondVC.delegate = self
}
That's how I push SecondViewController
#objc private func buttonTapped(_ sender: CustomButton) {
let nextViewController = MainScreen2()
navigationController?.pushViewController(nextViewController, animated: true)
}
In SecondViewController I've got this protocol
protocol PassData {
func transferData(text: String)
}
Also a delegate:
var delegate: PassData?
This is how I go back to initial view controller
#objc private func buttonTapped(_ sender: CustomButton) {
if let input = textField.text {
print(input)
self.delegate?.transferData(text: input)
self.navigationController?.popToRootViewController(animated: true)
}
}
Back to the Initial view controller where I've implemented delegate method
extension MainScreen1: PassData {
func transferData(text: String) {
print("delegate called")
label.text = text
}
}
Delegate doesn't get called.
BASED ON YOUR EDIT:
You must set the delegate in buttonTapped
#objc private func buttonTapped(_ sender: CustomButton) {
let nextViewController = MainScreen2()
nextViewController.delegate = self // HERE WHERE YOU SET THE DELEGATE
navigationController?.pushViewController(nextViewController, animated: true)
}
You can delete the second instance and your code in viewDidLoad. That's not the instance you push.
This should point you in the right direction to use delegation and completion handler.
protocol YourDelegateName {
func passData(data:YourDataType)
}
class SecondViewController: UIViewController {
var delegate: YourDelegateName?
func passDataFromSecondViewController(){
YourCoreDataClass.shared.getCoreData { (yourStringsArray) in
self.delegate?.passData(data: yourStringsArray)
self.navigationController?.popToRootViewController(animated: true)
}
}
class InitialViewController: UIViewController, YourDelegateName {
override func viewDidLoad() {
super.viewDidLoad()
// or whenever you instantiate your SecondViewController
let secondViewController = SecondViewController()
secondViewController.delegate = self //VERY IMPORTANT, MANY MISS THIS
self.navigationController?.pushViewController(createVC, animated: true)
}
func passData(data:YourDataType){
//user your data
}
}
class YourCoreDataClass: NSObject {
static let shared = YourCoreDataClass()
func getCoreData (completion: ([String]) -> ()){
........... your code
let yourStringsArray = [String]() // let's use as example an array of strings
//when you got the data your want to pass
completion(yourStringsArray)
}
}

Delegate always getting nil value in dynamic framework class

I used delegation for passing data to ViewController B to A in dynamic framework . B is my dynamic framework ViewController . A is my app ViewController . I am always set delegate as self in my A class
Without dynamic framework it works perfectly
Class B code : Inside dynamic framework (Using .xib)
import UIKit
public protocol MediaDataDelegate: class{
func mediaDidFinish(controller:
LoginViewController,transactionId:String,returnURL: String)
}
public class LoginViewController: UIViewController {
public var message = ""
public var delegate: MediaDataDelegate?
public init() {
super.init(nibName: "LoginViewController", bundle: Bundle(for: LoginViewController.self))
print("message 1234 :\(message)")
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func viewDidLoad() {
super.viewDidLoad()
print("message 1234 :\(message)")
}
public class func logToConsole(_ msg: String) {
print(msg);
}
#IBAction func backToMainBtnTapped(_ sender: UIButton) {
self.delegate?.mediaDidFinish(controller: self, transactionId: "WERTYQWRCT", returnURL: "www.media.com")
}
}
Class A Code:Inside Other App (Using Storyboard)
Click on conduct IPVButton navigate to dynamic framework view controller
I also pass some value to message string but in dynamic framework class getting empty string.
import UIKit
import NBView
class ViewController: UIViewController ,MediaDataDelegate{
var loginVC = LoginViewController()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
LoginViewController.logToConsole("hello media")
}
#IBAction func conductIPVBtnTapped(_ sender: Any) {
loginVC.delegate = self
present(loginVC, animated: true, completion: nil)
}
func mediaDidFinish(controller: LoginViewController, transactionId:
String, returnURL: String) {
print("Trans Id\(transactionId)")
print("return URl \(returnURL)")
}
}
It is because you are instantiating incorrectly the LoginViewController
You need to do it this way, since you wrote that you have it in a .xib file:
let loginVC = LoginViewController(nibName: yourNibName, bundle: nil)
Always have a weak reference to your delegate, otherwise you will have a retain cycle:
weak var delegate: MediaDataDelegate?
Also, you don't need to use public everywhere where you thought it might fit. Use it wisely and when needed. Here you don't need it. Remove it from everywhere in your LoginViewController

Delegate and Callback not working for passing Model data

I am trying to pass data from a firstVC to a second VC I have tried using delegate but it never worked (did not show required response) so I tried callback too and it now working so I am pasting both lines of code so any help is welcomed
Delegate:
protocol RatingDelegate: class {
func didLoadRating(ratings : [RatingModel])
}
the viewcontroller which the data would be passed from
ViewController A:
var delegate : RatingDelegate?
func showRatings(ratings: [RatingModel]) {
if delegate != nil {
delegate?.didLoadRating(ratings: ratings)
}
}
where the delegate value is supposed to me printed
RatingVC:
extension RatingVC: RatingDelegate {
func didLoadRating(ratings: [RatingModel]) {
log(ratings)
}
}
The callback Version
The view controller that would get the data
var ratingsCallBack: (() -> ([RatingModel]))?
the view controller which the value would be passed from
func showRatings(ratings: [RatingModel]) {
let ratingVC = RatingVC()
ratingVC.ratingsCallBack!() = {[unowned self] in
return ratings
}
}
this how ever throws a response saying
Expression is not assignable: function call returns immutable value
So the FirstVC passes data to RatingVC.
On FirstVC, at the point were you invoke RatingVC you should assign the delegate.
let ratingVC = RatingVC()
self.delegate = ratingVC //Here you specify RatingVC is the delegate variable
self.present(ratingVC, animated: true)
also
if delegate != nil {
}
is unnecessary, just do delegate?.didLoadRating(ratings: ratings) to keep it cleaner
EDIT: For the callback version is the same, just assign the value to the callback before initializing the view controller that sends the data.
It looks strange:
var ratingsCallBack: (() -> ([RatingModel]))?
should be something like this:
var ratingsCallBack: (([RatingModel]) -> ())?
so in case with callback:
class A: UIViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let ratingVC = RatingVC()
ratingVC.ratingsCallBack = { arr in
arr.forEach({ (model) in
print(model.rating)
})
}
navigationController?.pushViewController(ratingVC, animated: false)
}
}
class RatingVC: UIViewController {
var ratingsCallBack: (([RatingModel]) -> ())?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
#IBAction private func someButtonAction(_ sender: Any) {
let arr = [RatingModel.init(rating: 5), RatingModel()]
ratingsCallBack?(arr)
}
}
struct RatingModel {
var rating: Int = 1
}
Then when you press "someButton" you get this array in controller "A"

Not possible to transfer the data back to the ViewController

I am having issues trying to pass the data back to the ViewController (from BarCodeScannerViewController to TableViewController)
SecondVC (BarCodeScannerViewController.swift):
#objc func SendDataBack(_ button:UIBarButtonItem!) {
if let presenter = self.presentingViewController as? TableViewController {
presenter.BarCode = "Test"
}
self.dismiss(animated: true, completion: nil)
}
FirstVC (TableViewController.swift):
// The result is (BarCode - )
var BarCode: String = ""
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("BarCode - \(BarCode)")
}
Each time ViewWillAppear is running the value is not set, what could be causing this issue?
You should use the delegate pattern. I doubt in your code above that self.presentingViewController is actually set.
An example of using the delegate pattern for this:
// BarCodeScannerViewController.swift
protocol BarcodeScanningDelegate {
func didScan(barcode: String)
}
class BarCodeScannerViewController: UIViewController {
delegate: BarcodeScanningDelegate?
#objc func SendDataBack(_ button:UIBarButtonItem!) {
delegate?.didScan(barcode: "Test")
}
}
// TableViewController
#IBAction func scanBarcode() {
let vc = BarCodeScannerViewController()
vc.delegate = self
self.present(vc, animated: true)
}
extension TableViewController: BarcodeScanningDelegate {
func didScan(barcode: String) {
print("[DEBUG] - Barcode scanned: \(barcode)")
}
}

Clean Swift - Routing without segues

I found Router in Clean Swift architecture is responsible to navigate and pass data between view controllers. Some samples and articles depict that Routers use segue to communicate with view controllers. What would be the convenient design when I don't want to use any segue from Storyboard. Is it possible to pass data without segue in Clean Swift? If you describe with simplest complete example, would be appreciated.
Article says that you can:
// 2. Present another view controller programmatically
You can use this to manually create, configure and push viewController.
Example.
Let's pretend that you have ViewController with button (handle push):
final class ViewController: UIViewController {
private var router: ViewControllerRouterInput!
override func viewDidLoad() {
super.viewDidLoad()
router = ViewControllerRouter(viewController: self)
}
#IBAction func pushController(_ sender: UIButton) {
router.navigateToPushedViewController(value: 1)
}
}
This ViewController has router that implements ViewControllerRouterInput protocol.
protocol ViewControllerRouterInput {
func navigateToPushedViewController(value: Int)
}
final class ViewControllerRouter: ViewControllerRouterInput {
weak var viewController: ViewController?
init(viewController: ViewController) {
self.viewController = viewController
}
// MARK: - ViewControllerRouterInput
func navigateToPushedViewController(value: Int) {
let pushedViewController = PushedViewController.instantiate()
pushedViewController.configure(viewModel: PushedViewModel(value: value))
viewController?.navigationController?.pushViewController(pushedViewController, animated: true)
}
}
The navigateToPushedViewController func can takes any parameter you want (it is good to encapsulate parameters before configure new vc, so you may want to do that).
And the PushedViewController hasn't any specific implementation. Just configure() method and assert (notify you about missing configure() call):
final class PushedViewModel {
let value: Int
init(value: Int) {
self.value = value
}
}
final class PushedViewController: UIViewController, StoryboardBased {
#IBOutlet weak var label: UILabel!
private var viewModel: PushedViewModel!
func configure(viewModel: PushedViewModel) {
self.viewModel = viewModel
}
override func viewDidLoad() {
super.viewDidLoad()
assert(viewModel != nil, "viewModel is nil. You should call configure method before push vc.")
label.text = "Pushed View Controller with value: \(viewModel.value)"
}
}
Note: also, i used Reusable pod to reduce boilerplate code.
Result:
As above article explained you can use option 2/3/4 of navigateToSomewhere method as per your app design.
func navigateToSomewhere()
{
// 2. Present another view controller programmatically
// viewController.presentViewController(someWhereViewController, animated: true, completion: nil)
// 3. Ask the navigation controller to push another view controller onto the stack
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
// 4. Present a view controller from a different storyboard
// let storyboard = UIStoryboard(name: "OtherThanMain", bundle: nil)
// let someWhereViewController = storyboard.instantiateInitialViewController() as! SomeWhereViewController
// viewController.navigationController?.pushViewController(someWhereViewController, animated: true)
}
You need pass data across protocols
protocol SecondModuleInput {
// pass data func or variable
var data: Any? { get set }
}
protocol SecondModuleOutput {
// pass data func or variable
func send(data: Any)
}
First presenter
class FirstPresenter: SecondModuleOutput {
var view: UIViewController
var secondModuleInputHandler: SecondModuleInput?
// MARK: SecondModuleInput
func send(data: Any) {
//sended data from SecondPresenter
}
}
Second presenter
class SecondPresenter: SecondModuleInput {
var view: UIViewController
var secondModuleOutputHandler: SecondModuleOutput?
static func configureWith(block: #escaping (SecondModuleInput) -> (SecondModuleOutput)) -> UIViewController {
let secondPresenter = SecondPresenter()
secondPresenter.secondModuleOutputHandler = block(secondPresenter)
return secondPresenter.view
}
// Sending data to first presenter
func sendDataToFirstPresenter(data: Any) {
secondModuleOutputHandler?.send(data: data)
}
// MARK: FirstModuleInput
var data: Any?
}
Router
class FirstRouter {
func goToSecondModuleFrom(firstPresenter: FirstPresenter, with data: Any) {
let secondPresenterView = SecondPresenter.configureWith { (secondPreseter) -> (SecondModuleOutput) in
firstPresenter.secondModuleInputHandler = secondPreseter
return firstPresenter
}
//Pass data to SecondPresenter
firstPresenter.secondModuleInputHandler?.data = data
//Go to another view controller
//firstPresenter.view.present(secondPresenterView, animated: true, completion: nil)
//firstPresenter.view.navigationController.pushViewController(secondPresenterView, animated: true)
}
}

Resources