iOS ALAssetsLibrary and NSFileHandle reading file contents

谁说胖子不能爱 提交于 2019-11-28 05:36:23

问题


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];


回答1:


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;


来源:https://stackoverflow.com/questions/5876564/ios-alassetslibrary-and-nsfilehandle-reading-file-contents

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!