有没有办法将视频保存在缓存中,然后在需要时将其恢复?
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 });
我在Stack Overflow上找到了这个代码,但它似乎不起作用.
解决方法
您可以使用NSURLSessionDownloadTask下载视频或图像,直接写入临时目录.
During download,the session periodically calls the delegate’s
URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:
method with status information.Upon completion,the session calls the delegate’s
URLSession:downloadTask:didFinishDownloadingToURL:
method or completion handler. In that method,you must either open the file for
reading or move it to a permanent location in your app’s sandBox container directory.
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,YES) firstObject]; NSURL *documentsDirectoryURL = [NSURL fileURLWithPath:documentsPath]; NSURL *documentURL = [documentsDirectoryURL URLByAppendingPathComponent:[response suggestedFilename]]; [[NSFileManager defaultManager] moveItemAtURL:location toURL:documentURL error:nil]; }]; [downloadTask resume];