How to share image in instagram?Swift

user4790024 picture user4790024 · Jul 10, 2015 · Viewed 21.2k times · Source

Sorry for the question without a code.But i didn't find anywhere to look for. I want to share image with title in instagram? How can i do that?

Any help would be great

Answer

Zuhair Hussain picture Zuhair Hussain · Jul 24, 2016

if you don't want to use UIDocumentInteractionController

SWIFT 5 update

import Photos
...

func postImageToInstagram(image: UIImage) {
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if error != nil {
            print(error)
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if let lastAsset = fetchResult.firstObject as? PHAsset {

            let url = URL(string: "instagram://library?LocalIdentifier=\(lastAsset.localIdentifier)")!

            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                self.present(alertController, animated: true, completion: nil)
            }

        }
}