解决办法见代码:
.h文件
@interface UIImageView (NXWebCache)
/**
给UIImageView扩展一个新的方法
URLStr 图片的url
placehold 占位图片
referer 请求数据时发送的链接 (从这个链接发送到服务器)
*/
- (void)nx_setImageWithURLStr:(NSString *)urlStr placehold:(NSString *)placehold withReferer:(NSString *)referer;
.m文件
@implementation UIImageView (NXWebCache)
- (void)nx_setImageWithURLStr:(NSString *)urlStr placehold:(NSString *)placehold withReferer:(NSString *)referer
{
if (placehold) {
self.image = [UIImage imageNamed:placehold];
}
if (urlStr) {
[self setImageURLStr:urlStr withReferer:referer];
}
}
- (void)setImageURLStr:(NSString *)urlStr withReferer:(NSString *)referer
{
// 通过主路径拼urlStr的路径
NSString *path = [[self getDownloadImgaeCachePath] stringByAppendingPathComponent:[self md5String:urlStr]];
// 判断是否有该路径
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
self.image = [UIImage imageWithContentsOfFile:path];
}
else
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
//设置请求头属性@"Referer"
[request setValue:referer forHTTPHeaderField:@"Referer"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
self.image = [UIImage imageWithData:data];
[data writeToFile:path atomically:YES];
}];
}
}
// 沙盒路径
- (NSString *)getDownloadImgaeCachePath
{
NSString *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
path = [path stringByAppendingPathComponent:@"DownloadImageCache"];
if (![[NSFileManager defaultManager] fileExistsAtPath:path])
{
[[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
return path;
}
// md5
- (NSString *)md5String:(NSString *)string
{
const char *str = [string UTF8String];
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, (CC_LONG)strlen(str), r);
return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}