iOS下载网络图片并存储到沙盒目录下

xiaoxiao2021-02-27  374

//调用下面的方法model为一个实体类,可以传递一个网址

// model.urlId 为每一个网址图片的唯一标示,避免重复,如果重复会将原来图片覆盖 // model.urlStr = @"http://img1.126.net/channel6/2016/022471/0805/2.jpg?dpi=6401136" - (void)getData:(ADModel*)model{     NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];     DownloadImage([NSURL URLWithString:model.urlStr], ^(UIImage *image) {         [self saveImage:image withFileName:model.urlId ofType:@"jpg" inDirectory:documentsDirectoryPath];     }, ^{      }); } //获取网址并将图片转换成NSData 并且转成image通过block返回image如果失败返回错误信息 void DownloadImage ( NSURL * URL, void (^imageBlock)(UIImage * image), void (^errorBlock)(void) ) {     dispatch_async( dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_DEFAULT, 0 ), ^(void) { NSData * data = [[NSData alloc] initWithContentsOfURL:URL]; UIImage * image = [[UIImage alloc] initWithData:data]; dispatch_async( dispatch_get_main_queue(), ^(void){ if( image != nil ) { imageBlock( image ); } else { errorBlock(); } }); }); } //将图片存储到沙盒目录下存储成jpg形式 -(void) saveImage:(UIImage *)image withFileName:(NSString *)imageName ofType:(NSString *)extension inDirectory:(NSString *)directoryPath {     if ([[extension lowercaseString] isEqualToString:@"png"]) {         [UIImagePNGRepresentation(image) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"png"]] options:NSAtomicWrite error:nil];     } else if ([[extension lowercaseString] isEqualToString:@"jpg"] || [[extension lowercaseString] isEqualToString:@"jpeg"]) {         [UIImageJPEGRepresentation(image, 1.0) writeToFile:[directoryPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", imageName, @"jpg"]] options:NSAtomicWrite error:nil];     } else {         //ALog(@"Image Save Failed\nExtension: (%@) is not recognized, use (PNG/JPG)", extension);         NSLog(@"文件后缀不认识");     } } //获取图片 model1.urlId获取图片     NSString * documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];     NSString *filestr = [NSString stringWithFormat:@"/%@.jpg",_model1.urlId ];     NSString *newstr = [NSString stringWithFormat:@"%@%@",documentsDirectoryPath,filestr];     NSData *imageData = [NSData dataWithContentsOfFile:newstr];     UIImage* image = [[UIImage alloc] initWithData:imageData];     _imageview.image = image;

 

 

转载请注明原文地址: https://www.6miu.com/read-2109.html

最新回复(0)