问题
I am trying to make sharing from my app to Instagram easy. And what I want is to get to the screen that is depicted on the screenshot below. I've tried instagram-stories://share deeplink and I've read thorugh all these docs: https://developers.facebook.com/docs/instagram/sharing-to-stories/
However, whatever I do, when the url scheme action fires it goes directly into sharing the image into the story. What am I missing here?
Here is my code excerpt:
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)
}
}
回答1:
- assume that your
image
is "png" - assume that you allowed
"instagram-stories" in your info.plist (key
LSApplicationQueriesSchemes
)
回答2:
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)
}
})
来源:https://stackoverflow.com/questions/55211886/post-to-instagram-screen-on-ios-swift