Come condividere un'immagine su Instagram in iOS?


87

Il mio cliente vuole condividere un'immagine su Instagram, Twitter, Facebook.

Ho fatto Twitter e Facebook ma non ho trovato nessuna API o qualsiasi cosa su Internet per condividere l'immagine su Instagram. È possibile condividere un'immagine su Instagram? se si allora come?

Quando controllo il sito degli sviluppatori di Instagram ho trovato le librerie di Ruby on Rails e Python. Ma non c'è documentazione di iOS Sdk

Ho ricevuto il token da instagram come per instagram.com/developer ma ora non so cosa fare per la condivisione con l'immagine di instagram.


Risposte:


70

Finalmente ho avuto la risposta. non puoi pubblicare direttamente un'immagine su instagram. Devi reindirizzare la tua immagine con 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;
}

NOTA: una volta reindirizzato all'app Instagram, non puoi tornare alla tua app. devi aprire di nuovo la tua app

Scarica la fonte da qui


dov'è la funzione setupControllerWithURL o lo fa?
khaled l'

3
@SurenderRathore devi ridimensionare la tua immagine in 612 * 612 e salvarla in formato .ig .ig mostra che vuoi aprire la tua immagine in instagram e devi testarla sul tuo iPhone o iPod fino alla versione 4.3. iPad non è supportato
Hiren

1
@HiRen: Sì, hai ragione, ma nella mia app sto facendo uno screenshot di una vista e poi condivido quello screenshot tramite l'app di Instagram e funziona perfettamente. Ma voglio anche passare del testo statico con quello screenshot. Se hai qualche idea per favore aiutami. C'è un codice demo su GitHub per DMACtivityInstagram e puoi vedere da lì cosa sto cercando di dire. Grazie in anticipo.
Manthan

2
L'utilizzo di questa riga ha provocato un arresto anomalo in iOS 6: NSURL * igImageHookFile = [[NSURL alloc] initWithString: [[NSString alloc] initWithFormat: @ "file: //% @", jpgPath]]; L'utilizzo di questo funziona in entrambi: NSURL * igImageHookFile = [NSURL fileURLWithPath: jpgPath]; Potrebbe valere la pena modificare la risposta di conseguenza, a meno che non mi manchi qualcosa?
weienw

1
questo è solo per me, o qualcun altro vuole dire "ehi Instagram, sei stato sviluppatore una volta, perché ci stai rendendo la vita così difficile?"
Chris Chen

27

Ecco un codice completamente testato per caricare l'immagine + il testo della didascalia su Instagram ..

in.h file

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

O

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

e scrivi a .plist

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

è possibile tornare all'applicazione dopo aver condiviso l'immagine su Instagram?
Hiren

no ... dobbiamo tornare manualmente ... ma se trovo una soluzione aggiornerò il codice ...
Hardik Thakkar

Grazie @Fahim Parkar
Hardik Thakkar

Scelgo il pulsante Instagram ma dopo non succede niente? C'è del codice aggiuntivo oltre a questa risposta per farlo?
noobsmcgoobs

1
@HardikThakkar quando uso la tua soluzione ottengo solo una selezione di app tra cui scegliere, non Instagram. IOS 11. Sai se funziona ancora? Grazie
Vladyslav Melnychenko

22

Puoi utilizzare uno degli schemi di URL forniti da Instagram

inserisci qui la descrizione dell'immagine

  1. Documento ufficiale di Instagram qui

  2. Condividi con 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. Condividi con reindirizzamento diretto

    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. estensione per ridimensionare la foto alla dimensione consigliata

    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. Non dimenticare di aggiungere lo schema richiesto in plist

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

1
Ho provato un sacco di altre cose da altre risposte e solo questo ha funzionato (almeno per i video. "Instagram: // library? LocalIdentifier =" era quello che ha fatto. Molte grazie!
Bjorn Roche

La condivisione con reindirizzamento diretto (che è di gran lunga la migliore soluzione IMO) non funziona più per me: Instagram si apre nella pagina della libreria ma non preseleziona un'immagine. Hai idea di cosa potrebbe essere cambiato con questo schema URL? Stai riscontrando errori simili con l'ultima versione di Instagram su iOS?
urchino

@gbk Questo codice funziona per me. Ma ho un nuovo requisito per più foto su Instagram. Come Instagram ha una nuova opzione di caricamento multiplo e visualizzazione come la visualizzazione delle diapositive. Come si fa? Mi aiuti per favore.
Ekta Padaliya

Santa merda. Grazie per questo. Ho sbattuto la testa contro un muro nell'ultimo giorno cercando di far funzionare bene la condivisione su Instagram dalla mia app.
Jesse S.

2
solo la variante 3 funziona per me per iOS 13, ma non dimenticare di aggiungere <key> NSPhotoLibraryUsageDescription </key> <string> L'app ha bisogno delle tue foto di nudo. </string>
serg_zhd

14

Spero che questa risposta risolva la tua domanda. Questo aprirà direttamente la cartella della libreria su Instagram invece che su Fotocamera.

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
Trovi che ogni volta che lo fai, l'app di Instagram verrà caricata seleziona l'immagine precedente? Penso che ci sia qualcosa di sbagliato nel collegamento del percorso delle risorse.
Supertecnoboff

2
eccellente !! Quindi Instagram può essere aperto direttamente senza UIDocumentInteractionController.Thanks.
iChirag

Mi potete aiutare con questo caso stackoverflow.com/questions/34226433/...
jose920405

Possiamo anche passare l'URL con l'immagine?
Alok

1
Sfortunatamente, ALAssetsLibrary è deprecato da iOS 9.
Alena

10

se non vuoi usare 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)
            }

        }
    }

È ciò di cui ho veramente bisogno. Grazie!
Azel

Mi hai salvato la vita, risposta perfetta. Grazie !!
tecnico

1
Questo è totalmente sbagliato ogni volta che faccio clic per condividere su Instagram e ho annullato il suo salvataggio nel rullino fotografico.
Shrikant K

9

Per iOS 6 e versioni successive, puoi utilizzare questa UIActivity per caricare immagini su Instagram che ha lo stesso flusso di lavoro utilizzando gli hook iOS ma semplifica lo sviluppo:

https://github.com/coryalder/DMActivityInstagram


ciao @Chintan Patel come posso ottenere le informazioni del profilo utente se hai qualche fonte di esempio per favore condividi con noi
sabir

6

questa è la risposta corretta che implemento con i dettagli. Nel file .h

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

in.m solo scrittura

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

 }

Di sicuro otterrai risultati. Ad esempio, vedrai il popover dal basso con l'immagine di Instagram, fai clic su di esso e divertiti.


5

L'ho provato nella mia applicazione e funziona perfettamente (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

Ecco la risposta corretta. non puoi pubblicare direttamente un'immagine su Instagram. Devi reindirizzare a Instagram utilizzando 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 ];

}

NOTA: una volta reindirizzato all'app Instagram, non puoi tornare alla tua app. devi aprire di nuovo la tua app


Hai impostato il delegato ma non l'hai scritto / postato?
Raptor

2

Puoi farlo senza utilizzare l'UIDocumentInteractionController e andare direttamente su Instagram con questi 3 metodi:

Funziona proprio come tutte le altre famose app. Il codice è scritto in Objective c, quindi puoi tradurlo in swift se lo desideri. Quello che devi fare è salvare la tua immagine sul dispositivo e utilizzare un URLScheme

aggiungilo all'interno del tuo file .m

#import <Photos/Photos.h>

Per prima cosa devi salvare il tuo UIImage sul dispositivo con questo metodo:

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

Questo metodo è il callback per salvare l'immagine sul tuo dispositivo:

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

}

Dopo che l'immagine è stata salvata sul dispositivo, è necessario interrogare l'immagine appena salvata e ottenerla come 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");
        }

    }
}

E non dimenticare di inserirlo nella tua info.plist sotto LSApplicationQueriesSchemes

<string>instagram</string>


Come posso aggiungere più foto su 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];
    }
}

L'ho provato nella mia applicazione e funzionerà sicuramente


Forse dovresti spiegare UIUtils& UICachedFileMgr?
Raptor

Capire. Suggerisci di modificare la tua risposta per fornire maggiori dettagli
Raptor

@Raptor: Scarica l'app di esempio dal seguente: link
neha_sinha19

UIUtils è una classe che ho creato per gestire i metodi di utilità ed è derivata da NSObject. Ho aggiunto il metodo messageAlert per mostrare la visualizzazione degli avvisi. Nell'app di esempio di cui ho fornito il collegamento sopra, puoi trovare la classe UIUtils. Se tutto va bene, capirai.
neha_sinha19

1

Quanto a me, il modo migliore e più semplice descritto qui Condividi foto su Instagram dalla mia app iOS

È necessario salvare l'immagine sul dispositivo utilizzando il formato .igo, quindi utilizzare "UIDocumentInteractionController" per inviare l'app Instagram del percorso locale. Non dimenticare di impostare "UIDocumentInteractionControllerDelegate"

Il mio consiglio è di aggiungere qualcosa come:

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

Ho notato che se metti il URLpuntatore sull'immagine activityItemsinvece di UIImage, l' Copy to Instagramelemento dell'attività appare da solo e non devi fare nient'altro. Tieni presente che gli Stringoggetti all'interno activityItemsverranno scartati e non c'è modo di precompilare la didascalia su Instagram. Se vuoi comunque suggerire all'utente di pubblicare una didascalia particolare, devi creare un'attività personalizzata in cui copi il testo negli appunti e lo fai sapere all'utente, come in questa sintesi .


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

NOTA: - IMP TODO: - Aggiungi sotto chiave in Info.plist

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

0

Ho usato questo codice:

    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
Sebbene questo codice possa rispondere alla domanda, fornire un contesto aggiuntivo su come e / o perché risolve il problema migliorerebbe il valore a lungo termine della risposta.
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];
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.