Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating and using a .csv file with UIActivityViewController

So I am creating a .csv file and then allowing the user to share it using the UIActivityViewController.

My code to create the csv file will return the NSURL of the file:

- (NSURL *)exportToCSV
{
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"results.csv"];

    if (![[NSFileManager defaultManager] fileExistsAtPath:docPath]) {
        [[NSFileManager defaultManager] createFileAtPath:filePath
                                                contents:nil
                                              attributes:nil];
    }

    NSMutableString *contents = [NSMutableString stringWithCapacity:0];

    //fill contents with data in csv format
    // ...

    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    [fileHandle writeData:[contents dataUsingEncoding:NSUTF8StringEncoding]];
    [fileHandle closeFile];

    return [NSURL fileURLWithPath:filePath];
}

and then my activity uses that NSURL to initiate the UIActivityViewController:

- (IBAction)shareButtonPressed:(id)sender {

    NSArray *activityItems = @[@"results.csv", [self.object exportToCSV]];
    UIActivityViewController *shareScreen = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];

    [self presentViewController:shareScreen animated:YES completion:nil];
}

When I select mail an option, the csv file is not attached. it just has the text "results.csv"

what am I doing wrong?

like image 256
Alex Avatar asked Dec 16 '12 22:12

Alex


1 Answers

The problem would appear to be in your fileExistsAtPath line. You appear to be saying "if the documents directory doesn't exist, then create the file". That's certainly not right.

Personally, I'd lose that stuff and change it to be

- (NSURL *)exportToCSV
{
    NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
    NSString *filePath = [docPath stringByAppendingPathComponent:@"results.csv"];

    NSMutableString *contents = [NSMutableString stringWithCapacity:0];

    //fill contents with data in csv format
    // ...

    NSError *error;

    [contents writeToFile:filePath
               atomically:YES
                 encoding:NSUTF8StringEncoding
                    error:&error];

    // check for the error

    return [NSURL fileURLWithPath:filePath];
}
like image 103
Rob Avatar answered Oct 04 '22 03:10

Rob