iOS 图片,视屏的下载和保存到相册

一:实现图片或者视屏的下载
必须添加代理

-(void)download:(NSString *)urlStr{
    //1.url(图片或者视屏地址)
       NSURL *url = [NSURL URLWithString: urlStr];
       
       //2.创建请求对象
       NSURLRequest *request = [NSURLRequest requestWithURL:url];
       
       //3.创建session
       NSURLSession * session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
       self.session = session;

       //4.创建Task
       NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithRequest:request];
       self.downloadTask = downloadTask;
       //5.执行Task
       [downloadTask resume];
  
}
#pragma mark NSURLSessionDownloadDelegate
/**
 *  写数据
 *
 *  @param session                   会话对象
 *  @param downloadTask              下载任务
 *  @param bytesWritten              本次写入的数据大小
 *  @param totalBytesWritten         下载的数据总大小
 *  @param totalBytesExpectedToWrite  文件的总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
{
    //1. 获得文件的下载进度
    float ps = 1.0 * totalBytesWritten/totalBytesExpectedToWrite;
    NSLog(@"%f",ps);
    self.zyCell.circleView.progress = ps;
    
}
 
/**
 *  当恢复下载的时候调用该方法
 *
 *  @param fileOffset         从什么地方下载
 *  @param expectedTotalBytes 文件的总大小
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didResumeAtOffset:(int64_t)fileOffset expectedTotalBytes:(int64_t)expectedTotalBytes
{
    NSLog(@"%s",__func__);
}
 
/**
 *  当下载完成的时候调用
 *
 *  @param location     文件的临时存储路径
 */
-(void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
{
    NSLog(@"%@",location);
    
    //1 拼接文件全路径
    NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:downloadTask.response.suggestedFilename];
  
    //2 必须要剪切文件, 因为系统默认会删除
    [[NSFileManager defaultManager]moveItemAtURL:location toURL:[NSURL fileURLWithPath:fullPath] error:nil];
    NSLog(@"%@",fullPath);
}
 
/**
 *  请求结束
 */
-(void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    NSLog(@"didCompleteWithError");
}

二:保存图片或者视屏到相册 同时判断是否存在

-(void)repostPlay:(Reposted *)rep{
    NSLog(@"相册中资源的唯一表示:%@",rep.localIdentifier);
    //用localIdentifier去相册中查找是否已经存在
    if(rep.localIdentifier != NULL){
        //返回一个PHAsset数组
        PHFetchResult *result = [PHAsset fetchAssetsWithLocalIdentifiers:@[rep.localIdentifier] options:nil];

        //获取PHAsset对象
        if(result.count>0){
            NSLog(@"已保存到相册");
            return;
        }
    }
    
    if(rep.mediaType==2){
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:rep.saveUrl];
        __block NSString *assetLocalIdentifier = nil;
        PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
        [photoLibrary performChanges:^{
            assetLocalIdentifier = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:[NSURL
        fileURLWithPath:filePath]].placeholderForCreatedAsset.localIdentifier;
            NSLog(@"视屏地址%@",assetLocalIdentifier);
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                NSLog(@"已将视频保存至相册");
                rep.localIdentifier = assetLocalIdentifier;
                //把唯一表示进行存储 方便进行查重
            } else {
                NSLog(@"未能保存视频到相册");
            }
        }];
    }else{
        NSString *filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:rep.saveUrl];
        __block NSString *assetLocalIdentifier = nil;
        PHPhotoLibrary *photoLibrary = [PHPhotoLibrary sharedPhotoLibrary];
        [photoLibrary performChanges:^{
            assetLocalIdentifier = [PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:[NSURL
        fileURLWithPath:filePath]].placeholderForCreatedAsset.localIdentifier;
            NSLog(@"图片地址%@",assetLocalIdentifier);
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (success) {
                NSLog(@"已将图片保存至相册");
                rep.localIdentifier = assetLocalIdentifier;
                //把唯一表示进行存储 方便进行查重
            } else {
                NSLog(@"未能保存图片到相册");
            }
        }];
       
    }
}

你可能感兴趣的:(iOS 图片,视屏的下载和保存到相册)