Reputation: 18523
I need to share an image file to Instagram, and according to Instagram doc: https://www.instagram.com/developer/mobile-sharing/iphone-hooks/, I can use Document Interaction to implement this, but it just doesn't work. Here is my code:
let img = UIImage(named: "test.jpg")
let kInstagramURL = URL(string: "instagram://")
let kUTI = "com.instagram.exclusivegram" // testing "com.instagram.photo" too
let instagramCaption = "TESTING"
let kfileNameExtension = "instagram.igo" // testing "jpg"/"ig" too
if UIApplication.shared.canOpenURL(kInstagramURL!) {
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
if urls.count == 0 {
print("Not found")
return
}
let url = urls[0].appendingPathComponent(kfileNameExtension)
print("URL", url)
// OUPUT: file:///var/mobile/Containers/Data/Application/F14B18CB-5CD4-47AD-8257-E2288C23181E/Documents/instagram.igo
do {
try UIImageJPEGRepresentation(img!, 1.0)?.write(to: url, options: .atomic)
print("WRITEN", url) // Written successfully, no error
} catch {
//TODO: issue error on UI
print("WRITE ERROR: \(error)")
}
let documentInteractionController = UIDocumentInteractionController(url: url)
var rect = CGRect.zero
let view = self.view
documentInteractionController.delegate = DocInteractionResponder() // tried nil, same result
documentInteractionController.uti = kUTI
// adding caption for the image
documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
documentInteractionController.presentOpenInMenu(from: rect, in: view!, animated: true)
}
else {
//TODO: warn from dialog
}
I have tried many things within this code snippet (see comments), but the result is the same: after I tap instagram in the menu, nothing happens.
I thought it may be caused by other code in my app, so I create a blank app (with one simple UIViewController) and put this code in. It doesn't work.
I have read almost all answers on SO related to UIDocumentInteractionController
.
Does this happen to you? Is this the problem with iOS 11 (just upgraded my phone), or maybe Instagram stop supporting Document Interaction?
Upvotes: 1
Views: 1272
Reputation: 351
I just came across the same issue today, and I was able to solve it by declaring the UIDocumentInteractionController
as a class-level property in the view controller, to prevent it from getting deallocated too soon.
Upvotes: 5