Using ShareLink in SwiftUI to create item text with URL link formatted for both the Message app and email

620 views Asked by At

My need is to use ShareLink to allow the user to send formatted email or text message including a URL link. My SwiftUI code looks like:

    ShareLink(
        item: itemText,
        subject: Text("Message from app user"),
        preview: SharePreview("Link",image: "AppIcon")) {
        Label(message, systemImage:  "square.and.arrow.up")
    }

where I'm generating itemText from itemText(link: URL) (I've trimmed the string I'm using to just the basics):

    func shareItemMessage(link: URL) -> String {
        return
            "Please join me on our app\n\n"
            + "Tap on [link](\(link)) to accept my invitation (link: \(link)).\n\n"
    }

    func itemText(link: URL) -> (some Transferable)? {
        // The `available` condition is needed because only in iOS 16.1 does AttributedString conform to Transferable.
        if #available(iOS 16.1, *) {
            // The AttributedString options below enable inclusion of whitespace in the text formatting.
            // See also https://forums.macrumors.com/threads/markdown-linebreaks-are-ignored.2367417/
            return try? AttributedString(markdown: shareItemMessage(link: link),
                options: AttributedString.MarkdownParsingOptions(
                    allowsExtendedAttributes: false,
                    interpretedSyntax: .inlineOnlyPreservingWhitespace,
                    failurePolicy: .returnPartiallyParsedIfPossible,
                    languageCode: nil
                ))
        } else {
            return shareItemMessage(link: link)
        }
    }

My problem is that the markdown gets stripped out when the user chooses the message app. Example:

enter image description here

And when they use an email, I get two links. Example:

enter image description here

Note that I've generated the image examples above running on an iPhone with > iOS 16.1, so it's using the AttributedString formatting for both the message and email.

Has anyone come up with a better way to do this? i.e., to use ShareLink to send a text email or message with a link?

0

There are 0 answers