1,获取图片类型
jpg 和 gif 的保存 方式不同。
//获取图片类型
NSString * imageType = [self.slide_pic componentsSeparatedByString:@"."].lastObject;
2,下载图片
/**
* 下载新图片,根据类型不同使用不同的保存方式
*/
- (void)downloadAdImageWithUrl:(NSString *)imageUrl imageName:(NSString *)imageName
{
//保存 gif 类型
__weak typeof(self) weakSelf = self;
if([[_imageType lowercaseString] isEqualToString:@"gif"]){
NSString *filePath = [self getFilePathWithImageName:imageName];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSURL *url = [NSURL URLWithString:_imgUrl];
NSURLSessionDownloadTask *task = [session downloadTaskWithURL:url completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (error) {
NSLog(@"gif download error:%@", error);
} else {
NSLog(@"gif download success, file path:%@",location.path);
// 这个方法下载的图片在 tmp 目录,移动到缓存目录下。
[self savaSuccess:imageName];
NSFileManager *manager = [NSFileManager defaultManager];
[manager moveItemAtPath:location.path toPath:filePath error:nil];
}
}];
[task resume];
}else if(_imageType != nil){
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
SDWebImageManager *sdimage = [[SDWebImageManager alloc]init];
[sdimage loadImageWithURL:[NSURL URLWithString:imageUrl] options:SDWebImageRetryFailed context:nil progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
__strong typeof(self) strongSelf = weakSelf;
NSString *filePath = [self getFilePathWithImageName:imageName];
if ([UIImagePNGRepresentation(image) writeToFile:filePath atomically:YES]) {
// 保存成功
[strongSelf savaSuccess:imageName];
}else{
NSLog(@"保存失败");
}
}];
});
}
}
/// 保存图片后的操作
/// @param imageName 图片名
-(void)savaSuccess:(NSString *)imageName{
NSLog(@"保存成功");
//删除旧广告图片
[self deleteOldImage];
//设置新图片
[UserDefaults setValue:imageName forKey:adImageName];
//设置广告链接
[UserDefaults setValue:_adUrl forKey:adUrl];
[UserDefaults setValue:_adOpenType forKey:adOpen];
[UserDefaults synchronize];
}
/**
* 根据图片名拼接文件路径
*/
- (NSString *)getFilePathWithImageName:(NSString *)imageName
{
if (imageName) {
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) firstObject];
NSString *imgPath =[cachesPath stringByAppendingPathComponent:imageName];
return imgPath;
}
return nil;
}
/**
* 删除旧图片
*/
- (void)deleteOldImage
{
NSString *imageName = [UserDefaults valueForKey:adImageName];
if (imageName) {
NSString *imgPath = [self getFilePathWithImageName:imageName];
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:imgPath error:nil];
}
}
3,显示图片
sdwebimage 可以加载 gif 会动,imageview 直接加载 gif 不会动。
[_adView sd_setImageWithURL:[NSURL fileURLWithPath:_imgPath]];
网友评论