我需要在应用程序开始时预加载和缓存所有(近 80 张)图像,同时向用户显示"请稍候"。我所做的是:
NSMutableArray *operations = [[NSMutableArray alloc] init];
for(Category *c in shop.menu.categories){
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:c.imagePath] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:request imageProcessingBlock:nil cacheName:@"nscache"
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
[operations addObject:operation];
for(Item *i in c.items){
NSURLRequest *request2 = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:i.imagePath] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30];
AFImageRequestOperation *operation2 = [AFImageRequestOperation imageRequestOperationWithRequest:request2 imageProcessingBlock:nil cacheName:@"nscache"
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){
}];
[operations addObject:operation2];
}
}
[[APIClient sharedClient] enqueueBatchOfHTTPRequestOperations:operations
progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations)
{
float percentDone = 100 * ((float)((int)numberOfCompletedOperations) / (float)((int)totalNumberOfOperations));
//appDelegateHUD.progress = percentDone;
NSLog([NSString stringWithFormat:@"%f", percentDone]);
}
completionBlock:^(NSArray *operations)
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate hideHUDWithDelay:0];
}];
使用此代码块,某些图像已成功缓存,但其他图像则不成功。我正在使用这个代码块:
AFImageRequestOperation *operation = [AFImageRequestOperation imageRequestOperationWithRequest:imageRequest
imageProcessingBlock:nil
cacheName:@"nscache"
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image){
[UIView beginAnimations:@"ToggleViews" context:nil];
[UIView setAnimationDuration:1.0];
imageview.image = image;
[UIView commitAnimations];
}
failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error){ NSLog([error description]); }
];
[operation start];
应直接显示图像,因为它们都应在缓存中。但是它们加载得很晚。我在某些代码中错了吗?
我认为您不会等待所有图像都将被下载
[[APIClient sharedClient] enqueueBatchOfHTTPRequestOperations:operations
progressBlock:^(NSUInteger numberOfCompletedOperations, NSUInteger totalNumberOfOperations)
{
float percentDone = 100 * ((float)((int)numberOfCompletedOperations) / (float)((int)totalNumberOfOperations));
//appDelegateHUD.progress = percentDone;
NSLog([NSString stringWithFormat:@"%f", percentDone]);
}
completionBlock:^(NSArray *operations)
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[appDelegate hideHUDWithDelay:0];
// here you just hide HUD, but here you should start load images to UI
}]
;