Экспорт фото в Instagram

Я пытаюсь экспортировать фотографию из своего приложения в Instagram, используя этот код:

// Capture Screenshot
UIGraphicsBeginImageContextWithOptions(self.view.frame.size,self.view.opaque,0.0);
[self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage * image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/test.igo"];
NSURL *igImageHookFile = [[NSURL alloc] initWithString:[[NSString alloc] initWithFormat:@"file://%@", jpgPath]];
dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:igImageHookFile]];
dic.UTI = @"com.instagram.photo";
dic.annotation = [NSDictionary dictionaryWithObject:@"my caption" forKey:@"InstagramCaption"];
NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]) {
  [[UIApplication sharedApplication] openURL:instagramURL];
} else {
  NSLog(@"No Instagram Found");
}

Но это не работает. Вылетает со следующей ошибкой:

2013-01-19 20:40:41.948 Ayat[12648:c07] * Завершение работы приложения из-за необработанного исключения "NSInvalidArgumentException", причина: "* -[NSURL initFileURLWithPath:]: нулевой строковый параметр"

Я не уверен, что я правильно:

1- Сохранение jpgpath в качестве снимка экрана, который я сделал.

2- Передача документа «dic» в Instagram.


person user1767928    schedule 19.01.2013    source источник
comment
Определить не работает. Предупреждение/ошибка компилятора? Крушение? Какие? Быть конкретными. Вы пользовались отладчиком? Вы проверили, что все переменные имеют ожидаемые значения? Что происходит в операторе if?   -  person rmaddy    schedule 19.01.2013
comment
maddy.. происходит сбой со следующей ошибкой: 2013-01-19 20:40:41.948 Ayat[12648:c07] *** Завершение работы приложения из-за необработанного исключения 'NSInvalidArgumentException', причина: '*** -[NSURL initFileURLWithPath: ]: параметр строки nil' Я не уверен, что я правильно: 1- сохранение jpgpath в качестве снимка экрана, который я сделал 2- открытие instagram с документом dic   -  person user1767928    schedule 19.01.2013
comment
Обновите свой вопрос, указав дополнительные сведения.   -  person rmaddy    schedule 19.01.2013


Ответы (4)


В моем приложении я также экспортирую фото в Instagram. (Изображение должно быть больше 612x612) Попробуйте этот код:

-(void)shareImageOnInstagram:(UIImage*)shareImage
{
    //Remember Image must be larger than 612x612 size if not resize it.   

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

    if([[UIApplication sharedApplication] canOpenURL:instagramURL])
    {
        NSString *documentDirectory=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
        NSString *saveImagePath=[documentDirectory stringByAppendingPathComponent:@"Image.ig"];
        NSData *imageData=UIImagePNGRepresentation(shareImage);
        [imageData writeToFile:saveImagePath atomically:YES];

        NSURL *imageURL=[NSURL fileURLWithPath:saveImagePath];

        UIDocumentInteractionController *docController=[[UIDocumentInteractionController alloc]init];
        docController.delegate=self;
        [docController retain];
        docController.UTI=@"com.instagram.photo";

        docController.annotation=[NSDictionary dictionaryWithObjectsAndKeys:@"Image Taken via @App",@"InstagramCaption", nil];

        [docController setURL:imageURL];


        [docController presentOpenInMenuFromBarButtonItem:self.navigationItem.rightBarButtonItem animated:YES];  //Here try which one is suitable for u to present the doc Controller. if crash occurs

    }
    else
    {
        NSLog (@"Instagram not found");

    }

}

Я надеюсь, что это поможет вам.

person Satish Azad    schedule 19.01.2013
comment
Большое спасибо. ответил на мои вопросы и работал отлично - person user1767928; 20.01.2013
comment
Привет, я использую тот же код, но он не работает на ios 8, у кого-нибудь есть такая же проблема? - person Babul Prabhakar; 23.03.2015
comment
С какой проблемой вы столкнулись? - person Satish Azad; 23.03.2015

На этой линии

dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:igImageHookFile]];

вы звоните fileURLWithPath:. Для начала ожидается NSString, а не NSURL, но из вашего сообщения об ошибке похоже, что igImageHookFile равно nil.

person wattson12    schedule 19.01.2013

Потребовалось много исследований, но я наконец нашел это на этом сайте, который помог. Я просто немного обрезал его, чтобы не включать подпись, так как это была его первоначальная проблема... но если вы вставляете только картинку, вот она:

-(void)shareImageOnInstagram
{
//Remember Image must be larger than 612x612 size if not resize it.
 NSURL *instagramURL = [NSURL URLWithString:@"instagram://app"];
if ([[UIApplication sharedApplication] canOpenURL:instagramURL]){
    NSString *urlString = [[NSString alloc] initWithFormat:@"file://%@", blendedImageURL];
    NSURL *imageUrl = [[NSURL alloc] initWithString: urlString];
    self.docController = [self setupControllerWithURL:imageUrl usingDelegate:self];
    self.docController.UTI = @"com.instagram.exclusivegram";
   // self.docController.annotation = [NSDictionary dictionaryWithObject:@"I want to     share this text" forKey:@"InstagramCaption"];
    [self.docController presentOpenInMenuFromRect: self.view.frame inView: self.view     animated: YES ];}
}
person Brandon    schedule 17.06.2013

Я попробовал следующий код, и он сработал:

- (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:@"%@%@",self.approvedData.approvedCaption,self.approvedData.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];
    }
}
person neha_sinha19    schedule 04.02.2014