从 ALAsset url iOS 获取视频 NSData
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8791049/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get video NSData from ALAsset url iOS
提问by Ekra
I am not able to retrieve NSData from the url that I get from ALAsset
我无法从从 ALAsset 获得的 url 中检索 NSData
Below is the code I tried:- I always get NSData as nil.
以下是我尝试过的代码:- 我总是将 NSData 设为 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:-
我从 ALAsset 得到的网址:-
assets-library://asset/asset.MOV?id=1000000116&ext=MOV
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.
我已经在下面的链接中尝试过这个链接,但我需要不必要地写入一个非常耗时的临时位置。
Any hint in right direction would be highly appreciated.
任何正确方向的提示将不胜感激。
Waiting for your replies
等待您的回复
回答by Leena
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];
回答by riven
Byte buffer = (Byte)malloc(rep.size); if the rep.size is so big, maybe 300M,that will be crash. so try this code:
字节缓冲区 = (Byte)malloc(rep.size); 如果 rep.size 太大,可能是 300M,那将会崩溃。所以试试这个代码:
+ (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;
}