web-dev-qa-db-fra.com

Comment partager une image sur Instagram? Swift

Désolé pour la question sans code, mais je n'ai trouvé aucun endroit où chercher. Je veux partager l'image avec le titre sur Instagram? Comment puis je faire ça?

Toute aide serait formidable

17
user4790024

si vous ne voulez pas utiliser UIDocumentInteractionController

mise à jour Swift 5

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)
            }

        }
}
15
Zuhair Hussain
    class viewController: UIViewController, UIDocumentInteractionControllerDelegate {

    var yourImage: UIImage?
    var documentController: UIDocumentInteractionController!

    func shareToInstagram() {

     let instagramURL = NSURL(string: "instagram://app")

            if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) {

                let imageData = UIImageJPEGRepresentation(yourImage!, 100)

                let captionString = "caption"

           let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")
           if imageData?.writeToFile(writePath, atomically: true) == false {

                    return

                } else {
   let fileURL = NSURL(fileURLWithPath: writePath)

                    self.documentController = UIDocumentInteractionController(URL: fileURL)

                    self.documentController.delegate = self

                    self.documentController.UTI = "com.instagram.exlusivegram"

                    self.documentController.annotation = NSDictionary(object: captionString, forKey: "InstagramCaption")
                          self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true)

                }

            } else {
                print(" Instagram isn't installed ")
            }
        }
     }

    }

Maintenant, cela ne fonctionnera toujours pas avec iOS 9, vous devrez donc aller dans vos applications info.plist, ajouter le type "LSApplicationQueriesSchemes": Array, et ajouter le schéma d'URL dans ce cas "instagram".

12
user4341849

Swift 3. Version:

 @IBAction func shareInstagram(_ sender: Any) {

        DispatchQueue.main.async {

            //Share To Instagram:
            let instagramURL = URL(string: "instagram://app")
            if UIApplication.shared.canOpenURL(instagramURL!) {

                let imageData = UIImageJPEGRepresentation(image, 100)
                let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo")

                do {
                    try imageData?.write(to: URL(fileURLWithPath: writePath), options: .atomic)
                } catch {
                    print(error)
                }

                let fileURL = URL(fileURLWithPath: writePath)
                self.documentController = UIDocumentInteractionController(url: fileURL)
                self.documentController.delegate = self
                self.documentController.uti = "com.instagram.exlusivegram"

                if UIDevice.current.userInterfaceIdiom == .phone {
                    self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
                } else {
                    self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true)
                }
            } else {
                print(" Instagram is not installed ")
            }
        }
    }
11
Mc.Lover

Ici essayez ce code

    @IBAction func shareContent(sender: UIButton) {

              let image = UIImage(named: "imageName")
            let objectsToShare: [AnyObject] = [ image! ]
            let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
            activityViewController.popoverPresentationController?.sourceView = self.view 


            activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ]


            self.presentViewController(activityViewController, animated: true, completion: nil)

            }
        }
4
Anirudh R.Huilgol.