首页 > 解决方案 > 如何在 Instagram 的分享流程中打开图片?

问题描述

我正在尝试在 Instagram 的共享流程中打开图像,而无需将图像下载到照片库中。这两种方法有效,但它们有缺点:

第一种方法:这种方法将图像保存在临时位置。然后它UIDocumentInteractionController用于在 Instagram 的共享流程中打开图像。这里的问题是,一旦UIDocumentInteractionController出现,就会显示多个应用程序,我想避免这种情况。

var documentController: UIDocumentInteractionController!
func shareToInstagram(image: UIImage) {
        DispatchQueue.main.async {
            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)
                documentController = UIDocumentInteractionController(url: fileURL) 
                documentController.uti = "com.instagram.exlusivegram"
                documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)

            } else {
                print(" Instagram is not installed ")
            }
        }
    }

第二种方法:这是一种很好的方法,因为它不使用UIDocumentInteractionController,而是立即在 Instagram 共享流中打开图像。这种方法的问题是您必须首先将图像保存到照片库中,这是我想避免的。

func shareImage() {
        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        guard let lastAsset = fetchResult.firstObject else { return }
        let localIdentifier = lastAsset.localIdentifier
        let u = "instagram://library?LocalIdentifier=" + localIdentifier
        let url = URL(string: u)!
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            print("Error")
        }
    }

我想知道是否有一种方法可以使用第二种方法而不必将图像保存到照片库中?第一种方法似乎首先将其保存到临时目录中,是否可以在第二种方法中执行此操作?

谢谢

标签: swiftxcodefacebookinstagramphasset

解决方案


推荐阅读