Skip to content

Instantly share code, notes, and snippets.

@boehs
Last active March 19, 2024 20:39
Show Gist options
  • Save boehs/70159bf8c5d5ed565778f17448a7f59f to your computer and use it in GitHub Desktop.
Save boehs/70159bf8c5d5ed565778f17448a7f59f to your computer and use it in GitHub Desktop.
Open Mastodon URL iOS SwiftUI

For my app, Love Your Music, I want a link to my mastodon, https://social.coop/@eb (wink wink).

On iOS, only one app can handle each URL scheme, so it's hard to know what app to open. Lets chain the apps together. Unfortunately, this means the user cannot select the default preference. To compensate, we first try the Opener app, then chain to ivory, ice cubes, then mastodon's official app, ending at the browser.

The SwiftUI open link chain is not needed for email as users can set their default mail app.

struct MastodonLinker {
var instance: String
var user: String
@Environment(\.openURL) private var openURL
func openMastodonLink() {
let urls = [
"opener://x-callback-url/show-options?url=https%3A%2F%2F\(instance)%2F\(user)",
"ivory://\(instance)/@\(user)",
"icecubesapp://\(instance)/@\(user)",
"mastodon://profile/\(user)@\(instance)",
"https://\(instance)/@\(user)",
]
openURLs(urls)
}
private func openURLs(_ urls: [String]) {
guard let url = URL(string: urls.first ?? "") else {
return
}
openURL(url) { canOpen in
if !canOpen {
let remainingURLs = Array(urls.dropFirst())
if !remainingURLs.isEmpty {
self.openURLs(remainingURLs)
}
}
}
}
}
#Preview {
List {
Button {
MastodonHandler(instance: "social.coop", user: "eb").openMastodonLink()
} label: {
Label("Follow my Mastodon", systemImage: "pawprint")
}.foregroundStyle(Color(hex: "6364FF").gradient)
Button {
if MFMailComposeViewController.canSendMail() {
isShowingMailView.toggle()
} else {
openURL(URL(string: "mailto:evan (you know what goes here) boehs.org")!)
}
} label: {
Label("Contact me", systemImage: "at")
}.foregroundStyle(.green.gradient)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment