我正在开发一个应用程序,我需要下载视频,然后对其进行一些编辑。所以,我正在使用 NSURLSession 下载视频,当我下载它时,我关闭应用程序然后再打开它。现在我不需要使用下载的视频,而是检查它是否已经下载,然后获取URL。这是我一直在使用的代码:
-(void)startDownloadingWithURLString:(NSString*)urlString{
NSURL *url = [NSURL URLWithString:urlString];
configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];
task = [self.urlSession downloadTaskWithURL:url];
[task resume];
}
#pragma mark - NSURLSession delagate methods
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager_ = [NSFileManager defaultManager];
NSURL *url = [NSURL URLWithString:[path stringByAppendingPathComponent:@"video.mp4"]];
if([fileManager_ fileExistsAtPath:[location path]]){
[fileManager_ replaceItemAtURL:url withItemAtURL:location backupItemName:nil options:NSFileManagerItemReplacementUsingNewMetadataOnly resultingItemURL:nil error:nil];
_videoURLPath = url;
}
UISaveVideoAtPathToSavedPhotosAlbum([url path
], nil, nil, nil);
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView_.progress = 0.0;
});
}
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite{
NSLog(@"%f",(double)totalBytesWritten/(double)totalBytesExpectedToWrite);
dispatch_async(dispatch_get_main_queue(), ^{
self.progressView_.progress = (double)totalBytesWritten/(double)totalBytesExpectedToWrite;
});
}
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error{
[KSToastView ks_showToast:@"Download complete"];
NSData *data = [NSData dataWithContentsOfURL:[NSURL fileURLWithPath:_videoURLPath.path]];
[AppHelper saveToUserDefaults:_videoURLPath.path withKey:@"videoURL"];
dispatch_async(dispatch_get_main_queue(), ^{
SAEditUploadViewController *editVC = [self.storyboard instantiateViewControllerWithIdentifier:@"SAEditUploadViewController"];
editVC.videoPathData = data;
[self.navigationController pushViewController:editVC animated:YES];
});
}