2015-04-03 74 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設備上緩存視頻非常昂貴,並且不會帶來明顯的好處。

因此,您可以創建一個單例,添加一個字典並將其存儲在那裏。但你真的不應該:只需要時從磁盤中檢索它。