2

I want to read the contents of an assets library file in iOS

NSFileHandle fileHandleForReadingFromUrl using the asset defaultRepresentation url seems to always return 0x0...

I'll keep looking for a solution in the mean time.

EDIT:

Looks like the answer from Anomie might be what I want:

NSUInteger length = [representation getBytes:bytes fromOffset:0 length:[representation size] error:&error];

Community
  • 1
  • 1
cynistersix
  • 1,215
  • 1
  • 16
  • 30
  • Anomie's answer will probably work with small videos, but if you are dealing with larger videos you will probably have to copy out by chunks. See my answer below – chilitechno.com May 03 '11 at 22:55

1 Answers1

9

For larger files you probably want to copy out via a loop to read X bytes in chunks, otherwise you are liable to exhaust the on-device memory.

NSUInteger chunkSize = 100 * 1024;
uint8_t *buffer = malloc(chunkSize * sizeof(uint8_t));

ALAssetRepresentation *rep = [myasset defaultRepresentation];
NSUInteger length = [rep size];

NSFileHandle *file = [[NSFileHandle fileHandleForWritingAtPath: tempFile] retain];

if(file == nil) {
    [[NSFileManager defaultManager] createFileAtPath:tempFile contents:nil attributes:nil];
    file = [[NSFileHandle fileHandleForWritingAtPath:tempFile] retain];
}

NSUInteger offset = 0;
do {
    NSUInteger bytesCopied = [rep getBytes:buffer fromOffset:offset length:chunkSize error:nil];
    offset += bytesCopied;
    NSData *data = [[NSData alloc] initWithBytes:buffer length:bytesCopied];
    [file writeData:data];
    [data release];
    } while (offset < length);

[file closeFile];
[file release];
free(buffer);
buffer = NULL;
Adam H. Peterson
  • 4,511
  • 20
  • 28
chilitechno.com
  • 1,575
  • 10
  • 12
  • @Adam - I wanted to edit the code such that the horizontal bar does not get shown off (so that I can look at the code at one shot instead of scrolling left and right), so I put some next-line characters in some loc earlier. :) But it should not be too much of inconvenience I guess. :) I wish SO would make the code-section something like XCode editor :) Thanks anyways for further edit. – Viren Jan 30 '14 at 06:46
  • @Viren: I'm not sure what happened there, but my guess is that I saw the previous version of the answer that had part of the code not indented properly (and thus not marked as code), and when I corrected that, it stomped on your second edit. – Adam H. Peterson Jan 30 '14 at 10:49