美文网首页
扩展UIImageView根据URL直接设置图片,且进行缓存

扩展UIImageView根据URL直接设置图片,且进行缓存

作者: Dove_Q | 来源:发表于2016-10-08 08:52 被阅读283次
    - (void)setImageWithURL:(NSString *)url {
        if (!url.length) {
            return;
        }
        NSString *bathPath = [NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
        NSOperationQueue *queue = [NSOperationQueue new];
        NSString *cacheFilePath = [bathPath stringByAppendingPathComponent:[self cacheFileNameWithURL:url] ];
        if ([[NSFileManager defaultManager] fileExistsAtPath:cacheFilePath isDirectory:nil]) {
            [queue addOperationWithBlock:^{
                NSData *data = [NSData dataWithContentsOfFile:cacheFilePath];
                if (data) {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        self.image = [UIImage imageWithData:data];
                    }];
                }
            }];
        }
        else {
            [queue addOperationWithBlock:^{
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];
                if (data) {
                    [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                        self.image = [UIImage imageWithData:data];
                        [data writeToFile:cacheFilePath atomically:YES];
                    }];
                }
            }];
        }
    }
    
    - (NSString *)cacheFileNameWithURL: (NSString *)url {
        NSArray *tempArr = [url componentsSeparatedByString:@"/"];
        NSString *cacheFileName = tempArr.lastObject;
        return cacheFileName;
    }
    

    相关文章

      网友评论

          本文标题:扩展UIImageView根据URL直接设置图片,且进行缓存

          本文链接:https://www.haomeiwen.com/subject/zrbyyttx.html