Search code examples
swiftuiactivityviewcontroller

Share content with UIActivityViewController


In my app exists user-generated content such as a home for rent listing. I would like for other users to share a post/listing to imessages. And when the recipient taps the message it can open the exact same post within the app if the app is downloaded or take them to the app store. I have seen this functionality before but I am unsure what direction to go in. With my current code I can present the activity controller and send a imessage. Can anyone point me in the right direction?

  @objc func sharePost(){
        print("Share home")
        let items = ["Check out this house!"]
        let activityController = UIActivityViewController(activityItems: items, applicationActivities: nil)
        present(activityController, animated: true)
        
    }

Solution

  • You're going to want either a custom url scheme (ie myapp://contentID) or a universal link (ie https://myapp.com/contentID).

    Custom URL Schemes

    With a custom URL scheme (which is the closest to the example you gave), the URL tells the system to open the app associated with that type of URL. You can parse the section after the scheme (ie contentID in my examples) to see what to present to the user. See Apple's documentation: https://developer.apple.com/documentation/xcode/allowing_apps_and_websites_to_link_to_your_content/defining_a_custom_url_scheme_for_your_app

    Universal Links

    With Universal Links, you give a link to your website. If the user has the associated app downloaded, the page will open in the app instead of the website. The advantage here as that users can still see content even if they don't have the app. See documentation here: https://developer.apple.com/ios/universal-links/


    In either scenario, you'll be passing a URL to your UIActivityViewController. In the case of universal links, if you implement OpenGraph tags, you'll also get those nice preview images next to the links for free (in iMessages, say).

    How you implement the navigation to the content within your app is an architectural decision and depends on a lot of factors about how you have navigation set up, etc