有没有办法将视频保存在缓存中,然后在需要时将其恢复?
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];
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。