I am trying to implement a UIPageViewController with some initialization steps encapsulated in another base class.
As multiple inheritance is impossible in Swift, I am trying to go with protocols but I would like to trigger some initialization steps encapsulated in a base class.
Here is the base controller I wrote.
It encapsulates Facebook Account Kit plugin to hide connection infos that should not be seen from my child VC (e.g. the import AccountKit directive, the AKFAccountKit class instance).
When I use that in a standard class it works :
class ClientViewController: AccountKitBaseViewController { /*...*/ }
extension ClientViewController: AccountKitBaseViewControllerDelegate {/*...*/}
But I cannot use it if I use a PageVC as client class :
class ClientViewController: UIPageViewController, AccountKitBaseViewController { /* Error: Multiple inheritance from classes 'UIPageViewController' and 'AccountKitBaseViewController'*/ }
extension ClientViewController: AccountKitBaseViewControllerDelegate {/*...*/}
How can I manage to do it ?
I would like to advice you put all logic from AccountKitBaseViewController
to some assistant class and add instance of this class to your controllers. It will help you to avoid code duplication. You can use the following assistant class:
class SocialNetworkAssistant {
//Put here all required propertie from AccountKitBaseViewController
public var delegate: AccountKitBaseViewControllerDelegate?
public var isUserLoggedIn: Bool = false
private var _accountKit: AKFAccountKit!
private var _pendingLoginViewController: AKFViewController?
//Put here all required methods from AccountKitBaseViewController
public func accountKitLogout(completion: (() -> Swift.Void)? = nil) {
guard isUserLoggedIn == true else { return }
isUserLoggedIn = false
_accountKit?.logOut()
completion?()
}
// ... and so on
}
And then you can put instance of SocialNetworkAssistant
in your controllers:
class ClientViewControllerFirst : UIViewController, AKFViewControllerDelegate {
private let socialNetworkAssistantInstance = SocialNetworkAssistant()
/* AKFViewControllerDelegate methods implementation */
}
class ClientViewControllerSecond : UIPageViewController, AKFViewControllerDelegate {
private let socialNetworkAssistantInstance = SocialNetworkAssistant()
/* AKFViewControllerDelegate methods implementation */
}
You can also use the bridge pattern. Make SocialNetworkAssistant
as a base class for all classes that will implement AKFViewControllerDelegate
instead of your controllers. Then you will use different subclasses of SocialNetworkAssistant
in your controllers.