Як поділитися зображенням в Instagram в iOS?


87

Мій клієнт хоче поділитися зображенням в Instagram, Twitter, Facebook.

Я працював у Twitter та Facebook, але не знайшов жодного API чи чогось іншого в Інтернеті для обміну зображеннями в Instagram. Чи можна поділитися зображеннями в Instagram? якщо так, то як?

Перевіряючи веб-сайт розробника Instagram, я знайшов бібліотеки Ruby on Rails та Python. Але документації щодо iOS Sdk немає

Я отримав маркер з instagram відповідно до instagram.com/developer, але тепер не знаю, що робити наступним кроком для спільного використання із зображенням Instagram.


Будь-яка ідея щодо stackoverflow.com/questions/28858512/… ?
— Ашок

Відповіді:


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 або вона?
— khaled

3
@SurenderRathore ви повинні масштабувати своє зображення до 612 * 612 і зберегти у форматі .ig .ig показує, що ви хочете відкрити своє зображення в Instagram, і ви повинні протестувати на своєму iPhone або iPod до версії 4.3. iPad не підтримується
— Hiren,

1
@HiRen: Так, ти маєш рацію, але в моєму додатку я роблю скріншот перегляду, а потім ділюся цим скріншотом через програму instagram, і він чудово працює. Але я також хочу передати трохи статичного тексту з цим скріншотом. Якщо у вас є ідея, будь ласка, допоможіть мені. На github є демонстраційний код для DMACtivityInstagram, і звідти ви бачите, що я намагаюся сказати. Заздалегідь спасибі.
— Мантан,

2
Використання цього рядка призвело до аварії в iOS 6: NSURL * igImageHookFile = [[NSURL alloc] initWithString: [[NSString alloc] initWithFormat: @ "file: //% @", jpgPath]]; Використання цього працює в обох: NSURL * igImageHookFile = [файл NSURLURLWithPath: jpgPath]; Можливо, варто відредагувати відповідь відповідно, якщо я чогось не пропустив?
— weienw

1
це мені так, чи хтось інший хоче сказати "привіт, Instagram, ти колись був розробником, чому ти робиш наше життя таким важким?"
— Chris Chen

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?
— Хірен

ні ... ми повинні повернутися вручну ... але якщо я
— знайду

Дякую @Fahim Parkar
— Hardik Thakkar 02.03.15

Я вибираю кнопку Instagram, але після цього нічого не відбувається? Чи є якийсь додатковий код за межами цієї відповіді, щоб це зробити?
— noobsmcgoobs

1
@HardikThakkar, коли я використовую ваше рішення, я отримую лише вибір додатків на вибір, а не Instagram. IOS 11. Чи знаєте ви, чи все ще працює? Дякую
— Владислав Мельниченко

22

Ви можете скористатися однією із передбачених Instagram схемою URL-адрес

введіть тут опис зображення

  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 =". Велике спасибі!
— Бьорн Рош,

Спільний доступ із прямим перенаправленням (що є безумовно найкращим рішенням IMO) для мене більше не працює - Instagram відкривається на сторінці бібліотеки, але попередньо не вибирає зображення. Ви уявляєте, що могло змінитися за допомогою цієї схеми URL-адрес? Ви відчуваєте подібні збої з останньою версією Instagram на iOS?
— урчіно

@gbk Цей код працює для мене. Але у мене є нова вимога до декількох фотографій в Instagram. Як і Instagram, є нова опція багаторазового завантаження та відображення, як слайд-перегляд. Ти як це робиш? Будь ласка, допоможи мені.
— Екта Падалія,

Святий ш * т. Дякую за це. Минулого дня я бився головою об стіну, намагаючись змусити спільний доступ до Instagram з мого додатка працювати гарно.
— Джессі С.

2
у мене для iOS 13 працює лише 3-варіантний, до речі, не забудьте додати <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

2
чудово !! Отже, Instagram можна відкрити безпосередньо без UIDocumentInteractionController. Спасибі.
— iChirag

Ви можете мені допомогти з цією справою stackoverflow.com/questions/34226433 / ...
— jose920405

Чи можемо ми також передати URL-адресу із зображенням?
— Алок

1
На жаль, ALAssetsLibrary застаріла з iOS 9.
— Олена

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

        }
    }

Це те, що мені справді потрібно. Дякую!
— Азель

Ти врятував мені життя, ідеальна відповідь. Дякую !!
— technerd

1
Це абсолютно неправильно кожного разу, коли я натискаю, щоб поділитися в Instagram, і скасував його збереження в рулоні камери.
— Шрікант К

9

Для iOS 6 та новіших версій ви можете використовувати цю UIActivity, щоб завантажувати зображення в Instagram, який має той самий робочий процес за допомогою хуків iOS, але спрощує розробку:

https://github.com/coryalder/DMActivityInstagram


привіт @Chintan Patel, як я можу отримати інформацію про профіль користувача, якщо у вас є якесь зразок джерела, будь ласка, поділіться з нами
— sabir

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

Я спробував це в своєму додатку, і він працює ідеально (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)

 }

2

Ось правильна відповідь. ви не можете безпосередньо опублікувати зображення в Instagram. Вам потрібно перенаправити в Instagram за допомогою UIDocumentInteractionController ...

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 ви не зможете повернутися до програми. вам доведеться відкрити програму знову


Ви встановили делегата, але не написали / опублікували?
— Raptor

2

Ви можете зробити це, не використовуючи UIDocumentInteractionController, і перейти прямо до Instagram за допомогою цих 3 методів:

Це працює так само, як і всі інші відомі програми. Код написаний на Objective c, тому ви можете швидко перекласти його, якщо хочете. Вам потрібно зберегти зображення на пристрій і скористатися 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];

}

Після того, як зображення буде збережено на пристрої, вам потрібно зробити запит до щойно збереженого зображення та отримати його як PHA-набір

-(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?
— Екта Падалія,

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

Я спробував це у своєму додатку, і це точно буде працювати


Може, вам слід пояснити UIUtils& UICachedFileMgr?
— Raptor

Зрозумійте. Запропонуйте відредагувати свою відповідь, щоб надати більше деталей
— Raptor

@Raptor: Будь ласка, завантажте зразок програми з наступного: посилання
— neha_sinha19

UIUtils - це клас, який я створив для управління утилітними методами. Він походить від NSObject. Я додав метод messageAlert для відображення подання сповіщень. У прикладі програми, посилання якої я надав вище, ви можете знайти клас UIUtils. Сподіваємось, ви зрозумієте.
— neha_sinha19

1

Як на мене, найкращий і найпростіший спосіб, описаний тут, Поділіться фотографією в Instagram з мого додатка iOS

Вам потрібно зберегти зображення на пристрої у форматі .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вказівник на зображення , елемент діяльності з’являється сам, і вам не потрібно нічого робити. Зверніть увагу, що об’єкти всередині будуть викинуті, і в Instagram немає можливості попередньо заповнити підпис. Якщо ви все-таки хочете підказати користувачеві опублікувати певний підпис, вам потрібно буде створити власну активність, де ви скопіюєте цей текст у буфер обміну та повідомте користувача про це, як у цій суті .activityItemsUIImageCopy to InstagramStringactivityItems


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
Хоча цей код може відповісти на питання, надання додаткового контексту щодо того, як та / або чому він вирішує проблему, покращило б довгострокове значення відповіді.
— thewaywewere

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];
Використовуючи наш веб-сайт, ви визнаєте, що прочитали та зрозуміли наші Політику щодо файлів cookie та Політику конфіденційності.
Licensed under cc by-sa 3.0 with attribution required.