2015-04-03 85 views
5

有没有办法将视频保存在缓存中,然后在需要时进行修改?将视频保存在缓存中

NSCache *memoryCache; //assume there is a memoryCache for images or videos 
NSString *urlString = @"http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg"; 
NSString *path = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"A"] ofType:@"mov"]; 
NSURL *url = [NSURL fileURLWithPath:path]; 

NSData *downloadedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]]; 
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^
{ 
    if (downloadedData) 
    { 
     // STORE IN FILESYSTEM 
     NSString* path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
     NSString *file = [path stringByAppendingPathComponent:@"B.mov"]; 
     [downloadedData writeToFile:file options:NSDataWritingAtomic error:nil]; 
     NSLog(@"Cache File : %@", file); 

     // STORE IN MEMORY 
     [memoryCache setObject:downloadedData forKey:@"B.mov"]; 
    } 
    // NOW YOU CAN CREATE AN AVASSET OR UIIMAGE FROM THE FILE OR DATA 

}); 

我发现这个代码堆栈溢出,但它似乎并没有工作。

+0

欧普,你有你的答案吗? – Pawan 2015-04-06 09:07:31

+0

仍然混淆了缓存目录的行为 – 2015-04-06 09:10:50

+0

缓存目录的内容是否会在应用终止时被删除? – 2015-04-06 09:12:41

回答

3

您可以使用NSURLSessionDownloadTask下载视频或图像,直接写入临时目录。

在下载过程中,会话定期调用委托的 URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite: 方法与状态信息。

完成后,会话将调用代理的URLSession:downloadTask:didFinishDownloadingToURL: 方法或完成处理程序。在该方法中,您必须打开 阅读文件或将其移至应用程序的沙箱容器目录中的永久位置。

NSURL *URL = [NSURL URLWithString:@"http://blog.jimdo.com/wp-content/uploads/2014/01/tree-247122.jpg"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:URL]; 

NSURLSession *session = [NSURLSession sharedSession]; 
NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request 
                completionHandler: 
^(NSURL *location, NSURLResponse *response, NSError *error) { 
    NSString *documentsPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; 
    NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath]; 
    NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response 
    suggestedFilename]]; 
    [[NSFileManager defaultManager] moveItemAtURL:location 
              toURL:documentURL 
              error:nil]; 
    }]; 

    [downloadTask resume]; 

NSURLSessionDownloadTask Class Reference

0

NSCache就像NSDictionary中,但如果它检测到内存浪费清空自己。以下是文档:https://developer.apple.com/library/mac/documentation/Cocoa/Reference/NSCache_Class/

即使是小视频也很大,所以它可能会立即将其从内存中丢弃或拒绝将其存储在首位。

您可以将视频存储在存储在某种类型的单例中的NSDictionary中,但这会导致下一个问题:我无法理解为iOS设备在内存中存储视频的任何原因。只有很少的内存 - 比台式机少得多 - 但所有的iOS设备都具有异常快速的磁盘I/O。也就是说,在iOS设备上缓存视频非常昂贵,并且不会带来明显的好处。

因此,您可以创建一个单例,添加一个字典并将其存储在那里。但你真的不应该:只需要时从磁盘中检索它。