ios – 在缓存中保存视频

有没有办法将视频保存在缓存中,然后在需要时将其恢复?

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];

NSURLSessionDownloadTask Class Reference

相关文章

在有效期内的苹果开发者账号(类型为个人或者公司账号)。还...
Appuploader官网--IOS ipa上传发布工具,证书制作工具跨平台...
苹果在9月13号凌晨(北京时间)发布 iOS 16,该系统的设备可...
计算机图形学--OpenGL递归实现光线追踪
Xcode 14打出来的包在低版本系统运行时会崩溃,报错信息是Li...