Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save a video in Cache

Is there a way to save a video in Cache Memory and then retrive the same when needed ?

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

});

I found this code on Stack Overflow, but it doesn't seem to work.

like image 918
Vaibhav Jhaveri Avatar asked Sep 29 '22 09:09

Vaibhav Jhaveri


1 Answers

You can use NSURLSessionDownloadTask for downloading video or image , directly write to temp directory.

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, 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

like image 140
Pawan Rai Avatar answered Oct 21 '22 19:10

Pawan Rai