iOS ALAssetsLibrary和NSFileHandle读取文件内容 [英] iOS ALAssetsLibrary and NSFileHandle reading file contents

查看:130
本文介绍了iOS ALAssetsLibrary和NSFileHandle读取文件内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在iOS中阅读资产库文件的内容

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

NSFileHandle fileHandleForReadingFromUrl 使用资产 defaultRepresentation url似乎总是返回 0x0 ...

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

我会一直在寻找解决方案。

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

编辑:

看起来答案来自 Anomie 可能就是我想要的:

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

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

推荐答案

对于较大的文件,您可能希望通过循环复制出来以读取块中的X字节,否则就是可能会耗尽设备内存。

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;

这篇关于iOS ALAssetsLibrary和NSFileHandle读取文件内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆