我正在UITableView
使用CustomCell
. CustomCell
包含UIImageView
和 2 UILabel
。在UIImageView
我想从URL加载图像并且我想保存在我的文档目录中。
这是我尝试过的代码,
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[URLarr objectAtIndex:indexPath.row]];//arr is NSMutablearray of image URL
UIImage *img1 = [UIImage imageWithContentsOfFile:savedImagePath];
if (!img1 || [UIImagePNGRepresentation(img1) length] <=0)
{
id path =[URLarr objectAtIndex:indexPath.row];
path = [path stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSURL *url = [NSURL URLWithString:path];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:url, [NSString stringWithFormat:@"%d", indexPath.row+1], nil ];
[self performSelectorInBackground:@selector(loadImageInBackground:) withObject:arr];
}
还有这个。
//—————————————-lazy loading———————–
- (void)loadImageInBackground:(NSArray *)urlAndTagReference
{
NSData *imgData = [NSData dataWithContentsOfURL:[urlAndTagReference objectAtIndex:0]];
UIImage *imgload = [[UIImage alloc] initWithData:imgData];
NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:imgload, [urlAndTagReference objectAtIndex:1], nil];
[self performSelectorOnMainThread:@selector(assignImageToImageView:) withObject:arr waitUntilDone:YES];
}
- (void) assignImageToImageView:(NSArray *)imgAndTagReference
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:[URLarr objectAtIndex:[[imgAndTagReference objectAtIndex:1] intValue]-1]];
UIImage* imageToSave = savedImagePath;
NSData *imageData = UIImagePNGRepresentation(imageToSave);
[imageData writeToFile:savedImagePath atomically:NO];
}
崩溃原因显示NSInvalidArgumentException。图像也没有显示在UITableViewCell
. 任何帮助,将不胜感激。