Post To Instagram screen on iOS Swift

只谈情不闲聊 提交于 2019-12-05 15:30:58
  1. assume that your image is "png"
  2. assume that you allowed "instagram-stories" in your info.plist (key LSApplicationQueriesSchemes)

What you need to do is to open Instagram app using the following url:
instagram://library?LocalIdentifier= and pass as a parameter PHAsset.localIdentifier.
For some reason this hook isn't listed anywhere in the documentation 🤷‍♂️

But in order to receive a local identifier for your image/video, you must first save the image/video to user's photo library. So the final code would look like this

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)
    }
})
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!