LoginSignup
19
18

More than 5 years have passed since last update.

UIDocumentInteractionControllerを使ってNSStringを他のアプリで開くまで

Last updated at Posted at 2014-03-25

UIDocumentInteractionControllerを使った事がある方はいると思いますが、
ネット上のサンプルコードを探してもNSStringを他のアプリで開くまでの手順が書かれているものがなかったのでコチラに投稿。

UIActivityViewControllerを使えば、簡単にテキストを他のアプリで開けるのですが、
コチラの場合、自分でアプリを追加しなければいけなかったりと、面倒。

UIDocumentInteractionControllerを使えば、自動的にテキストファイルが開けるアプリを
探して表示してくれるのでコチラのほうが断然便利です。

UIDocumentInteractionControllerを使用

//テキストファイルとして書き出すためのディレクトリを作成する
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* docDir = [paths objectAtIndex:0];

    NSString* dirPath = [NSString stringWithFormat:@"%@/cache", docDir];
    NSFileManager* fileManager = [NSFileManager defaultManager];
    // ディレクトリが存在するか確認する
    if (![fileManager fileExistsAtPath:dirPath])
    {
        // 存在しなければ、ディレクトリを作成する
        [fileManager createDirectoryAtPath:dirPath
               withIntermediateDirectories:YES
                                attributes:nil error:nil];
    }


    // 最終的に他のアプリで開きたい文字列を用意しておきます
    NSString* hoge = @"テスト"

    // データの書き込み
    NSString* filePath = [NSString stringWithFormat:@"%@/new.txt", dirPath];

    [hoge writeToFile:filePath atomically:YES encoding:NSUnicodeStringEncoding error:nil];


    NSURL *url = [NSURL fileURLWithPath:filePath];
    self.docInterCon = [UIDocumentInteractionController interactionControllerWithURL:url];

    self.docInterCon.delegate = self;

    BOOL isValid;
    isValid = [self.docInterCon presentOpenInMenuFromRect:self.view.frame inView:self.view animated:YES];
    if (!isValid) {
        NSLog(@"データを開けるアプリケーションが見つかりません。");
    }

他のアプリで開くまでの手順としては、

1.一度NSStringをテキストファイルとして書き出す
2.UIDocumentInteractionControllerを使って書きだしたテキストファイルを開けるアプリを表示させる

という感じです。

19
18
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
18