Search code examples
iosswiftuiapplication

How can I handle a user clicking cancel when prompted to open another app


I have a requirement to open a tweet in my app, if the user has twitter installed, open in Twitter, otherwise present a webview and render the tweet.

I am able to achieve this essentially with the below. It works and I am happy with it.

However when initially prompted to open in Twitter, should the user click cancel, I'd like to present the webview instead. Currently however if the user clicks cancel, nothing happens and they need to tap the tweet item in there feed again.

Is it possible to have a fallback should the user click cancel in the message?

   func didSelectItemInFeed(_ selected: FeedItem) {
        switch selected.item.type {
        case .companyNews:
           ....
        case .tweet:
            guard
                let username = selected.item.tweet?.displayName,
                let appURL = URL(string: "twitter://status?id=\(selected.item.externalId)"),
                let webURL = URL(string: "https://twitter.com/\(username)/status/\(selected.item.externalId)")
                else { return }

            let application = UIApplication.shared

            if application.canOpenURL(appURL as URL) {
                application.open(appURL as URL)
            } else {
                presentWebView(webURL)
            }
        default:
            break
        }
    }

Solution

  • Complete your function with: application.open(appURL as URL, completionHandler: {isSuccess in})()

        func didSelectItemInFeed(_ selected: FeedItem) {
            switch selected.item.type {
            case .companyNews:
                ....
            case .tweet:
                guard
                    let username = selected.item.tweet?.displayName,
                    let appURL = URL(string: "twitter://status?id=\(selected.item.externalId)"),
                    let webURL = URL(string: "https://twitter.com/\(username)/status/\(selected.item.externalId)")
                    else { return }
    
                let application = UIApplication.shared
    
                if application.canOpenURL(appURL as URL) {
                    application.open(appURL as URL, completionHandler: { isSuccess in
                        // print here does your handler open/close : check 'isSuccess'
                    })()
                } else {
                    presentWebView(webURL)
                }
            default:
                break
            }
        }