博客> 模拟多线程图片下载SD_Image
模拟多线程图片下载SD_Image
2019-12-16 05:57 评论:0 阅读:802 wolimomo
MD5

import

import "UIImageView+WebCache.h"

@implementation UIImageView (WebCache)

//post ---> md5

  • (NSString )md5:(NSString )str { const char cStr = [str UTF8String]; unsigned char result[16]; CC_MD5(cStr, strlen(cStr), result); // This is the md5 call return [NSString stringWithFormat: @"xxxxxxxxxxxxxxxx", result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7], result[8], result[9], result[10], result[11], result[12], result[13], result[14], result[15] ]; } // -(NSString )getFilePath:(NSString *)url { //url return [NSString stringWithFormat:@"%@/Documents/%@",NSHomeDirectory(),[self md5:url]]; }

-(void)setImageWithURL:(NSString )url placeholderImage:(NSString )imageName { // NSLog(@"%@",[self getFilePath:url]);

if([[NSFileManager defaultManager] fileExistsAtPath:[self getFilePath:url]])
{
    self.image = [UIImage imageWithData:[NSData dataWithContentsOfFile:[self getFilePath:url]]];
}
else
{
    self.image = [UIImage imageNamed:imageName];

    [NSThread detachNewThreadSelector:@selector(downloadImage:) toTarget:self withObject:url];
}

}

-(void)updateUI:(NSData *)data { self.image = [UIImage imageWithData:data]; }

-(void)downloadImage:(NSString )url { NSData data = [NSData dataWithContentsOfURL:[NSURL URLWithString:url]];

[self performSelectorOnMainThread:@selector(updateUI:) withObject:data waitUntilDone:NO];

[data writeToFile:[self getFilePath:url]  atomically:YES];

}

收藏
0
sina weixin mail 回到顶部