Elena Zherdeva
Elena Zherdeva

Reputation: 150

Social sharing in Swift

I'm writing a function that when a button is clicked makes a screenshot, and then lets you share this photo on Twitter, Instagram and Facebook. So I have a function for all apps EXCEPT Instagram:

func socialShare(sharingText: String?, sharingImage: UIImage?) {
    var sharingItems = [AnyObject]()

    if let text = sharingText {
        sharingItems.append(text as AnyObject)
    }
    if let image = sharingImage {
        sharingItems.append(image)
    }
    let activityViewController = UIActivityViewController(activityItems: sharingItems, applicationActivities: nil)

    activityViewController.excludedActivityTypes = [UIActivityType.addToReadingList, UIActivityType.print, UIActivityType.assignToContact, UIActivityType.copyToPasteboard]

    self.present(activityViewController, animated: true, completion: nil)
}

And also function for Instagram sharing:

var docController: UIDocumentInteractionController!

func documentsDirectory() -> String {
    return NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
}

func postImageToInstagram(sharingImage: UIImage?) {



    let instagram = URL(string: "instagram://app")!


    if UIApplication.shared.canOpenURL(instagram) {


        let imageURL = URL(fileURLWithPath: documentsDirectory())

        let fullPath = imageURL.appendingPathComponent("instagram.igo")

        do {
            try UIImagePNGRepresentation(sharingImage!)!.write(to: fullPath)

            let rect = CGRect(x: 0, y: 0, width: 0, height: 0)

            let igImageHookFile = URL(string: "file://\(fullPath)")

            docController = UIDocumentInteractionController(url: igImageHookFile!)

            docController.uti = "com.instagram.photo"
            docController.presentOpenInMenu(from: rect, in: self.view, animated: true)
        } catch {
            print(error)
        }  
    }
    else {
        print("Instagram not installed")
    }

}

How I can use it together? Because they work only separately...

Upvotes: 1

Views: 1454

Answers (1)

Brandon A
Brandon A

Reputation: 8279

I have found that it is slightly annoying that Instagram is not included in the default UIActivityViewController activities. But that does not mean that you can't add your own UIActivity for Instagram and the logic you already have to post to Instagram in your already created method. See this post from SO on how to create your own UIActivitys. It even includes a link to a fancy GitHub repo that has custom UIActivitys for most of the left out social services, including Instagram.

Upvotes: 1

Related Questions