简体   繁体   English

如何在 iOS 中的 Instagram 上分享图片?

[英]How to share an image on Instagram in iOS?

My client wants to share an image on Instagram, Twitter, Facebook.我的客户想在 Instagram、Twitter、Facebook 上分享一张图片。

I have done Twitter and Facebook but did not find any API or any thing on internet to share image on Instagram.我做过 Twitter 和 Facebook,但没有在互联网上找到任何 API 或任何东西来在 Instagram 上分享图像。 Is it possible to share image on Instagram?是否可以在 Instagram 上分享图片? if yes then how?如果是那么怎么办?

When I check the developer site of Instagram I have found the Libraries of Ruby on Rails and Python.当我查看 Instagram 的开发者网站时,我发现了 Ruby on Rails 和 Python 的库。 But there are no documentation of iOS Sdk但是没有iOS Sdk的文档

I have get token from instagram as per instagram.com/developer but now don't know what to do next step for sharing with instagram image.我已经根据 instagram.com/developer 从 instagram 获得令牌,但现在不知道下一步要做什么才能与 instagram 图片共享。

Finally I got the answer.最后我得到了答案。 you can not directly post an image on instagram.你不能直接在 Instagram 上发布图片。 You have to rediredt your image with UIDocumentInteractionController.您必须使用 UIDocumentInteractionController 重新定向您的图像。

@property (nonatomic, retain) UIDocumentInteractionController *dic;    

CGRect rect = CGRectMake(0 ,0 , 0, 0);
UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIGraphicsEndImageContext();
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];

NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];
self.dic.UTI = @"com.instagram.photo";
self.dic = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
self.dic=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
[self.dic presentOpenInMenuFromRect: rect    inView: self.view animated: YES ];


- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
     UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
     interactionController.delegate = interactionDelegate;
     return interactionController;
}

NOTE: once you redirect to instagram app you can not back to your app.注意:一旦您重定向到 instagram 应用程序,您将无法返回到您的应用程序。 you have to open your app again你必须再次打开你的应用程序

Download source from here这里下载源

Here is a full tested code to Upload image + caption text to Instagram..这是一个完整的测试代码,用于将图像 + 标题文本上传到 Instagram。

in.h file在.h文件

//Instagram
@property (nonatomic, retain) UIDocumentInteractionController *documentController;

-(void)instaGramWallPost
{
            NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
            if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
            {
                NSData *imageData = UIImagePNGRepresentation(imge); //convert image into .png format.
                NSFileManager *fileManager = [NSFileManager defaultManager];//create instance of NSFileManager
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); //create an array and store result of our search for the documents directory in it
                NSString *documentsDirectory = [paths objectAtIndex:0]; //create NSString object, that holds our exact path to the documents directory
                NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"insta.igo"]]; //add our image to the path
                [fileManager createFileAtPath:fullPath contents:imageData attributes:nil]; //finally save the path (image)
                NSLog(@"image saved");

                CGRect rect = CGRectMake(0 ,0 , 0, 0);
                UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);
                [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
                UIGraphicsEndImageContext();
                NSString *fileNameToSave = [NSString stringWithFormat:@"Documents/insta.igo"];
                NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:fileNameToSave];
                NSLog(@"jpg path %@",jpgPath);
                NSString *newJpgPath = [NSString stringWithFormat:@"file://%@",jpgPath];
                NSLog(@"with File path %@",newJpgPath);
                NSURL *igImageHookFile = [[NSURL alloc]initFileURLWithPath:newJpgPath];
                NSLog(@"url Path %@",igImageHookFile);

                self.documentController.UTI = @"com.instagram.exclusivegram";
                self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];
                self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];
                NSString *caption = @"#Your Text"; //settext as Default Caption
                self.documentController.annotation=[NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%@",caption],@"InstagramCaption", nil];
                [self.documentController presentOpenInMenuFromRect:rect inView: self.view animated:YES];
            }
            else
            {
                 NSLog (@"Instagram not found");
            }
}

- (UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {
    NSLog(@"file url %@",fileURL);
    UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
    interactionController.delegate = interactionDelegate;

    return interactionController;
}

OR要么

-(void)instaGramWallPost
{
    NSURL *myURL = [NSURL URLWithString:@"Your image url"];
    NSData * imageData = [[NSData alloc] initWithContentsOfURL:myURL];
    UIImage *imgShare = [[UIImage alloc] initWithData:imageData];

    NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];

    if([[UIApplication sharedApplication] canOpenURL:instagramURL]) //check for App is install or not
    {
        UIImage *imageToUse = imgShare;
        NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.igo"];
        NSData *imageData=UIImagePNGRepresentation(imageToUse);
        [imageData writeToFile:saveImagePath atomically:YES];
        NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];
        self.documentController=[[UIDocumentInteractionController alloc]init];
        self.documentController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
        self.documentController.delegate = self;
        self.documentController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"Testing"], @"InstagramCaption", nil];
        self.documentController.UTI = @"com.instagram.exclusivegram";
        UIViewController *vc = [UIApplication sharedApplication].keyWindow.rootViewController;
        [self.documentController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:vc.view animated:YES];
    }
    else {
        DisplayAlertWithTitle(@"Instagram not found", @"")
    }
}

and Write this to.plist并将其写入.plist

<key>LSApplicationQueriesSchemes</key>
    <array>
        <string>instagram</string>
    </array>

You can use one of the provided by Instagram url scheme您可以使用 Instagram 网址方案提供的其中一种

在此处输入图像描述

  1. Instagramoficial doc here Instagram官方文档在这里

  2. Share with UIDocumentInteractionController与 UIDocumentInteractionController 共享

     final class InstagramPublisher: NSObject { private var documentsController:UIDocumentInteractionController = UIDocumentInteractionController() func postImage(image: UIImage, view: UIView, result:((Bool)->Void)? = nil) { guard let instagramURL = NSURL(string: "instagram://app") else { if let result = result { result(false) } return } if UIApplication.sharedApplication().canOpenURL(instagramURL) { let jpgPath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagrammFotoToShareName.igo") if let image = UIImageJPEGRepresentation(image, 1.0) { image.writeToFile(jpgPath, atomically: true) let fileURL = NSURL.fileURLWithPath(jpgPath) documentsController.URL = fileURL documentsController.UTI = "com.instagram.exclusivegram" documentsController.presentOpenInMenuFromRect(view.bounds, inView: view, animated: true) if let result = result { result(true) } } else if let result = result { result(false) } } else { if let result = result { result(false) } } } }
  3. Share with direct redirect与直接重定向分享

     import Photos final class InstagramPublisher: NSObject { func postImage(image: UIImage, result:((Bool)->Void)? = nil) { guard let instagramURL = NSURL(string: "instagram://app") else { if let result = result { result(false) } return } let image = image.scaleImageWithAspectToWidth(640) do { try PHPhotoLibrary.sharedPhotoLibrary().performChangesAndWait { let request = PHAssetChangeRequest.creationRequestForAssetFromImage(image) let assetID = request.placeholderForCreatedAsset?.localIdentifier?? "" let shareURL = "instagram://library?LocalIdentifier=" + assetID if UIApplication.sharedApplication().canOpenURL(instagramURL) { if let urlForRedirect = NSURL(string: shareURL) { UIApplication.sharedApplication().openURL(urlForRedirect) } } } } catch { if let result = result { result(false) } } } }
  4. extension for resize photo to recommended size将照片调整为推荐尺寸的扩展

     import UIKit extension UIImage { // MARK: - UIImage+Resize func scaleImageWithAspectToWidth(toWidth:CGFloat) -> UIImage { let oldWidth:CGFloat = size.width let scaleFactor:CGFloat = toWidth / oldWidth let newHeight = self.size.height * scaleFactor let newWidth = oldWidth * scaleFactor; UIGraphicsBeginImageContext(CGSizeMake(newWidth, newHeight)) drawInRect(CGRectMake(0, 0, newWidth, newHeight)) let newImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return newImage } }
  5. Don't forget to add required scheme in plist不要忘记在 plist 中添加所需的方案

 <key>LSApplicationQueriesSchemes</key> <array> <string>instagram</string> </array>

Hope this answer will resolve your query.希望这个答案能解决您的疑问。 This will directly opens library folder in Instagram instead of Camera.这将直接打开 Instagram 中的库文件夹而不是相机。

NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{
    NSURL *videoFilePath = [NSURL URLWithString:[NSString stringWithFormat:@"%@",[request downloadDestinationPath]]]; // Your local path to the video
    NSString *caption = @"Some Preloaded Caption";
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
    [library writeVideoAtPathToSavedPhotosAlbum:videoFilePath completionBlock:^(NSURL *assetURL, NSError *error) {
        NSString *escapedString   = [self urlencodedString:videoFilePath.absoluteString];
        NSString *escapedCaption  = [self urlencodedString:caption];
        NSURL *instagramURL = [NSURL URLWithString:[NSString stringWithFormat:@"instagram://library?AssetPath=%@&InstagramCaption=%@",escapedString,escapedCaption]];
        if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
            [[UIApplication sharedApplication] openURL:instagramURL];
        }
    }];

if you don't want to use UIDocumentInteractionController如果你不想使用 UIDocumentInteractionController

import Photos

...

func postImageToInstagram(image: UIImage) {
        UIImageWriteToSavedPhotosAlbum(image, self, #selector(SocialShare.image(_:didFinishSavingWithError:contextInfo:)), nil)
    }
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
        if error != nil {
            print(error)
        }

        let fetchOptions = PHFetchOptions()
        fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
        let fetchResult = PHAsset.fetchAssetsWithMediaType(.Image, options: fetchOptions)
        if let lastAsset = fetchResult.firstObject as? PHAsset {
            let localIdentifier = lastAsset.localIdentifier
            let u = "instagram://library?LocalIdentifier=" + localIdentifier
            let url = NSURL(string: u)!
            if UIApplication.sharedApplication().canOpenURL(url) {
                UIApplication.sharedApplication().openURL(NSURL(string: u)!)
            } else {
                let alertController = UIAlertController(title: "Error", message: "Instagram is not installed", preferredStyle: .Alert)
                alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
                self.presentViewController(alertController, animated: true, completion: nil)
            }

        }
    }

For iOS 6 and above, you can use this UIActivity to upload images to Instagram which has the same workflow using iOS hooks but simplifies development:对于 iOS 6 及更高版本,您可以使用此 UIActivity 将图像上传到 Instagram,它使用 iOS 挂钩具有相同的工作流程,但简化了开发:

https://github.com/coryalder/DMActivityInstagram https://github.com/coryalder/DMActivityInstagram

this is correct answer which i implement with detail.这是我详细实施的正确答案。 In.h file在.h文件中

 UIImageView *imageMain;
 @property (nonatomic, strong) UIDocumentInteractionController *documentController;

in.m file only write in.m文件只写

 NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
 if([[UIApplication sharedApplication] canOpenURL:instagramURL])
 {
      CGFloat cropVal = (imageMain.image.size.height > imageMain.image.size.width ? imageMain.image.size.width : imageMain.image.size.height);

      cropVal *= [imageMain.image scale];

      CGRect cropRect = (CGRect){.size.height = cropVal, .size.width = cropVal};
      CGImageRef imageRef = CGImageCreateWithImageInRect([imageMain.image CGImage], cropRect);

      NSData *imageData = UIImageJPEGRepresentation([UIImage imageWithCGImage:imageRef], 1.0);
      CGImageRelease(imageRef);

      NSString *writePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"instagram.igo"];
      if (![imageData writeToFile:writePath atomically:YES]) {
      // failure
           NSLog(@"image save failed to path %@", writePath);
           return;
      } else {
      // success.
      }

      // send it to instagram.
      NSURL *fileURL = [NSURL fileURLWithPath:writePath];
      self.documentController = [UIDocumentInteractionController interactionControllerWithURL:fileURL];
      self.documentController.delegate = self;
      [self.documentController setUTI:@"com.instagram.exclusivegram"];
      [self.documentController setAnnotation:@{@"InstagramCaption" : @"We are making fun"}];
      [self.documentController presentOpenInMenuFromRect:CGRectMake(0, 0, 320, 480) inView:self.view animated:YES];
 }
 else
 {
      NSLog (@"Instagram not found");

 }

For sure you will get result.你肯定会得到结果。 Eg you will see popover from bottom with instagram image.Click on it and have fun.例如,您会从底部看到带有 instagram 图像的弹出窗口。单击它并享受乐趣。

I tried this in my application and it is working perfectly (Swift)我在我的应用程序中尝试过这个并且它运行良好(Swift)

import Foundation

import UIKit

class InstagramManager: NSObject, UIDocumentInteractionControllerDelegate {

    private let kInstagramURL = "instagram://"
    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()
        }
    }
}


 func sendToInstagram(){

     let image = postImage

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

 }

Here is the correct answer.这是正确答案。 you cannot directly post an image on Instagram.您不能直接在 Instagram 上发布图片。 You need to redirect to Instagram using UIDocumentInteractionController...您需要使用 UIDocumentInteractionController 重定向到 Instagram...

NSString* imagePath = [NSString stringWithFormat:@"%@/instagramShare.igo", [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]];
[[NSFileManager defaultManager] removeItemAtPath:imagePath error:nil];
    
UIImage *instagramImage = [UIImage imageNamed:@"imagename you want to share"];
[UIImagePNGRepresentation(instagramImage) writeToFile:imagePath atomically:YES];
NSLog(@"Image Size >>> %@", NSStringFromCGSize(instagramImage.size));
    
self.dic=[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:imagePath]];
self.dic.delegate = self;
self.dic.UTI = @"com.instagram.exclusivegram";
[self.dic presentOpenInMenuFromRect: self.view.frame inView:self.view animated:YES ];

NOTE: once you redirect to instagram app you can not back to your app.注意:一旦您重定向到 instagram 应用程序,您将无法返回到您的应用程序。 you have to open your app again你必须再次打开你的应用程序

You can do that without using the UIDocumentInteractionController and go straight to Instagram with these 3 methods:您可以在不使用 UIDocumentInteractionController 的情况下执行此操作,并使用以下 3 种方法直接进入 Instagram:

It works just like all the other famous app does.它的工作原理与所有其他著名应用程序一样。 The code is written in Objective c, so you can translate it to swift if you want.代码是用 Objective c 编写的,因此您可以根据需要将其转换为 swift。 What you need to do is saving your image to the device and use a URLScheme您需要做的是将图像保存到设备并使用 URLScheme

add this inside your.m file将其添加到您的.m 文件中

#import <Photos/Photos.h>

First you need to save your UIImage to the device with this method:首先,您需要使用此方法将 UIImage 保存到设备:

-(void)savePostsPhotoBeforeSharing
{
    UIImageWriteToSavedPhotosAlbum([UIImage imageNamed:@"image_file_name.jpg"], self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

This method is the callback for saving the image to your device:此方法是将图像保存到您的设备的回调:

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
{
    [self sharePostOnInstagram];

}

After the image is saved to the device, you need to query the image you just saved and get it as a PHAsset图片保存到设备后,需要查询刚刚保存的图片,获取为PHAsset

-(void)sharePostOnInstagram
{
    PHFetchOptions *fetchOptions = [PHFetchOptions new];
    fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:NO],];
    __block PHAsset *assetToShare;
    PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];
    [result enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
        assetToShare = asset;


    }];


    if([assetToShare isKindOfClass:[PHAsset class]])
    {
        NSString *localIdentifier = assetToShare.localIdentifier;
        NSString *urlString = [NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",localIdentifier];
        NSURL *instagramURL = [NSURL URLWithString:urlString];
        if ([[UIApplication sharedApplication] canOpenURL: instagramURL])
        {
            [[UIApplication sharedApplication] openURL: instagramURL];
        } else
        {
            // can not share with whats app
            NSLog(@"No instagram installed");
        }

    }
}

And dont forget to put this in your info.plist under LSApplicationQueriesSchemes并且不要忘记将它放在LSApplicationQueriesSchemes下的 info.plist 中

<string>instagram</string>

- (void) shareImageWithInstagram
{
    NSURL *instagramURL = [NSURL URLWithString:@"instagram://"];
    if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
    {
        UICachedFileMgr* mgr = _gCachedManger;
        UIImage* photoImage = [mgr imageWithUrl:_imageView.image];
        NSData* imageData = UIImagePNGRepresentation(photoImage);
        NSString* captionString = [NSString  stringWithFormat:@"ANY_TAG",];
        NSString* imagePath = [UIUtils documentDirectoryWithSubpath:@"image.igo"];
        [imageData writeToFile:imagePath atomically:NO];
        NSURL* fileURL = [NSURL fileURLWithPath:[NSString stringWithFormat:@"file://%@",imagePath]];

        self.docFile = [[self setupControllerWithURL:fileURL usingDelegate:self]retain];
        self.docFile.annotation = [NSDictionary dictionaryWithObject: captionString
                                                     forKey:@"InstagramCaption"];
        self.docFile.UTI = @"com.instagram.photo";

        // OPEN THE HOOK
        [self.docFile presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
    }
    else
    {
        [UIUtils messageAlert:@"Instagram not installed in this device!\nTo share image please install instagram." title:nil delegate:nil];
    }
}

I tried this in my application and it will definitely work我在我的应用程序中尝试过这个,它肯定会工作

As for me, the best and the easiest way described here Share photo to Instagram from my iOS App至于我,这里描述的最好和最简单的方法从我的 iOS 应用程序将照片分享到 Instagram

You need to save image on device using.igo format, then use "UIDocumentInteractionController" to send local path Instagram app.您需要使用 .igo 格式在设备上保存图像,然后使用“UIDocumentInteractionController”发送本地路径 Instagram 应用程序。 Don't forget to set "UIDocumentInteractionControllerDelegate"不要忘记设置“UIDocumentInteractionControllerDelegate”

My advice is to add something like:我的建议是添加如下内容:

NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) 
{
 <your code>
}
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];

if ([[UIApplication sharedApplication] canOpenURL:instagramURL])
{

    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/Insta_Images/%@",@"shareImage.png"]];


    NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];


    docController.UTI = @"com.instagram.photo";

    docController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];

    docController =[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];

    docController.delegate=self;

    [docController presentOpenInMenuFromRect:CGRectMake(0 ,0 , 612, 612) inView:self.view animated:YES];

I noticed if you put URL pointing to image to activityItems instead of UIImage , Copy to Instagram activity item appears itself, and you don't have to do anything else.我注意到,如果您将指向图像的URL放在activityItems而不是UIImage中, Copy to Instagram活动项目本身就会出现,您无需执行任何其他操作。 Please note that String objects inside activityItems would be discarded and there is no way to prefill caption in Instagram.请注意, activityItems中的String对象将被丢弃,并且无法在 Instagram 中预填充标题。 If you still want to hint user to post particular caption, you'd need to create custom activity where you copy that text to clipboard and let user know about it, like in this gist .如果您仍然想提示用户发布特定的标题,您需要创建自定义活动,您可以在其中将该文本复制到剪贴板并让用户知道它,就像在这个要点中一样。

    @import Photos;

    -(void)shareOnInstagram:(UIImage*)imageInstagram {

        [self authorizePHAssest:imageInstagram];
    }

    -(void)authorizePHAssest:(UIImage *)aImage{

        PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

        if (status == PHAuthorizationStatusAuthorized) {
            // Access has been granted.
            [self savePostsPhotoBeforeSharing:aImage];
        }

        else if (status == PHAuthorizationStatusDenied) {
            // Access has been denied.
        }

        else if (status == PHAuthorizationStatusNotDetermined) {

            // Access has not been determined.
            [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {

                if (status == PHAuthorizationStatusAuthorized) {
                    // Access has been granted.
                    [self savePostsPhotoBeforeSharing:aImage];
                }
            }];
        }

        else if (status == PHAuthorizationStatusRestricted) {
            // Restricted access - normally won't happen.
        }
    }
    -(void)saveImageInDeviceBeforeSharing:(UIImage *)aImage
    {
        UIImageWriteToSavedPhotosAlbum(aImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    }

    - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo: (void *) contextInfo;
    {
        if (error == nil){
            [self sharePostOnInstagram];
        }
    }

    -(void)shareImageOnInstagram
    {
        PHFetchOptions *fetchOptions = [PHFetchOptions new];
        fetchOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:false]];
        PHFetchResult *result = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:fetchOptions];

        __block PHAsset *assetToShare = [result firstObject];

        if([assetToShare isKindOfClass:[PHAsset class]])
        {
            NSString *localIdentifier = assetToShare.localIdentifier;
            NSString *urlString = [NSString stringWithFormat:@"instagram://library?LocalIdentifier=%@",localIdentifier];
            NSURL *instagramURL = [NSURL URLWithString:urlString];
            if ([[UIApplication sharedApplication] canOpenURL: instagramURL])
            {
                [[UIApplication sharedApplication] openURL:instagramURL options:@{} completionHandler:nil];
            } else
            {
                NSLog(@"No instagram installed");
            }
        }
    }

NOTE:- IMP TODO:- Add below key in Info.plist注意:- IMP TODO:- 在 Info.plist 中添加以下键

<key>LSApplicationQueriesSchemes</key>
<array>
<string>instagram</string>
</array>

I Used this code:我使用了这段代码:

    NSString* filePathStr = [[NSBundle mainBundle] pathForResource:@"UMS_social_demo" ofType:@"png"];
NSURL* fileUrl = [NSURL fileURLWithPath:filePathStr];

NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];
[[NSData dataWithContentsOfURL:fileUrl] writeToFile:jpgPath atomically:YES];

NSURL* documentURL = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@", jpgPath]];

UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: documentURL];
self.interactionController = interactionController;
interactionController.delegate = self;
interactionController.UTI = @"com.instagram.photo";
CGRect rect = CGRectMake(0 ,0 , 0, 0);
[interactionController presentOpenInMenuFromRect:rect inView:self.view animated:YES];
-(void)shareOnInstagram {

    CGRect rect = CGRectMake(self.view.frame.size.width*0.375 ,self.view.frame.size.height/2 , 0, 0);



    NSString * saveImagePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/ShareInstragramImage.igo"];

    [UIImagePNGRepresentation(_image) writeToFile:saveImagePath atomically:YES];

    NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", saveImagePath]];

    self.documentController=[UIDocumentInteractionController interactionControllerWithURL:igImageHookFile];

    self.documentController.UTI = @"com.instagram.exclusivegram";
    self.documentController = [self setupControllerWithURL:igImageHookFile usingDelegate:self];

    [self.documentController presentOpenInMenuFromRect: rect    inView: self.view animated: YES ];

}

-(UIDocumentInteractionController *) setupControllerWithURL: (NSURL*) fileURL usingDelegate: (id <UIDocumentInteractionControllerDelegate>) interactionDelegate {

    UIDocumentInteractionController *interactionController = [UIDocumentInteractionController interactionControllerWithURL: fileURL];
    interactionController.delegate = interactionDelegate;
    return interactionController;
}
NSURL *myURL = [NSURL URLWithString:sampleImageURL];
NSData * imageData = [[NSData alloc] initWithContentsOfURL:myURL];
UIImage *imageToUse = [[UIImage alloc] initWithData:imageData];
NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.ig"];
[imageData writeToFile:saveImagePath atomically:YES];
NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];
self.documentController = [UIDocumentInteractionController interactionControllerWithURL:imageURL];
self.documentController.delegate = self;
self.documentController.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@""], @"", nil];
self.documentController.UTI = @"com.instagram.exclusivegram";
[self.documentController presentOpenInMenuFromRect:CGRectMake(1, 1, 1, 1) inView:self.view animated:YES];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM