画像をフォトライブラリに追加してから、その画像をInstagramに直接共有する必要があります
まず最初に、NSPhotoLibraryAddUsageDescriptionとInstagramスキームをinfo.plistに追加することを忘れないでください。
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME) wants to save pictures to your library</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>
12.4および13 iOSで正しく動作します
import UIKit
import Photos
class TestViewController: UIViewController, UIDocumentInteractionControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
postImageToInstagram(UIImage(named: "bigImage")!)
}
func postImageToInstagram(_ image: UIImage) {
// Check if we have instagarm app
if UIApplication.shared.canOpenURL(URL(string: "instagram://app")!) {
// Requesting authorization to photo library in order to save image there
PHPhotoLibrary.requestAuthorization { status in
if status == .authorized {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(_:didFinishSavingWithError:contextInfo:)), nil)
} else { print("wrong status \(status)") }
}
} else { print("Please install the Instagram application") }
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
print(error)
return
}
let fetchOptions = PHFetchOptions()
// add sorting to take correct element from fetchResult
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchOptions.fetchLimit = 1
// taking our image local Identifier in photo library to share it
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if let lastAsset = fetchResult.firstObject {
let url = URL(string: "instagram://library?LocalIdentifier=\(lastAsset.localIdentifier)")!
if UIApplication.shared.canOpenURL(url) { UIApplication.shared.open(url) }
else { print("Please install the Instagram application") }
}
}
}
結果