Post UIImage to Instagram using Swift similar to SLComposeViewController

前端 未结 3 646
执笔经年
执笔经年 2020-12-14 12:55

I have an iOS Xcode 7 Swift 2 project I\'m working on. The app posts photos to Facebook and Twitter using:

var shareToFacebook: SL         


        
3条回答
  •  难免孤独
    2020-12-14 13:28

    I looked here and found a solution:

    I created an NSObject:

    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.sharedApplication().canOpenURL(instagramURL!) {
                let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(kfileNameExtension)
                UIImageJPEGRepresentation(imageInstagram, 1.0)!.writeToFile(jpgPath, atomically: true)
                let rect = CGRectMake(0,0,612,612)
                let fileURL = NSURL.fileURLWithPath(jpgPath)
                documentInteractionController.URL = fileURL
                documentInteractionController.delegate = self
                documentInteractionController.UTI = kUTI
    
                // adding caption for the image
                documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
                documentInteractionController.presentOpenInMenuFromRect(rect, inView: view, animated: true)
            } else {
    
                // alert displayed when the instagram application is not available in the device
                UIAlertView(title: kAlertViewTitle, message: kAlertViewMessage, delegate:nil, cancelButtonTitle:"Ok").show()
            }
        }
    
    }
    

    Then in my @IBAction I used:

    let image = self.photoImageView.image
    InstagramManager.sharedManager.postImageToInstagramWithCaption(image!, instagramCaption: "\(self.description)", view: self.view)
    

    This opens bring a menu up with the 'open-in' style and the user can open the app in Instagram (if installed).

提交回复
热议问题