iOS 视频的下载保存

2020-08-31  本文已影响0人  断念的决绝
#pragma mark - loadData

- (void)newLoadData {
    
    NSString *name = [[NSFileManager defaultManager] displayNameAtPath:self.movieURL.path];
    NSString *filePath = [[self videoFilePath] stringByAppendingPathComponent:name];
    BOOL fileExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (fileExists)
    {
        NSLog(@"已经有视频了-----");
        [self videoPlayer:[NSURL fileURLWithPath:filePath]];
        return ;
    }
    
    NSString *documentsDirectory = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    NSString  *fullPath = [NSString stringWithFormat:@"%@%@",documentsDirectory, @"clockin.mp4"];
    NSURL *url = self.movieURL;
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    
    NSURLSessionDownloadTask *downTask = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {

        dispatch_async(dispatch_get_main_queue(), ^{
            
            self.progressView.hidden = NO;
            self.progressView.progress = downloadProgress.completedUnitCount*1.0/downloadProgress.totalUnitCount;
        });
        
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        
        return [NSURL fileURLWithPath:fullPath];
        
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        
        NSString *name = [[NSFileManager defaultManager] displayNameAtPath:self.movieURL.path];
        NSString *savefilePath = [[self videoFilePath] stringByAppendingPathComponent:name];
        [[NSFileManager defaultManager] moveItemAtPath:filePath.path toPath:savefilePath error:nil];
        BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:savefilePath];
        
        if (isExists)
        {
            [self videoPlayer:[NSURL fileURLWithPath:savefilePath]];
        }
        
    }];
    
    [downTask resume];
    
}
- (NSString *)videoFilePath {
    
    NSString *path = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    NSString *filePath = [path stringByAppendingPathComponent:@"clockin_movie_file"];
    BOOL isExists = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
    if (!isExists)
    {
        [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}

上一篇下一篇

猜你喜欢

热点阅读