Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get video NSData from ALAsset url iOS

I am not able to retrieve NSData from the url that I get from ALAsset

Below is the code I tried:- I always get NSData as nil.

 NSData *webData = [NSData dataWithContentsOfURL:[asset defaultRepresentation].url];

I also tried something like this

 NSData *webData1 = [NSData dataWithContentsOfURL:[[asset valueForProperty:ALAssetPropertyURLs] valueForKey:[[[asset valueForProperty:ALAssetPropertyURLs] allKeys] objectAtIndex:0]]];

The url that I get from the ALAsset:-

assets-library://asset/asset.MOV?id=1000000116&ext=MOV

I have tried this below link which works but I need to unnecessary write to a temp location which is very time consuming.

Getting video from ALAsset

Any hint in right direction would be highly appreciated.

Waiting for your replies

like image 505
Ekra Avatar asked Jan 09 '12 15:01

Ekra


2 Answers

try this code:-

ALAssetRepresentation *rep = [asset defaultRepresentation];
Byte *buffer = (Byte*)malloc((NSUInteger)rep.size);
NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:(NSUInteger)rep.size error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
like image 77
Leena Avatar answered Oct 13 '22 07:10

Leena


Byte buffer = (Byte)malloc(rep.size); if the rep.size is so big, maybe 300M,that will be crash. so try this code:

+ (BOOL)writeDataToPath:(NSString*)filePath andAsset:(ALAsset*)asset
{
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath:filePath];
    if (!handle) {
        return NO;
    }
    static const NSUInteger BufferSize = 1024*1024;

    ALAssetRepresentation *rep = [asset defaultRepresentation];
    uint8_t *buffer = calloc(BufferSize, sizeof(*buffer));
    NSUInteger offset = 0, bytesRead = 0;

    do {
        @try {
            bytesRead = [rep getBytes:buffer fromOffset:offset length:BufferSize error:nil];
            [handle writeData:[NSData dataWithBytesNoCopy:buffer length:bytesRead freeWhenDone:NO]];
            offset += bytesRead;
        } @catch (NSException *exception) {
            free(buffer);

            return NO;
        }
    } while (bytesRead > 0);

    free(buffer);
    return YES;
}
like image 38
riven Avatar answered Oct 13 '22 06:10

riven