2017-01-02 17 views
2

Я пытаюсь использовать изображение в приложении Instagram через мое приложение.Как поделиться изображением в Instagram из одного приложения

Пожалуйста, проверьте мой код ниже и, пожалуйста, сообщите мне, где я ошибся.

_instagramURL = [NSURL URLWithString:[NSString stringWithFormat: @"instagram://media?id=%@",[SingletoneClass sharedSingleTone].imageId]]; 

if ([[UIApplication sharedApplication] canOpenURL:_instagramURL]) { 
    self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]]; 
    self.dic.delegate = self; 
    self.dic.UTI = @"com.instagram.exclusivegram"; 
    self.dic.annotation = [NSDictionary dictionaryWithObject:[SingletoneClass sharedSingleTone].captionStr forKey:@"InstagramCaption"]; 
    [self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ]; 
} 
else { 
    UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:@"" message:@"Instagram is not present in your device" andCallback:^(id actionResponse) { 
     [alert dismissViewControllerAnimated:YES completion:nil]; 
    }]; 
    [self presentViewController:alert animated:YES completion:nil]; 
} 

Если приведенный выше код является правильным, то, пожалуйста, дайте мне знать, откуда я могу найти изображениеId?

+0

Можете ли вы добавить описание файла SingletonClass. Какой объект он возвращает. –

+0

@AnilGupta вы спрашиваете о, UIAlertController сигнал тревога * = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle: @ "" сообщение: @ "Instagram нет в устройстве" andCallback:^(идентификатор ActionResponse) { [оповещения dismissViewControllerAnimated: ДА завершение : ноль]; }]; –

+0

Если вы делитесь изображениями с изображениями «Фотогалереи» или «Изображения», чем просто передайте путь объекта изображения в «_instagramURL». Вы можете найти идентификатор imges из https://www.instagram.com/developer/, зарегистрировав ваше приложение. Но для обмена вам не нужно регистрировать ваше приложение. –

ответ

3

Наконец-то я получил решение. Нам нужно сохранить изображение в каталоге Document. Приложение Instagram может извлекать изображение из каталога Document.

NSData *imagedata = UIImageJPEGRepresentation(image, 0.5); 
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) 

Затем, используя UIDocumentInteractionController, мы можем предоставить общий доступ к изображению в приложении Instagram. Перед совместным использованием изображения вы должны быть уверены, что приложение Instagram присутствует в устройстве.

- (void) shareImageToInstagram { 
    _instagramURL = [NSURL URLWithString:[NSString stringWithFormat: @"instagram://app"]]; 

    if ([[UIApplication sharedApplication] canOpenURL:_instagramURL]) 
    { 
     self.dic = [UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:[SingletoneClass sharedSingleTone].imagePath]]; 
     self.dic.delegate = self; 
     self.dic.UTI = @"com.instagram.photo"; 
     self.dic.annotation = [NSDictionary dictionaryWithObjectsAndKeys:[SingletoneClass sharedSingleTone].captionStr,@"InstagramCaption", nil]; 
     [self.dic presentOpenInMenuFromRect: CGRectZero inView:self.view animated:YES ]; 
    } 
    else 
    { 
     UIAlertController *alert = [[SingletoneClass sharedSingleTone] setAlertControllerWithTitle:@"" message:@"Instagram is not present in your device" andCallback:^(id actionResponse) { 
      [alert dismissViewControllerAnimated:YES completion:nil]; 
     }]; 
     [self presentViewController:alert animated:YES completion:nil]; 
    } 
} 

Для получения дополнительной информации вы можете сослаться на следующие ссылки. https://www.instagram.com/developer/mobile-sharing/iphone-hooks/ и Share photo to Instagram from my iOS App

+0

Не могли бы вы рассказать мне, что находится внутри одноэлементного класса? Загрузите полный код. – Abha

 Смежные вопросы

  • Нет связанных вопросов^_^