NSURLSession实现图片下载

本文主要介绍使用NSURLSession来实现图片下载,分别是带缓存的下载和无缓存下载

1.带缓存下载

    NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self preventNotRecognizedCharactersWithUrl:url]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    
    NSURLSession * session = [NSURLSession sharedSession];
    
    
    NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@", response);
        NSLog(@"%@", response.suggestedFilename);
        NSLog(@"%@", location.description);
        NSString * locationPath = [location.absoluteString substringFromIndex:7];
        if (!error) {
            NSString * cachePath = [self saveImageFileUrl];
            NSString * fileName = response.suggestedFilename;
            //缓存文件夹路劲
            NSString * savePath = [cachePath stringByAppendingPathComponent:fileName];
            NSURL * saveUrl = [NSURL fileURLWithPath:savePath];
            NSError * saveError;
            
            //判断下载的文件与缓存的是否一样,如果一样,使用缓存文件,如果不一样,替换或转移缓存文件
            
            if ([[NSFileManager defaultManager] contentsEqualAtPath:locationPath andPath:savePath]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    imageView.image = [UIImage imageWithContentsOfFile:savePath];
                });
            }else{
                //将tmp文件夹中的临时文件重命名后转移到缓存文件夹中
                [[NSFileManager defaultManager] copyItemAtURL:location toURL:saveUrl error:&saveError];
                if (!saveError) {
                    dispatch_async(dispatch_get_main_queue(), ^{
                        imageView.image = [UIImage imageWithContentsOfFile:savePath];
                    });
                }
            }
        }else{
            NSLog(@"%@", error.localizedDescription);
        }
    }];
    [downloadTask resume];

2.不带缓存下载

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[self preventNotRecognizedCharactersWithUrl:url]] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    
    
    NSURLSession * session = [NSURLSession sharedSession];
    
    
    NSURLSessionDownloadTask * downloadTask = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@", response);
        if (!error) {
            dispatch_async(dispatch_get_main_queue(), ^{
                //无缓存下载图片
                NSData * imageData = [NSData dataWithContentsOfURL:location];
                imageView.image = [UIImage imageWithData:imageData];
            });
        }else{
            NSLog(@"%@", error.localizedDescription);
        }
    }];
    [downloadTask resume];


上文中的自定义方法

//沙盒图片存储路劲
+(NSString *)saveImageFileUrl{
    NSString * imageUrl = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:@"/images"];
    
    NSFileManager *fileManager = [[NSFileManager alloc] init];
    // 判断文件夹是否存在,如果不存在,则创建
    if (![[NSFileManager defaultManager] fileExistsAtPath:imageUrl]) {
        [fileManager createDirectoryAtPath:imageUrl withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSLog(@"%@", imageUrl);
    return imageUrl;
}

//防止不被承认的字符
+(NSString *)preventNotRecognizedCharactersWithUrl:(NSString *)url{
    if (DeviceVersion >= 9.0) {
        //对url进行编译不被承认的字符(ios9 中新出的方法,替代[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];)
        url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    }else{
        url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    return url;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值