QuickLook for the win

So you want to present a CSV, Microsoft Office, iWorks or RTF document in your iOS app? Instead of writing a viewer-interface for these formats yourself, you might want to use the QuickLook.framework within iOS to do the heavy lifting for you.

In a recent project, I needed to present a CSV file for viewing purposes. Nothing fancy, the data should just be shown in a grid-like style. While looking for an elegant solution, I stumbled upon QuickLook.framework. It's available in iOS as of iOS4 and is pretty easy to use. Below is some sample code in order to get QuickLook to preview a CSV file named mycontent.csv (in the application bundle).

-(void)previewCSV
{
        QLPreviewController* previewController = [[QLPreviewController alloc] init];
        previewController.delegate = self;
        previewController.dataSource = self;
        [self presentModalViewController:previewController animated:YES];
        [previewController.navigationItem setRightBarButtonItem:nil];
}

#pragma mark Quicklook
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller
{
        return 1;
}

- (id <QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
    NSString *path=[[NSBundle mainBundle] pathForResource:@"mycontent" ofType:@"csv"];
    return [NSURL fileURLWithPath:path];
}

- (BOOL)previewController:(QLPreviewController *)controller shouldOpenURL:(NSURL *)url forPreviewItem:(id <QLPreviewItem>)item
{
    return YES;
}