使用类似于 SLComposeViewController 的 Swift 将 UIImage 发布到 Instagram

Posted

技术标签:

【中文标题】使用类似于 SLComposeViewController 的 Swift 将 UIImage 发布到 Instagram【英文标题】:Post UIImage to Instagram using Swift similar to SLComposeViewController 【发布时间】:2016-04-04 15:15:56 【问题描述】:

我正在处理一个 ios Xcode 7 Swift 2 项目。该应用使用以下方式将照片发布到FacebookTwitter

var shareToFacebook: SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)

var shareToTwitter: SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeTwitter)

喜欢将照片发布到这两个社交媒体是多么容易和简单。我不需要也不想要它们的 API。

我想为Instagram 做一些类似而简单的事情。无需处理Instagram API 的最佳方法是什么?还是我别无选择?

我的照片data 是使用NSCoding 保存的,而不是在DocumentDirectory 中。我查看了here 进行集成,但这是保存在应用程序directory 中的照片。

就像我已经拥有的 Facebook 和 Twitter 一样简单。

【问题讨论】:

使用 UIDocumentInteractionController 启动带有您选择的照片和标题的 Instagram 应用程序。 (不过,用户可以在 Instagram 应用程序中编辑标题) 【参考方案1】:

为 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)
        
    

然后在你想要调用的 ViewController 中...

InstagramManager.sharedManager.postImageToInstagramWithCaption(imageInstagram: <YOUR IMAGE>, instagramCaption: shareText, view: self.view)

如果安装了 Instagram,这将打开“打开”功能

【讨论】:

【参考方案2】:

我看了here,找到了解决办法:

我创建了一个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()
        
    


然后在我的@IBAction 中我使用了:

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

这会打开一个带有“open-in”样式的菜单,用户可以在Instagram(如果已安装)中打开应用程序。

【讨论】:

这行得通,但对于 ios9,您必须在 plist 文件中添加以下内容: LSApplicationQueriesSchemesinstagram跨度> 通过这种方式,我只看到带有标签的警报表:“复制到 instagram”我必须点击它才能分享。有没有直接在应用内分享照片的方法? @MRizwan33 你找到解决方案了吗? @TejasArdeshna 是的,我现在得到了解决方案。 @TejasArdeshna 我已经发布了答案,如果它对你有帮助,然后投票或告诉我错误。【参考方案3】:

这是一个 swift 4+ 的可重用类。在 Xcode 10.1 中工作。

    快速制作空文件。

    将以下代码复制并粘贴到文件中。

    import UIKit
    import Foundation
    
    class InstagramHelper: NSObject, UIDocumentInteractionControllerDelegate 
    
        private let kInstagramURL = "instagram://den3079"
        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: InstagramHelper 
            struct Singleton 
                static let instance = InstagramHelper()
            
            return Singleton.instance
        
    
    
        func postImageToInstagramWithCaption(imageInstagram: UIImage, instagramCaption: String, controller: UIViewController) 
            // called to post image with caption to the instagram application
    
            let instagramURL = URL(string: kInstagramURL)
    
            DispatchQueue.main.async 
    
                if UIApplication.shared.canOpenURL(instagramURL!) 
    
                    let jpgPath = (NSTemporaryDirectory() as NSString).appendingPathComponent(self.kfileNameExtension)
                    if let jpegData = UIImageJPEGRepresentation(imageInstagram, 1.0) 
                        do 
                            try jpegData.write(to: URL(fileURLWithPath: jpgPath), options: .atomicWrite)
    
                         catch 
                            print("write image failed")
                        
                    else 
                        let jpegData = UIImagePNGRepresentation(imageInstagram)
                        do 
                            try jpegData?.write(to: URL(fileURLWithPath: jpgPath), options: .atomicWrite)
    
                         catch 
                            print("write image failed")
                        
                    
                    let fileURL = NSURL.fileURL(withPath: jpgPath)
                    self.documentInteractionController.url = fileURL
                    self.documentInteractionController.delegate = self
                    self.documentInteractionController.uti = self.kUTI
    
                    // adding caption for the image
                    self.documentInteractionController.annotation = ["InstagramCaption": instagramCaption]
                    self.documentInteractionController.presentOpenInMenu(from: controller.view.frame, in: controller.view, animated: true)
    
                 else 
    
                    // alert displayed when the instagram application is not available in the device
                    self.showAlert("", message: self.kAlertViewMessage, controller: controller)
                
            
        
     func showAlert(_ title: String, message: String, controller : UIViewController)
    
        let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler:  action -> Void in
            //Just dismiss the action sheet
            let selector: Selector = NSSelectorFromString("alertOkButtonHandler")
            if controller.responds(to: selector)
                _ = controller.perform(selector)
            
        )
        alert.addAction(okAction)
        controller.present(alert, animated: true, completion: nil)
    
    

以及在 ViewController 类中使用这个函数。

InstagramHelper.sharedManager.postImageToInstagramWithCaption(imageInstagram: img!, instagramCaption: "www.google.com", controller: self)

【讨论】:

以上是关于使用类似于 SLComposeViewController 的 Swift 将 UIImage 发布到 Instagram的主要内容,如果未能解决你的问题,请参考以下文章

仅类似于电话的数字软键盘

运行类似于 Kubernetes 仪表盘的网页

使用类似于 QueryTable 的东西导入 excel 文件?

如何使用 xcode 4 创建类似于 UI 的网格

使用 Scollview 进行垂直分页,类似于 CNN App

我可以使用啥来构建类似于 Shopify 使用的在线帮助手册?