Domanda

Voglio leggere il contenuto di un file della libreria delle risorse in iOS

NSFileHandle fileHandleForReadingFromUrl usando l'asset defaultRepresentation URL sembra tornare sempre 0x0...

Continuerò a cercare una soluzione nel frattempo.

MODIFICARE:

Sembra la risposta da Anomia Potrebbe essere quello che voglio:

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

È stato utile?

Soluzione

Per i file più grandi probabilmente si desidera copiare tramite un loop per leggere X byte in blocchi, altrimenti è possibile esaurire la memoria sul dispositivo.

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;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top