如何在Instagram分享图片?Swift

23

抱歉,这个问题没有提供代码。但我找不到任何地方可以查找。 我想在Instagram上分享带标题的图片?我该怎么做?

任何帮助都将不胜感激


1
除非有我不知道的变化,否则您无法将图像发布到Instagram API。 您可能需要尝试更通用的共享选项:http://nshipster.com/uiactivityviewcontroller/。 - Logan
1
您想要使用您的应用程序提供的图像打开Instagram应用程序吗?还是想代表您的应用程序向用户的Instagram上传图像? - Daniel Storm
@Logan 谢谢,我会研究一下的。 - user4790024
@DanielStorm 我想做你提到的第二个..我该怎么做? - user4790024
@copeME 你可以使用OAuth Swift来实现DanielStorm提到的功能。OAuth是您可以对个人帐户进行任何操作(上传、关注等)的唯一方式,下面提到的第三方库会为您处理所有事情。我强烈建议您使用它。 - brimstone
4个回答

27

如果你不想使用 UIDocumentInteractionController

SWIFT 5 更新

import Photos
...

func postImageToInstagram(image: UIImage) {
    UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}
@objc func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if error != nil {
            print(error)
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

        let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)

        if let lastAsset = fetchResult.firstObject as? PHAsset {

            let url = URL(string: "instagram://library?LocalIdentifier=\(lastAsset.localIdentifier)")!

            if UIApplication.shared.canOpenURL(url) {
                UIApplication.shared.open(url)
            } else {
                let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
                self.present(alertController, animated: true, completion: nil)
            }

        }
}

2
兄弟.. 这正是我要找的。有没有可能在不保存图片到照片库的情况下完成相同的操作呢? - Tapas Pal
1
我只是想知道为什么instagram://library不在Instagram文档中。无论如何,它对我有效。谢谢! - Jakub Vodak
谢谢!正是我想要的。 尽管需要注意的是,这需要您的应用程序对照片库具有写入访问权限。这可能会成为某些人的阻碍。 - r-dent
我怎样才能分享视频? - alexsmith

11
class viewController: UIViewController, UIDocumentInteractionControllerDelegate {
    
    var yourImage: UIImage?
    var documentController: UIDocumentInteractionController!
    
    func shareToInstagram() {
        
        let instagramURL = NSURL(string: "instagram://app")
        
        if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) {
            
            let imageData = UIImageJPEGRepresentation(yourImage!, 100)
            
            let captionString = "caption"
            
            let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo")
            if imageData?.writeToFile(writePath, atomically: true) == false {
                
                return
                
            } else {
                let fileURL = NSURL(fileURLWithPath: writePath)
                
                self.documentController = UIDocumentInteractionController(URL: fileURL)
                
                self.documentController.delegate = self
                
                self.documentController.UTI = "com.instagram.exlusivegram"
                
                self.documentController.annotation = NSDictionary(object: captionString, forKey: "InstagramCaption")
                self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true)
                
            }
            
        } else {
            print(" Instagram isn't installed ")
        }
    }
}

现在这个方法在iOS 9上已经不再可行,所以您需要前往应用程序信息属性列表(info.plist),添加"LSApplicationQueriesSchemes"类型为"Array"的键值对,并将需要使用的URL方案(此例中为"instagram")添加到该数组中。

2
为了使其正常工作,需要在plist中添加以下内容:<key>LSApplicationQueriesSchemes</key> <array> <string>instagram</string> </array> - Ashok
2
http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing - Yakiv Kovalskyi
1
我在iOS 10.1的Swift 3中尝试将图像数据写入writePath时,出现错误Error Domain=NSCocoaErrorDomain Code=518 "The file couldn’t be saved because the specified URL type isn’t supported." UserInfo={NSURL=/private/var/mobile/Containers/Data/Application/5B80A983-5571-44A5-80D7-6A7B065800B5/tmp/instagram.igo} - Rohan Sanap

11

Swift 3.0 版本:

 @IBAction func shareInstagram(_ sender: Any) {

        DispatchQueue.main.async {

            //Share To Instagram:
            let instagramURL = URL(string: "instagram://app")
            if UIApplication.shared.canOpenURL(instagramURL!) {

                let imageData = UIImageJPEGRepresentation(image, 100)
                let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo")

                do {
                    try imageData?.write(to: URL(fileURLWithPath: writePath), options: .atomic)
                } catch {
                    print(error)
                }

                let fileURL = URL(fileURLWithPath: writePath)
                self.documentController = UIDocumentInteractionController(url: fileURL)
                self.documentController.delegate = self
                self.documentController.uti = "com.instagram.exlusivegram"

                if UIDevice.current.userInterfaceIdiom == .phone {
                    self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true)
                } else {
                    self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true)
                }
            } else {
                print(" Instagram is not installed ")
            }
        }
    }

这种方法似乎不再起作用了,请参见示例repo - sashab

4

请尝试使用此代码。

@IBAction func shareContent(sender: UIButton) {
    
    let image = UIImage(named: "imageName")
    let objectsToShare: [AnyObject] = [image!]
    let activityViewController = UIActivityViewController(
        activityItems: objectsToShare,
        applicationActivities: nil
    )
    activityViewController.popoverPresentationController?.sourceView = self.view
    activityViewController.excludedActivityTypes = [
        UIActivityTypeAirDrop,
        UIActivityTypePostToFacebook
    ]
    self.presentViewController(
        activityViewController,
        animated: true,
        completion: nil
    )
}

2
是的,这正是现代iOS中分享到Instagram(或任何其他地方)的方法。您永远不会尝试“从应用程序内部分享”。 - Fattie
提醒一下,这在iOS 13.1中已经失效了。我认为这不是你的代码问题,而是苹果公司破坏了某些或所有共享扩展。 - jjxtra

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接