Search code examples
iosswiftuiviewcontrollerios-extensionsuiresponder

iOS Action Extension not opening my main app


I want to be able to open Safari links in my app. For this I have created an Action Extension. I have tried multiple variations of the following code to test but none of them open my main app:

First try:

func openContainerApp() {
        var responder: UIResponder? = self as UIResponder
        let selector = #selector(openURL(_:))
        while responder != nil {
            if responder!.responds(to: selector) && responder != self {
                responder!.perform(selector, with: URL(string: "awesome://item?id=20036169")!)
            }
            responder = responder?.next
        }
        self.extensionContext!.completeRequest(returningItems: [], completionHandler: nil)
    }

Second try:

func redirectToHostApp() {
        let url = URL(string: "awesome://item?id=20036169")
        let selectorOpenURL = sel_registerName("openURL:")
        let context = NSExtensionContext()
        context.open(url! as URL, completionHandler: nil)

        var responder = self as UIResponder?

        while (responder != nil){
            if responder?.responds(to: selectorOpenURL) == true{
                responder?.perform(selectorOpenURL, with: url)
            }
            responder = responder!.next
        }

    }

I have added the "awesome" URL scheme in my main app. I am also returning "true" for all possible openURL delegate methods in my app delegate:

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return true
    }

    func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return true
    }

I have set the NSExtensionActivationSupportsWebURLWithMaxCount in my action extension to 1.

Despite all this, my main app doesn't open. Tapping on the action extension in Safari does nothing.

I have tried these solutions but none work:

https://stackoverflow.com/a/28037297/1634905

https://forums.developer.apple.com/thread/65621


Solution

  • I figured it out by myself and wanted to share this in case someone gets stuck with the same.

    My problem was that I was calling the openContainerApp or redirectToHostApp functions from viwDidLoad() where the UIResponder is apparently not ready yet.

    I moved the function call to viewWillAppear() and it worked.

    override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            openContainerApp()
    }