在iOS Swift上发布到Instagram屏幕

时间:2019-03-17 21:01:50

标签: ios swift facebook instagram

我正在尝试简化从我的应用程序到Instagram的共享。我想要的是进入下面的屏幕截图所示的屏幕。我已经尝试过instagram-stories:// share deeplink,并且已经阅读了所有这些文档:https://developers.facebook.com/docs/instagram/sharing-to-stories/

但是,无论我做什么,当url方案动作触发时,它都会直接将图像共享到故事中。我在这里想念什么?

enter image description here

这是我的代码摘录:

           if let image = image {
                guard let urlScheme = URL(string: "instagram-stories://share"),
                    let imageData = image.pngData() else {
                    return
                }

                if UIApplication.shared.canOpenURL(urlScheme) {
                    let pasterboardItems = [["com.instagram.sharedSticker.backgroundImage": imageData]]
                    let pasterboardOptions = [UIPasteboard.OptionsKey.expirationDate: Date().addingTimeInterval(60*5)]

                    UIPasteboard.general.setItems(pasterboardItems, options: pasterboardOptions)

                    UIApplication.shared.open(urlScheme, options: [:], completionHandler: nil)
                }
            }

2 个答案:

答案 0 :(得分:1)

  1. 假设您的image是“ png”
  2. 假设您允许 您info.plist中的“ instagram故事”(键LSApplicationQueriesSchemes

答案 1 :(得分:1)

您需要做的是使用以下URL打开Instagram应用:
instagram://library?LocalIdentifier=并作为参数PHAsset.localIdentifier传递。
由于某种原因,此挂钩未在文档?‍♂️

中的任何地方列出

但是为了接收图像/视频的本地标识符,您必须首先将图像/视频保存到用户的照片库。 所以最终代码看起来像这样

let videoFileUrl: URL = URL(fileURLWithPath: "path/to/my/video")!
var localId: String?
PHPhotoLibrary.shared().performChanges({
    let request = PHAssetChangeRequest.creationRequestForAssetFromVideo(atFileURL: videoFileUrl)
    localId = request?.placeholderForCreatedAsset?.localIdentifier
}, completionHandler: { success, error in
    // completion handler is called on an arbitrary thread
    // but since you (most likely) will perform some UI stuff
    // you better move everything to the main thread.
    DispatchQueue.main.async {
        guard error == nil else {
            // handle error
            return
        }
        guard let localId = localId else {
            // highly unlikely that it'll be nil,
            // but you should handle this error just in case
            return
        }

        let url = URL(string: "instagram://library?LocalIdentifier=\(localId)")!
        guard UIApplication.shared.canOpenURL(url) else {
            // handle this error
            return
        }
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
})