2015-07-10 2 views
8

Извините за вопрос без кода. Но я не нашел нигде, чтобы его искать. Я хочу поделиться изображением с заголовком в instagram? Как я могу это сделать?Как поделиться имиджем в instagram? Swift

Любая помощь будет большим

+1

Если что-то не не изменилось, что я не» Знаете, вы не можете отправлять изображения в instgram api. Возможно, вы захотите попробовать более общий вариант совместного использования: http://nshipster.com/uiactivityviewcontroller/ – Logan

+1

Вы хотите открыть приложение Instagram с изображением, предоставленным вашим приложением? Или вы хотите загрузить изображение в Instagram от имени ваших приложений? –

+0

@Logan thanks..i будет изучать то, что .... –

ответ

10
class viewController: UIViewController, UIDocumentInteractionControllerDelegate { 

    var yourImage: UIImage? 
    var documentController: UIDocumentInteractionController! 

    func shareToInstagram() { 

    let instagramURL = NSURL(string: "instagram://app") 

      if (UIApplication.sharedApplication().canOpenURL(instagramURL!)) { 

       let imageData = UIImageJPEGRepresentation(yourImage!, 100) 

       let captionString = "caption" 

      let writePath = (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent("instagram.igo") 
      if imageData?.writeToFile(writePath, atomically: true) == false { 

        return 

       } else { 
    let fileURL = NSURL(fileURLWithPath: writePath) 

        self.documentController = UIDocumentInteractionController(URL: fileURL) 

        self.documentController.delegate = self 

        self.documentController.UTI = "com.instagram.exlusivegram" 

        self.documentController.annotation = NSDictionary(object: captionString, forKey: "InstagramCaption") 
          self.documentController.presentOpenInMenuFromRect(self.view.frame, inView: self.view, animated: true) 

       } 

      } else { 
       print(" Instagram isn't installed ") 
      } 
     } 
    } 

    } 

Теперь это еще не будет работать с прошивкой 9, так что вам придется идти к приложениям info.plist, добавить «LSApplicationQueriesSchemes» Тип: массив и добавить URL-схема в этом случае «instagram».

+1

Чтобы сделать эту работу, необходимо добавить следующее в PLIST: LSApplicationQueriesSchemes Instagram

+0

Почему заголовок не работает? –

+2

http://developers.instagram.com/post/125972775561/removing-pre-filled-captions-from-mobile-sharing –

7

, если вы не хотите использовать 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) 
      } 

     } 
} 
+1

Bro .. Это я искал. Можно ли сделать то же самое, не сохраняя изображение в фотогалерее? –

+0

Мне просто интересно, почему instagram: // библиотека отсутствует в документации Instagram. Во всяком случае, это работает для меня. Спасибо! –

+0

Спасибо! Именно то, что я искал. Хотя нужно помнить, что для его приложения требуется доступ к записи в библиотеку фотографий. Может быть, блокатор для некоторых. –

1

Вот попробуйте этот код

@IBAction func shareContent(sender: UIButton) { 

       let image = UIImage(named: "imageName") 
      let objectsToShare: [AnyObject] = [ image! ] 
      let activityViewController = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil) 
      activityViewController.popoverPresentationController?.sourceView = self.view 


      activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook ] 


      self.presentViewController(activityViewController, animated: true, completion: nil) 

      } 
     } 
+0

Да, именно так вы делитесь с Instagram (или где-либо еще) в современной iOS. Вы никогда не пытаетесь «делиться изнутри приложения». – Fattie

6

Swift 3,0 Версия:

@IBAction func shareInstagram(_ sender: Any) { 

    DispatchQueue.main.async { 

     //Share To Instagrma: 

     let instagramURL = URL(string: "instagram://app") 

     if UIApplication.shared.canOpenURL(instagramURL) { 

      let imageData = UIImageJPEGRepresentation(<YOURIMAGE>!, 100) 

      let writePath = (NSTemporaryDirectory() as NSString).appendingPathComponent("instagram.igo") 

      do { 
        try imageData?.write(to: URL(fileURLWithPath: writePath), options: .atomic) 

      } catch { 

       print(error) 
      } 

       let fileURL = URL(fileURLWithPath: writePath) 

       self.documentController = UIDocumentInteractionController(url: fileURL) 

       self.documentController.delegate = self 

       self.documentController.uti = "com.instagram.exlusivegram" 

      if UIDevice.current.userInterfaceIdiom == .phone { 

       self.documentController.presentOpenInMenu(from: self.view.bounds, in: self.view, animated: true) 

      } else { 

       self.documentController.presentOpenInMenu(from: self.IGBarButton, animated: true) 

      } 


      } else { 

      print(" Instagram is not installed ") 
     } 
    } 


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