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

2016-10-08  本文已影响283人  Dove_Q
- (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;
}
上一篇下一篇

猜你喜欢

热点阅读