如何在iOS中的Instagram上共享图像?


87

我的客户希望在Instagram,Twitter,Facebook上共享图像。

我已经完成了Twitter和Facebook,但是在互联网上找不到任何API或任何东西可以在Instagram上共享图像。是否可以在Instagram上分享图片?如果是,那怎么办?

当我检查Instagram的开发人员站点时,我发现了Ruby on Rails和Python库。但是没有iOS Sdk的文档

我已经根据instagram.com/developer从instagram获取了令牌,但现在不知道下一步如何与instagram图像共享。


Answers:


70

终于我得到了答案。您不能直接在instagram上发布图片。您必须使用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;
}

注意:重定向到instagram应用后,您将无法返回到您的应用。您必须再次打开您的应用

这里下载源


函数setupControllerWithURL在哪里或在哪里?
哈立德

3
@SurenderRathore,您必须将图像缩放到612 * 612并保存为.ig格式。ig显示要在instagram中打开图像,并且必须在iPhone或iPod最高版本4.3中进行测试。不支持iPad
Hiren's

1
@HiRen:是的,您是对的,但是在我的应用程序中,我正在拍摄视图的屏幕截图,然后通过instagram应用程序共享该屏幕截图,并且效果很好。但我也想通过该屏幕截图传递一些静态文本。如果您有任何想法请帮助我。github上有一个用于DMACtivityInstagram的演示代码,您可以从那里看到我想说的话。提前致谢。
曼森

2
使用此行使我在iOS 6中崩溃:NSURL * igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@“ file://%@”,jpgPath]]; 两者均可使用:NSURL * igImageHookFile = [NSURL fileURLWithPath:jpgPath]; 除非我丢失了某些内容,否则可能值得相应地编辑答案?
weienw

1
这是我的意思,还是有其他人想说:“嘿,Instagram,您曾经是开发人员,为什么让我们的生活如此艰难?”
克里斯·陈

27

这是将图片和标题文本上传到Instagram的完整测试代码。

in.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;
}

要么

-(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", @"")
    }
}

并将其写入.plist

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

在Instagram上分享图像后,是否有可能返回到应用程序?
Hiren'2

不,我们必须手动返回...但是,如果我找到任何解决方案,我将更新代码...
Hardik Thakkar,2015年

感谢@Fahim Parkar
Hardik Thakkar

我选择了Instagram按钮,但此后没有任何反应?除了此答案之外,还有其他代码可以做到这一点吗?
noobsmcgoobs

1
@HardikThakkar在使用您的解决方案时,我只能选择一些应用程序,而不能选择Instagram。IOS 11.您知道它是否仍然有效吗?谢谢
弗拉迪斯拉夫·梅尔尼琴科

22

您可以使用Instagram提供的网址方案之一

在此处输入图片说明

  1. Instagram官方文档在这里

  2. 与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. 直接重定向共享

    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. 扩展名以将照片调整为推荐尺寸

    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. 不要忘记在plist中添加所需的方案

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

1
从其他答案中尝试了一堆其他方法,但只有此方法才有效(至少对于视频而言。“ instagram:// library?LocalIdentifier =“是它的功能。非常感谢!
Bjorn Roche

具有直接重定向功能的共享(到目前为止,这是IMO最好的解决方案)对我不再起作用-Instagram在库页面上打开,但不会预选图像。您是否知道此URL方案可能会发生什么变化?您是否在iOS上使用最新版本的Instagram遇到类似的故障?
urchino

@gbk此代码对我有用。但我有新的要求,要在Instagram上多张照片。像Instagram一样,有多个新选项可以上传并显示为幻灯片视图。你如何做到这一点?请帮我。
Ekta Padaliya

神圣的 这次真是万分感谢。在过去的一天里,我一直在想办法从我的应用程序共享到instagram,以便正常工作。
杰西S.18年

2
只有3'd变体对我来说适用于ios 13,顺便说一句,不要忘记添加<key> NSPhotoLibraryUsageDescription </ key> <string>应用需要您的裸照。</ string>
serg_zhd

14

希望这个答案能解决您的查询。这将直接在Instagram中打开库文件夹而不是Camera。

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];
        }
    }];

1
是否发现每次执行此操作时,Instagram应用程序都会加载选择前一张图像?我认为资产路径链接有问题。
Supertecnoboff 2015年

2
太好了!所以Instagram可以直接打开而无需UIDocumentInteractionController。
iChirag

你能帮我做这种情况下stackoverflow.com/questions/34226433/...
jose920405

我们也可以通过图片传递URL吗?
阿洛克

1
不幸的是,自iOS 9起,ALAssetsLibrary已弃用。–
Alena

10

如果您不想使用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)
            }

        }
    }

这是我真正需要的。谢谢!
Azel

您救了我的命,完美的答案。谢谢 !!
technerd

1
每次我单击以在instagram上共享并取消其保存到相机胶卷时,这是完全错误的。
Shrikant K


6

这是我详细介绍的正确答案。在.h文件中

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

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");

 }

当然,您会得到结果。例如,您将在底部看到带有instagram图像的弹出窗口。


5

我在我的应用程序中尝试过,它运行良好(快速)

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)

 }

2

这是正确的答案。您不能直接在Instagram上发布图片。您需要使用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 ];

}

注意:重定向到instagram应用后,您将无法返回到您的应用。您必须再次打开您的应用


您设置了代表,但没有写/张贴?
猛禽2014年

2

您可以在不使用UIDocumentInteractionController的情况下做到这一点,并使用以下3种方法直接进入Instagram:

就像其他所有著名的应用程序一样工作。该代码是用Objective c编写的,因此您可以根据需要将其转换为swift。您需要做的是将图像保存到设备并使用URLScheme

将此添加到您的.m文件中

#import <Photos/Photos.h>

首先,您需要使用以下方法将UIImage保存到设备:

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

此方法是用于将图像保存到设备的回调:

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

}

将图像保存到设备后,您需要查询刚刚保存的图像并将其作为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");
        }

    }
}

并且不要忘记将其放在您的info.plist下 LSApplicationQueriesSchemes

<string>instagram</string>


如何在instagram上添加多张照片?
Ekta Padaliya

1
- (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];
    }
}

我在我的应用程序中尝试过,它肯定会工作


也许您应该解释UIUtilsUICachedFileMgr
猛禽2014年

理解。建议编辑您的答案以提供更多详细信息
Raptor 2014年

@Raptor:请从以下位置下载示例应用程序: 链接
neha_sinha19 2014年

UIUtils是我创建的用于管理实用程序方法的类,它是从NSObject派生的。我添加了messageAlert方法来显示警报视图。在上面提供了链接的示例应用程序中,您可以找到UIUtils类。希望您会理解。
neha_sinha19 2014年

1

对于我来说,这里描述的最好和最简单的方法是从我的iOS应用程序将照片分享到Instagram

您需要使用.igo格式将图像保存在设备上,然后使用“ UIDocumentInteractionController”发送本地路径Instagram应用。不要忘记设置“ UIDocumentInteractionControllerDelegate”

我的建议是添加类似以下内容:

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

1
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];

1

我注意到,如果您将URL图像指向activityItems而不是UIImageCopy to Instagram活动项会自动出现,并且您无需执行其他任何操作。请注意,String内部的对象activityItems将被丢弃,并且无法在Instagram中预填充字幕。如果仍要提示用户张贴特定标题,则需要创建自定义活动,在该活动中,您可以将该文本复制到剪贴板,并让用户知道,如本要点所示


1
    @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");
            }
        }
    }

注意:-IMP TODO:-在Info.plist中添加以下项

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

0

我使用以下代码:

    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];

0
-(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;
}

1
尽管此代码可以回答问题,但提供有关如何和/或为什么解决问题的其他上下文将提高​​答案的长期价值。
thewaywere是

0
 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];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.