Updated for Swift 3
import UIKit
import Foundation
class InstagramManager: NSObject, UIDocumentInteractionControllerDelegate {
private let kInstagramURL = "instagram://app"
private let kUTI = "com.instagram.exclusivegram"
private let kfileNameExtension = "instagram.igo"
private let kAlertViewTitle = "Error"
private let kAlertViewMessage = "Please install the Instagram application"
var documentInteractionController = UIDocumentInteractionController()
// singleton manager
class var sharedManager: InstagramManager {
struct Singleton {
static let instance = InstagramManager()
}
return Singleton.instance
}
func postImageToInstagramWithCaption(imageInstagram: UIImage, instagramCaption: String, view: UIView) {
// called to post image with caption to the instagram application
let instagramURL = NSURL(string: kInstagramURL)
if UIApplication.shared.canOpenURL(instagramURL! as URL) {
let jpgPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(kfileNameExtension)
do {
try UIImageJPEGRepresentation(imageInstagram, 1.0)?.write(to: URL(fileURLWithPath: jpgPath), options: .atomic)
} catch {
print(error)
}
let rect = CGRect(x: 0, y: 0, width: 612, height: 612)
let fileURL = NSURL.fileURL(withPath: jpgPath)
documentInteractionController.url = fileURL
documentInteractionController.delegate = self
documentInteractionController.uti = kUTI
// adding caption for the image
documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
documentInteractionController.presentOpenInMenu(from: rect, in: view, animated: true)
} else {
/// display some message about how it didn't work
/// Like: UIAlertController(title: kAlertViewTitle, message: kAlertViewMessage, preferredStyle: .alert)
}
}
}
and then in the ViewController you want to call it in...
InstagramManager.sharedManager.postImageToInstagramWithCaption(imageInstagram: <YOUR IMAGE>, instagramCaption: shareText, view: self.view)
This opens the 'open-in' function if Instagram is installed
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…