簡體   English   中英

使用類似於SLComposeViewController的Swift將UIImage發布到Instagram

[英]Post UIImage to Instagram using Swift similar to SLComposeViewController

我正在開發一個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保存。 在這里尋找集成,但這是為了保存在app directory的照片。

就像我已經擁有的Facebook和Twitter一樣簡單。

針對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,這將打開“開放”功能

我看着這里 ,發現一個解決方案:

我創建了一個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)

這將打開帶有“開放式”風格的菜單,用戶可以在Instagram打開應用程序(如果已安裝)。

這是一個可重復使用的快速4+類。 使用Xcode 10.1。

  1. 制作swift空文件。
  2. 將以下代碼復制並粘貼到文件中。

     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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM