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下载视频或图像,直接写入临时目录.
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 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |