我正在使用AFNetworking从我的应用程序中的服务器下载 json 和图像。我想使用 AFNetworking 以串行顺序下载图像,但响应顺序不正确,因为它以随机顺序提供图像。单击时,我在轮播中有缩略图,我想显示同一选定图像的更大图像,但是通过使用 AFNetworking,当我单击轮播图像时,我得到了随机图像。
我可以使用 GCD 中的串行队列来完成任务,但我想使用 AFNetworking 来完成任务。怎么做请建议。
以下是我使用 GCD 以串行顺序下载的代码
-(void)downloadImages:(NSMutableArray *)twitterThumbnailUrl withtwitterImages:(NSMutableArray *)twitterImageUrl
{
dispatch_queue_t queue;
queue = dispatch_queue_create("myImageQueue", NULL);
for(int i = 0; i<twitterThumbnailUrl.count; i++) {
NSURL *imageUrl = [NSURL URLWithString:[twitterThumbnailUrl objectAtIndex:i]];
NSURL *mainUrl = [NSURL URLWithString:[twitterImageUrl objectAtIndex:i]];
dispatch_async(queue, ^{
// do your stuff in the right order
NSData *imageData = [NSData dataWithContentsOfURL:imageUrl];
NSData *imgData = [NSData dataWithContentsOfURL:mainUrl];
UIImage *image = [UIImage imageWithData:imageData];
UIImage *mainImage = [UIImage imageWithData:imgData];
if (image != NULL) {
[self.twitterImages addObject:image];
NSLog(@"num = %d", i);
}
if (mainImage != NULL) {
[self.celebImageArray addObject:mainImage];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.carousel reloadData];
[spinner stopAnimating];
});
});
}
}
下面是使用 AFNetworking 的代码
-(void)downloadTwitterImages:(NSString *)twitterImagesUrl
{
// download the photo
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:twitterImagesUrl]];
AFImageRequestOperation *operation = [AFImageRequestOperation
imageRequestOperationWithRequest:request
imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
if (image != nil) {
[self.celebImageArray addObject:image];
}
[self.carousel reloadData];
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", error.description);
}];
[operation start];
}
我将如何在 AFNetworking 中进行相同的归档。请帮忙
更新:
我从这篇文章[链接]中尝试了这种方法,它正在按顺序下载图像
这是我的代码。如果我在这里做错了什么,请纠正我
- (void) downloadTwitterImages:(NSMutableArray *)thumbnailArray {
{
[_thumbDownloadQueue cancelAllOperations];
_thumbDownloadQueue = [[NSOperationQueue alloc] init];
self.twitterImages = [[NSMutableArray alloc] init];
}
AFImageRequestOperation *previousOperation = nil;
for (NSUInteger i = 0; i<[thumbnailArray count]; i++) {
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[thumbnailArray objectAtIndex:i]]];
AFImageRequestOperation *operation = [AFImageRequestOperation
imageRequestOperationWithRequest:request
imageProcessingBlock:nil
success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image)
{
if (image != nil) {
NSLog(@"thumbnail downloaded %@", image);
[self.twitterImages addObject:image];
}
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {
NSLog(@"%@", error.description);
}];
if (previousOperation) {
[operation addDependency:previousOperation];
}
previousOperation = operation;
[_thumbDownloadQueue addOperation:operation];
}
}