我使用SDWebImage以异步方式加载图像。我想在下面的词典中结合评论和照片:
- (NSArray *) fetchPhotos:(NSArray *) requestedPhotoArray
{
NSMutableArray *photos;
UIImageView *imageview;
for (requestedPhoto in requestedPhotoArray) {
[imageview setImageWithURL:[NSURL URLWithString: requestedPhoto.url]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
NSDictionary *parameters = @{ @"function":GET_COMMENT,
@"photoId":requestedPhoto.photoID,
}
NSArray *comments = [[self.communicator sharedInstance] HTTPRequestWithParams:parameters];
Photo *photo = [Photo photoWithDictionary:
@{@"imageView": imageview,
@"comments" : comments,
}];
[photos addObject:photo];
}
return photos;
}
但是fetchPhotos函数会进行一次http调用并永远等待,然后什么都不返回。
fetchPhotos被调用如下(简化版):
NSDictionary *parameters = @{@"function":GET_PHOTO_INFO_ARRAY,
@"userid":3,
@"pageid":99,
}
dispatch_async(dispatch_get_global_queue(0, 0), ^{
requestedPhotosInfoArray = [[self.communicator sharedInstance] HTTPRequestWithParams:parameters];
dispatch_async(dispatch_get_main_queue(), ^{
[self fetchPhotos: requestedPhotosInfoArray];
}
communicator:HTTPRequestWithParams执行如下所示的HTTP请求
...
__block id result;
dispatch_queue_t queue = dispatch_queue_create("my_queue", 0);
dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
dispatch_async( queue, ^{
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
result = responseObject;
dispatch_semaphore_signal(semaphore);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
result = error;
dispatch_semaphore_signal(semaphore);
}
];
});
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
return result;
知道为什么fetchPhotos只返回第一个数据并永远等待?
更新:
我意识到它在等待
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
然后我在fetchPhotos
中添加一个异步调度队列 for (requestedPhoto in requestedPhotoArray) {
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(queue, ^{
[imageview setImageWithURL:[NSURL URLWithString:requestedPhoto.url] placeholderImage:[UIImage imageNamed:@" placeholder.png"]];
NSDictionary *parameters = @{ @"function":GET_COMMENT,
@"photoId":requestedPhoto.photoID,
}
NSArray *comments = [[self.communicator sharedInstance] HTTPRequestWithParams:parameters];
....
它现在不会永远等待,但它没有进行http呼叫。
答案 0 :(得分:0)
我使用了块回调而不是信号量
dispatch_async( queue, ^{
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success(responseObject);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}
];
});