iOS ALAssetsLibrary and NSFileHandle reading file contents

后端 未结 1 439
眼角桃花
眼角桃花 2020-12-20 00:29

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

NSFileHandle fileHandleForReadingFromUrl using the asset defaultRepresentation

相关标签:
1条回答
  • 2020-12-20 01:01

    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;
    
    0 讨论(0)
提交回复
热议问题