[英]HTTP call runs first time but then waits forever
我正在使用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調用。
我使用了塊回調而不是信號量
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);
}
}
];
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.