以下代码成功从链接获取图像并存储到我的缓存目录中。但我希望从不同的网址获得许多(如100)图像(但在同一网站上,只有文件名不同)。这适用于拍摄这些图像,但我需要等待很长时间。无论如何都可以轻松获取图像并使我的响应时间更快。
NSString *UCIDLink = [NSString stringWithFormat:@"http://www.example.com/picture.png];
NSURL * imageURL = [NSURL URLWithString:UCIDLink];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *filePath = [[paths objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"picture.png"]];
NSError *writeError = nil;
[imageData writeToFile:filePath options:NSDataWritingAtomic error:&writeError];
if (writeError) {
NSLog(@"Success");
}else{
NSLog(@"Failed");
}
ghgh
答案 0 :(得分:1)
您使用的代码需要时间来加载图像内容。所以,更喜欢异步加载图像。
使用以下代码:
dispatch_queue_t q = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul);
dispatch_async(q, ^{
/* Fetch the image from the server... */
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
/* This is the main thread again, where we set the tableView's image to
be what we just fetched. */
cell.imgview.image = img;
});
});
或者您可以使用:
AsyncImageView *asyncImageView = [[AsyncImageView alloc]initWithFrame:CGRectMake(30,32,100, 100)];
[asyncImageView loadImageFromURL:[NSURL URLWithString:your url]];
[YourImageView addSubview:asyncImageView];
[asyncImageView release];
从这里下载文件..... https://github.com/nicklockwood/AsyncImageView 强>
答案 1 :(得分:0)
使用多线程以便同时进行多次图像提取。这样,你可以减少很多等待时间。