我使用AFNetworking库来调用Web服务。我的应用程序在集合视图单元格和表格视图单元格中有图像视图每次加载我的应用程序时,都需要花费大量时间来加载图像。所以我想要一种从缓存加载图像的方法。我附上了我的部分代码。
layout-weight
这是返回单元格
- (void)loadcategoryData
{
post = nil;
NSString *mainurl = [NSString stringWithFormat:@"some url"];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
[manager GET:mainurl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
posts = (NSDictionary *)responseObject;
post = [NSMutableArray array];
for(NSDictionary *all in posts)
{
Categories *category = [Categories new];
category.title = [all objectForKey:@"catname"];
category.firsturl = [all objectForKey:@"url"];
[self.maincollectionView reloadData];
//call for images
imagespost = nil;
NSString *imageUrl = [NSString stringWithFormat:@"%@", category.firsturl];
AFHTTPRequestOperationManager *managerone = [AFHTTPRequestOperationManager manager];
[managerone GET:imageUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
imagesposts = (NSDictionary *)responseObject;
NSArray *resultone = [imagesposts objectForKey:@"posts"];
imagespost = [NSMutableArray array];
if ([resultone count]) {
NSDictionary *firstpost = resultone[0];
// Categories *newmogocat = [Categories new];
NSDictionary *thumbnail_images = [firstpost objectForKeyedSubscript:@"thumbnail_images"];
NSDictionary *thumbnail = [thumbnail_images objectForKey:@"thumbnail"];
category.imageOneUrl = [NSString stringWithFormat:@"%@",[thumbnail objectForKey:@"url"]];
// NSLog(@"%@", newmogocat.imageOneUrl);
// [imagespost addObject:newmogocat];
[post addObject:category];
[self.maincollectionView reloadData];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
UIAlertView *erroralert = [[UIAlertView alloc] initWithTitle:@"Something Wrong!" message:[NSString stringWithFormat:@"%@", error.localizedDescription] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[erroralert show];
}];
}
} failure:^(AFHTTPRequestOperation *operation, NSError * responseObject) {
}];
}
- (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse
{
NSMutableDictionary *mutableUserInfo = [[cachedResponse userInfo] mutableCopy];
NSMutableData *mutableData = [[cachedResponse data] mutableCopy];
NSURLCacheStoragePolicy storagePolicy = NSURLCacheStorageAllowedInMemoryOnly;
return [[NSCachedURLResponse alloc] initWithResponse:[cachedResponse response] data:mutableData userInfo:mutableUserInfo storagePolicy:storagePolicy];
}
答案 0 :(得分:1)
你需要的是一个单独的课程。该类的每个对象都知道如何异步下载单个图像,并缓存它以及通知与图像准备显示相关联的图像视图...
幸运的是你AFNetworking已经为你写了这封信。看看它对UIImageView的扩展。使用此扩展程序,您只需将图像的URL传递给UIImageView(使用setImageWithURL
),它就可以为您完成所有艰苦的工作。
对于那些不使用AFNetworking的人,Apple有示例代码:https://developer.apple.com/library/ios/samplecode/LazyTableImages/Introduction/Intro.html