Skip to content

Instantly share code, notes, and snippets.

Created July 6, 2021 11:48
Show Gist options
  • Save shaundon/28d121931eab29d4feb1f61b21b60e28 to your computer and use it in GitHub Desktop.
Save shaundon/28d121931eab29d4feb1f61b21b60e28 to your computer and use it in GitHub Desktop.
Proof of concept of sharing to Instagram Stories from SwiftUI
import SwiftUI
struct InstagramShareView: View {
var imageToShare: Image {
// An image defined in your app's asset catalogue.
return Image("SomeImage")
var body: some View {
VStack {
// Display the image that will be shared to Instagram.
if InstagramSharingUtils.canOpenInstagramStories {
Button(action: { InstagramSharingUtils.shareToInstagramStories(imageToShare.uiImage) }) {
Text("Share to Instagram Stories")
} else {
Text("Instagram is not available.")
See for full reference.
import Foundation
import SwiftUI // You can import UIKit instead if you like, both will work.
struct InstagramSharingUtils {
// Returns a URL if Instagram Stories can be opened, otherwise returns nil.
private static var instagramStoriesUrl: URL? {
if let url = URL(string: "instagram-stories://share?source_application=uk.sdonnelly.personal-best-0") {
if UIApplication.shared.canOpenURL(url) {
return url
return nil
return nil
// Convenience wrapper to return a boolean for `instagramStoriesUrl`
static var canOpenInstagramStories: Bool {
return instagramStoriesUrl != nil
// If Instagram Stories is available, writes the image to the pasteboard and
// then opens Instagram.
static func shareToInstagramStories(_ image: UIImage) {
// Check that Instagram Stories is available.
guard let instagramStoriesUrl = instagramStoriesUrl else {
// Convert the image to data that can be written to the pasteboard.
let imageDataOrNil = UIImage.pngData(image)
guard let imageData = imageDataOrNil() else {
Logging.error("🙈 Image data not available.")
let pasteboardItem = ["com.instagram.sharedSticker.backgroundImage": imageData]
let pasteboardOptions = [UIPasteboard.OptionsKey.expirationDate: Date().addingTimeInterval(60 * 5)]
// Add the image to the pasteboard. Instagram will read the image from the pasteboard when it's opened.
UIPasteboard.general.setItems([pasteboardItem], options: pasteboardOptions)
// Open Instagram., options: [:], completionHandler: nil)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment