debe agregar su imagen a la biblioteca de fotos y luego compartirla directamente a Instagram
en primer lugar, no olvide agregar NSPhotoLibraryAddUsageDescription y el esquema de instagram a su info.plist:
<key>NSPhotoLibraryAddUsageDescription</key>
<string>$(PRODUCT_NAME) wants to save pictures to your library</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>
Funciona correctamente para iOS 12.4 y 13
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") }
}
}
}
Resultado