Skip to content

Instantly share code, notes, and snippets.

@bendytree
Created December 17, 2013 23:03
Show Gist options
  • Save bendytree/8014289 to your computer and use it in GitHub Desktop.
Save bendytree/8014289 to your computer and use it in GitHub Desktop.
Objective-c category for saving an `ALAssetRepresentation` to disk using a buffer (instead of reading the whole thing into memory).
//
// ALAssetRepresentation+SaveToDisk.m
//
// Adapted from http://damir.me/import-video-from-alasset
//
// Created by Joshua Wright<@BendyTree> on 12/17/13.
// http://www.joshwright.com
//
#import "ALAssetRepresentation+SaveToDisk.h"
@implementation ALAssetRepresentation (SaveToDisk)
- (BOOL) saveTo:(NSString *)filePath
{
// Create a file handle to write the file at your destination path
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
if (!handle)
return NO;
// Create a buffer for the asset
static const NSUInteger BufferSize = 1024*1024;
uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
NSUInteger offset = 0, bytesRead = 0;
// Read the buffer and write the data to your destination path as you go
do
{
@try
{
NSError* error = nil;
bytesRead = [self getBytes:buffer fromOffset:offset length:BufferSize error:&error];
[handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
offset += bytesRead;
if(error) return NO;
}
@catch (NSException *exception)
{
free(buffer);
return NO;
}
} while (bytesRead > 0);
free(buffer);
return YES;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment