Function Overriding in iOS - ios

I have created BaseClassviewController and all my controllers are derived from this controller. I am doing the following steps:
Set custom delegate in BaseClassViewController.
Implement all function of protocol in BaseClassViewController.
Then I am pushing HomeController derived from BaseClassViewController.
Again I am pushing DetailController also derived from BaseClassViewController.
Now when delegate function is called I should get control in DetailController but I am getting control in HomeController.
So my question is why its not calling top controller at navigation i.e DetailController and is it possible to call delegate functions in both controllers?
P.S I am overriding delegate functions in all child controllers.
EDIT: After reading answers and comments I think I have not been clear that much so adding following code snippet.
In Helper Class:
#objc protocol SampleDelegate: class
{
#objc optional func shouldCallDelegateMethod()
}
class SampleHelper: NSObject
{
var sampleDelegate:SampleDelegate!
static var sharedInstance = SampleHelper()
//It is triggered
func triggerDelegateMethod()
{
sampleDelegate!.shouldCallDelegateMethod()
}
func apiCall()
{
let urlString = URL(string: "https://google.com")
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else {
if let usableData = data {
self. triggerDelegateMethod()
}
}
}
task.resume()
}
}
}
In BaseClass
class BaseClassViewController: UIViewController,SampleDelegate{
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(true)
SampleHelper.sharedInstance.delegate = self;
}
func shouldCallDelegateMethod()
{
//Override
}
}
In HomeController i.e 1st controller to be pushed
class HomeViewController: BaseClassViewController{
override func shouldCallDelegateMethod()
{
//
}
}
In DetailController i.e 2nd controller is pushed after HomeController from HomeController.
class DetailViewController: BaseClassViewController{
override func viewDidLoad()
{
super.viewDidLoad()
SampleHelper.sharedInstance.apiCall()
}
override func shouldCallDelegateMethod()
{
//
}
}
Now my question is when delegate is triggered from helper class it calls shouldCallDelegateMethod in HomeViewController but not in DetailViewController. But DetailViewController is at top of navigation array.
Also is there any possibility I can trigger same function in both controller at a time with delegate only?

In BaseClassviewController you should have a delegate variable/property.
In HomeController and DetailController you need to set that delegate variable/property to self if you want that class to be listening to the delegate callbacks.

The basic problem is that you are using delegate with a singleton.
Setting the delegate in viewWillAppear is not a good solution either. In short, when view controllers are being shown and hidden, the delegate on your singleton will changed all the time.
Don't use delegates with singletons. Use a completion callback. Otherwise you will keep running into problems.
func apiCall(onCompletion: (() -> Void)?) {
let urlString = URL(string: "https://google.com")
if let url = urlString {
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error)
} else if let usableData = data {
onCompletion?()
}
}
task.resume()
}
}
called as
SampleHelper.apiCall {
// do something
}

Edit 2
After you posted your code, i realize that you have used the singleton class for delegation.
Delegates allows an object to send a message to another object.
Answer for your query is "No". You can not trigger same function in both controller at a time with delegate.
If you really want to listen an event in both class at a time, i would suggest you to use NSNotificationCenter instead of delegate.

Thats not the correct way to achieve this. I think proper way to set delegate only in respective UIViewController rather than implementing that protocol on BaseViewController and then overriding in child classes. So your implementation should be like.
In HomeViewController
class HomeViewController: BaseClassViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
SampleHelper.sharedInstance.delegate = self;
}
func shouldCallDelegateMethod() {
// Provide implementation
}
}
In DetailViewController
class DetailViewController: BaseClassViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewDidLoad()
SampleHelper.sharedInstance.delegate = self;
}
func shouldCallDelegateMethod() {
// Provide implementation
}
}
Using this imeplementation you will be having only one-to-one communication design pattern, ensuring right UIViewController to be called.

Related

How to wait for a function to be finished that is already running

I have a class that will do some network requests. On init() I load some initial data. So the class looks like this:
class NetworkHandler {
init() {
loadData()
}
func loadData() {
// Do an asynchronous function to load initial data
}
}
I pass an object of this class to a ViewController. In this ViewController I want to show a loading indicator until the initial load is finished. Next I want to show a normal screen. So like this:
class viewController: UIViewController {
var networkHandler: NetworkHandler?
override func viewDidLoad() {
super.viewDidLoad()
if networkHandler.initialLoadIsDone {
// Show something
} else {
// Show a loading indicator
// Listen on networkHandlers initial load
// On initial load done: Show somethin
}
}
}
So the first step if the initial load is finished or not I could handle with a local variable in networkHandler. But as I do not call the initial load function I cannot use a completionHandler to wait for the initial load to be finished. So I am wondering what's the best way to wait for the initial load to be finished? Also, can I replace the local variable solution by this?
Thanks for any help
Don't wait. Do notify.
For example use protocol / delegate to inform the target class about the stages
protocol NetworkHandlerProtocol {
func didStartLoading()
func didFinishInitialLoading(with data: Data)
}
class NetworkHandler {
var delegate : NetworkHandlerProtocol
init(delegate : NetworkHandlerProtocol) {
self.delegate = delegate
}
func loadData() {
delegate.didStartLoading()
// Do an asynchronous function to load initial data
let data = // some Data object
delegate.didFinishInitialLoading(with: data)
}
}
In the controller adopt the protocol and implement the methods
class ViewController: UIViewController {
lazy var networkHandler = NetworkHandler(delegate : self)
override func viewDidLoad() {
super.viewDidLoad()
networkHandler.loadData()
}
}
extension ViewController : NetworkHandlerProtocol {
func didStartLoading() { }
func didFinishInitialLoading(with data: Data) { }
}

Swift 3 : Back to last ViewController with sending data [duplicate]

This question already has answers here:
Passing data between view controllers
(45 answers)
Closed 5 years ago.
I'm trying to go back to my las viewController with sending data, but it doesn't work.
When I just use popViewController, I can go back to the page, but I can't move my datas from B to A.
Here is my code :
func goToLastViewController() {
let vc = self.navigationController?.viewControllers[4] as! OnaylarimTableViewController
vc.onayCode.userId = taskInfo.userId
vc.onayCode.systemCode = taskInfo.systemCode
self.navigationController?.popToViewController(vc, animated: true)
}
To pass data from Child to parent Controller, you have to pass data using Delegate pattern.
Steps to implement delegation pattern, Suppose A is Parent viewController and B is Child viewController.
Create protocol, and create delegate variable in B
Extend protocol in A
pass reference to B of A when Push or Present viewcontroller
Define delegate Method in A, receive action.
After that, According to your condition you can call delegate method from B.
You should do it using delegate protocol
class MyClass: NSUserNotificationCenterDelegate
The implementation will be like following:
func userDidSomeAction() {
//implementation
}
And ofcourse you have to implement delegete in your parent class like
childView.delegate = self
Check this for more information
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Protocols.html
You have to send back to last ViewController with 2 options.
1. Unwind segue. (With use of storyboard)
You can refer this link.
2. Use of delegate/protocol.
You can refer this link.
Also this link will be useful for you.
You can use Coordinator Pattern
For example, I have 2 screens. The first displays information about the user, and from there, he goes to the screen for selecting his city. Information about the changed city should be displayed on the first screen.
final class CitiesViewController: UITableViewController {
// MARK: - Output -
var onCitySelected: ((City) -> Void)?
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
onCitySelected?(cities[indexPath.row])
}
...
}
UserEditViewController:
final class UserEditViewController: UIViewController, UpdateableWithUser {
// MARK: - Input -
var user: User? { didSet { updateView() } }
#IBOutlet private weak var userLabel: UILabel?
private func updateView() {
userLabel?.text = "User: \(user?.name ?? ""), \n"
+ "City: \(user?.city?.name ?? "")"
}
}
And Coordinator:
protocol UpdateableWithUser: class {
var user: User? { get set }
}
final class UserEditCoordinator {
// MARK: - Properties
private var user: User { didSet { updateInterfaces() } }
private weak var navigationController: UINavigationController?
// MARK: - Init
init(user: User, navigationController: UINavigationController) {
self.user = user
self.navigationController = navigationController
}
func start() {
showUserEditScreen()
}
// MARK: - Private implementation
private func showUserEditScreen() {
let controller = UIStoryboard.makeUserEditController()
controller.user = user
controller.onSelectCity = { [weak self] in
self?.showCitiesScreen()
}
navigationController?.pushViewController(controller, animated: false)
}
private func showCitiesScreen() {
let controller = UIStoryboard.makeCitiesController()
controller.onCitySelected = { [weak self] city in
self?.user.city = city
_ = self?.navigationController?.popViewController(animated: true)
}
navigationController?.pushViewController(controller, animated: true)
}
private func updateInterfaces() {
navigationController?.viewControllers.forEach {
($0 as? UpdateableWithUser)?.user = user
}
}
}
Then we just need to start coordinator:
coordinator = UserEditCoordinator(user: user, navigationController: navigationController)
coordinator.start()

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/

Class protocols not working after updating from Swift 2.3 to Swift 3.0

I have a very basic user class, who os responsible for get user data from Firebase and update the currently screen if needed, everything was working until a decided to update my project to Swift 3.0
This is the User Class
#objc protocol userClassProtocol {
func updateScreen()
#objc optional func sucessUnlockedCategory()
}
class User {
static let sharedInstance = User()
internal var delegate : userClassProtocol?
func fakeClassThatGetsDataFromFirebase() {
//Got data
print("Has new data")
self.delegate?.updateScreen()
}
}
And here is the ViewController:
class FirstViewController: UIViewController, userClassProtocol {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
print("View will load")
User.sharedInstance.delegate = self
}
func updateScreen() {
print("Screen is going to update")
//Do stuff here
}
}
The logs i get from this are:
Has new Data
View Will Appear
But the function updateScreen() in the view controller never gets called. No errors are being pointed out by Xcode.
Looks like it's just an issue with the timing of your method calls.
Your fakeClassThatGetsDataFromFirebase method is called first, and at that point, your delegate hasn't been set. So self.delegate is nil when calling:
self.delegate?.updateScreen()
This will only work if your viewWillAppear gets called before fakeClassThatGetsDataFromFirebase
It shouldn't get called, according to your code. Nothing calls fakeClassThatGetsDataFromFirebase(), which is what should call updateScreen() on your delegate method.

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