41
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

アプリ内のデータをCSV形式でメール添付する

Last updated at Posted at 2013-01-10

手順

  • MessageUI.frameworkを追加
  • 書き出すデータをカンマと改行区切りのNSStringに整形
  • MFMailComposeViewControllerにデータをセット、表示

コード

例として、ObjというNSManagedObjectクラスのid, ユーザ名, 日付, コメントを取得したいとします。

// メールを利用できるかチェック
if (![MFMailComposeViewController canSendMail]) {
    return;
}
MFMailComposeViewController* controller = [[MFMailComposeViewController alloc] init];
[controller setMailComposeDelegate:self];

// 取得したNSStringをNSdataに変換
NSData* data = [[Obj exportCSVString:objects] dataUsingEncoding:NSUTF8StringEncoding];

// mimeTypeはtext/csv
[controller addAttachmentData:data mimeType:@"text/csv" fileName:@"export.csv"];

// 表示
[self.navigationController presentViewController:controller animated:YES completion:nil];
- (NSString*)exportCSVString:(NSArray*)sources
{
    NSDateFormatter* f = [[NSDateFormatter alloc] init];
    [f setDateFormat:@"yyyy-MM-dd"];
    
    // 1行目だけ先に追加
    NSMutableArray* all = [@[@"id,user_name,date,comment"] mutableCopy];
    
    // データを降順にソート
    NSSortDescriptor* desc = [[NSSortDescriptor alloc] initWithKey:@"date" ascending:NO];
    sources = [sources sortedArrayUsingDescriptors:@[desc]];
    
    // カンマ区切りで追加
    for (NSInteger i=0; i<sources.count; i++) {
        Obj* obj = [sources objectAtIndex:i];
        NSArray* adding = @[[obj.identifier stringValue], obj.user.name, [f stringFromDate:obj.date], obj.comment];
        NSString* str = [adding componentsJoinedByString:@","];
        [all addObject:str];
    }
    // CRLFで区切ったNSStringを返す
    return [all componentsJoinedByString:@"\r\n"];
}
41
39
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
41
39

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?