0
votes

I have to share image on instagram with caption but in Instagram nothing is coming. I used below code for sharing on instagram. Is there any changes in code of sharing. I also check the official page of Instagram but no code is given. https://www.instagram.com/developer/mobile-sharing/iphone-hooks/

Following code is working till ios10 but in ios11 it is not working any more.

File write successfully in document directory but problem was in UIDocumentInteractionController. It is not able to read file from document directory.

    //MARK:
    //MARK: share with instagram
    func shareImageToInstagram(withImagePath imgPath:String,withStrTitle strTitle:String,withView view:UIView,withSender sender:UIButton! = nil) {
        let instagramURL = URL(string: "instagram://app")
        if UIApplication.shared.canOpenURL(instagramURL!) {
            interactionController = UIDocumentInteractionController(url: URL.init(fileURLWithPath: imgPath))
            interactionController?.uti = "com.instagram.photos"
            interactionController?.annotation = NSDictionary.init(dictionaryLiteral: ("InstagramCaption",strTitle))
            interactionController?.presentOpenInMenu(from: CGRect.zero, in: view, animated: true)
            sender.isUserInteractionEnabled = true
        }
    }

    //MARK:
    //MARK: share with instagram
    func downloadUserImageFromURL(withImageUrl imgURl : URL,withView view:UIView,withstrTitle strTitle:String,withSender sender:UIButton! = nil){

        DispatchQueue.global(qos: .userInitiated).async {
            do {
                DispatchQueue.main.async {
                    SINGLETON.startLoadingActivity(view)
                }
                let data = try Data.init(contentsOf: imgURl) //make sure your image in this url does exist, otherwise unwrap in a if let check
                DispatchQueue.main.async {
                    SINGLETON.stopLoadingActivity(view)
                    //create instance of NSFileManager
                    let paths: [Any] = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
                    //create an array and store result of our search for the documents directory in it
                    let documentsDirectory: String = paths[0] as? String ?? ""
                    //create NSString object, that holds our exact path to the documents directory
                    let fullPath: String = URL(fileURLWithPath: documentsDirectory).appendingPathComponent("insta.igo").absoluteString
                    //add our image to the path

                    if FileManager.default.fileExists(atPath: fullPath)
                    {
                        do {
                            try FileManager.default.removeItem(at: URL.init(string: fullPath)!)
                        } catch let error as NSError {
                            sender.isUserInteractionEnabled = true
                            print(error.localizedDescription)
                        }
                    }
                    do {
                        try data.write(to: URL.init(string: fullPath)!)
                        self.shareImageToInstagram(withImagePath: fullPath, withStrTitle: strTitle, withView: view,withSender: sender)

                    } catch let error as NSError {
                        sender.isUserInteractionEnabled = true
                        print(error.localizedDescription)
                    }

                }
            }
            catch{
                DispatchQueue.main.async {
                    SINGLETON.stopLoadingActivity(view)
                }
            }
        }
    }
1
@dvp.petrov thanks for reply but it is possible. Please check my answer and let me know if anything wrongchirag shah

1 Answers

3
votes

You use wrong UTI: "com.instagram.photos" should be "com.instagram.photo".
Also don't forget to add URL scheme instagram into plist at Key LSApplicationQueriesSchemes.

Here you can find example of sharing into Instagram (method - (void)send).
Main code from there: Objective-C:

// make a path into documents
    NSString* homePath = [self _getpathToDocuments];
    NSString* basePath = @"integration/instagram";
    NSString* tmpFileName;
    if ([self _isInstagramOnly]) {
        tmpFileName = @"jumpto.igo";
    } else {
        tmpFileName = @"jumpto.ig";
    }

    NSString* dirPath = [NSString stringWithFormat:@"%@/%@", homePath, basePath];
    NSString* docPath = [NSString stringWithFormat:@"%@/%@", dirPath, tmpFileName];

    [[NSFileManager defaultManager] removeItemAtPath:docPath error:nil];
    if ([[NSFileManager defaultManager] createDirectoryAtPath:dirPath withIntermediateDirectories:YES attributes:nil error:nil]) {
        UIImage* tmpImg = [self _imageForSharing];

        if([self _needResizeImage]){
            tmpImg = [self _resizeImage:tmpImg];
        }

        NSData* imgData = [self generateImageData:tmpImg];
        [[NSFileManager defaultManager] createFileAtPath:docPath contents:imgData attributes:nil];
        NSURL* url = [NSURL fileURLWithPath:docPath isDirectory:NO ];

        NSString *UTI  = nil;
        if ([self _isInstagramOnly]) {
            UTI = @"com.instagram.exclusivegram";
        } else {
            UTI = @"com.instagram.photo";
        }

        NSString *captionString = @"Caption message";

        UIDocumentInteractionController* dic = [UIDocumentInteractionController interactionControllerWithURL:documentFileURL];
        dic.UTI = UTI;
        dic.annotation = @{@"InstagramCaption" : captionString};
        dic.delegate = self;

        [self presentOpenInMenuFromRect:[self _getButtonRect] inView:self.view animated:YES];
    }

Swift:

//  Converted with Swiftify v1.0.6491 - https://objectivec2swift.com/
// make a path into documents

var homePath: String = _getpathToDocuments()
var basePath = "integration/instagram"
var tmpFileName = ""
if _isInstagramOnly() {
    tmpFileName = "jumpto.igo"
}
else {
    tmpFileName = "jumpto.ig"
}
var dirPath = "\(homePath)/\(basePath)"
var docPath = "\(dirPath)/\(tmpFileName)"
try? FileManager.default.removeItem(atPath: docPath)
if try? FileManager.default.createDirectory(atPath: dirPath, withIntermediateDirectories: true, attributes: nil) != nil {
    var tmpImg: UIImage? = _imageForSharing()
    if _needResizeImage() {
        tmpImg = _resize(tmpImg)
    }
    var imgData = generateImageData(tmpImg)
    FileManager.default.createFile(atPath: docPath, contents: imgData, attributes: nil)
    var url = URL.fileURL(withPath: docPath, isDirectory: false)
    var UTI: String? = nil
    if _isInstagramOnly() {
        UTI = "com.instagram.exclusivegram"
    }
    else {
        UTI = "com.instagram.photo"
    }
    var captionString = "Caption message"
    var dic = UIDocumentInteractionController(url: documentFileURL)
    dic.uti = UTI
    dic.annotation = ["InstagramCaption": captionString]
    dic.delegate = self
    presentOpenInMenu(from: _getButtonRect(), in: view, animated: true)
}