If your SDK needs to be compatible with app extensions, then UIApplication
will be unavailable for you to use.
To work around this, while also giving the host application greater control, you can implement a delegate which presents the view controller for the SDK.
The host application can implement the delegate and choose the most appropriate controller, including using the root view controller as recommended by Mark.
First declare a protocol:
public protocol MySDKPopupDelegate: NSObjectProtocol {
func presentPopupViewController(viewController: UIViewController)
}
Define a way to set the delegate in the SDK:
public class MySDKConfig {
public let sharedConfig = MySDKConfig
weak var delegate: MySDKPopupDelegate?
}
When your SDK needs to present the video, request the view controller from the delegate:
func showPopupForVideo(url: NSURL) {
let viewController = viewControllerForVideo(url)
delegate?.presentPopupViewController(videoViewController)
}
Finally, the host application should implement the delegate method to actually present the view controller, for example, in the AppDelegate:
class AppDelegate: NSObject, MySDKPopupDelegate {
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
MySDKConfig.sharedConfig.delegate = self
}
func presentPopupViewController(viewController: UIViewController) {
guard let presentingViewController = window?.rootViewController else {
return
}
presentingViewController.presentViewController(viewController, animated: true, completion: nil)
}
}
The delegate can also be implemented in a specific view controller, including in an app extension:
class ShareViewController: UIViewController, MySDKPopupDelegate {
override public func viewDidLoad() {
MySDKConfig.sharedConfig.delegate = self
}
func presentPopupViewController(viewController: UIViewController) {
presentViewController(viewController, animated: true, completion: nil)
}
}