Delegate and Callback not working for passing Model data - ios

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"

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)
}
}

Protocol function sends the value back to the first VC but does not set it to the variables

I am learning IOS, and I have three view controllers A, B and C, and I can access C from B and B from A, then I send back data using this delegate method from C to A then I want to use these received data in A, and finally update the text in the textView of VC A, but it always updates the textView using the default values not the received ones.
class A
protocol isAbleToReceiveData{
func pass(book: String, chapter: Int)
}
class AViewController: UIViewController, isAbleToReceiveData{
var verses: [DBTVerse] = []
var text: String = ""
var currentBook: String = "Test"
var currentChapter: Int = 1
#IBOutlet weak var TextView: UITextView!
func pass(book: String, chapter: Int) {
self.currentBook = book
self.currentChapter = chapter
print(currentBook, currentChapter)
// current output is ok "the received data"
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
getVerses(book: self.currentBook, Chapter: NSNumber(value: self.currentChapter))
print(currentBook, currentChapter)
// current output "test" "1" while it should be the received data
}
func data(verses: [DBTVerse]) {
for verse in verses{
if let chapter: Int = verse.verseId?.intValue{
text.append(String(chapter))
text.append(verse.verseText)
}
}
updateData(text: text)
}
func updateData(text: String){
if let textView = self.versesTextView {
textView.text = text
textView.setNeedsDisplay()
}
}
func getVerses(book: String, Chapter: NSNumber) {
DBT.getTextVerse(withDamId: "ARBWTCO1ET", book: book, chapter: Chapter, verseStart: nil, verseEnd: nil, success: { (verse) in
if let verse = verse {
self.verses = verse as! [DBTVerse]
self.data(verses: self.verses)
}
}) { (error) in
if let error = error {
print("Error \(error)")
}
}
}
}
class C
class CTableViewController: UITableViewController {
var currentBook: String = ""
var chapters: [DBTChapter] = []
var AVC = AViewController()
var delegate: isAbleToReceiveData?
override func viewDidLoad() {
super.viewDidLoad()
self.delegate = AVC
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let selectedChapter = Int(chapters[indexPath.row].chapterId) {
doDismiss(book: currentBook, chapter: selectedChapter)
}
}
func doDismiss(book: String, chapter: Int) {
if let delegate = self.delegate{
delegate.pass(book: book, chapter: chapter)
}
// Use presentingViewController twice to go back two levels and call
// dismissViewController to dismiss both viewControllers.
self.presentingViewController?.presentingViewController?.dismiss(animated: true, completion: nil)
}
So in general A receives the data but it does not override it to the variable so I can use it later or in the viewWillAppear.
You have to tell to next Viewcontroller who is it delegate like so if you are in A VC ande B goes trhow a segue then add in A viewController
class AViewController: UIViewController, isAbleToReceiveData{
//all class details
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToClassB"{
let vc = segue.destination as! bViewController
vc.delegate = self
}
}
in class B then you have a new property like c with
class b: UIVIewcontroller{
var delegate: isAbleToReceiveData?
So in the func to segue to next viewController c VC add this func
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToClassC"{
let vc = segue.destination as! CTableViewController
vc.delegate = self.delegate
}
}

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

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")
}
}

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