我的密码工作得很好。我需要帮助或澄清的是嵌套的NSURLSessionDataTask实例。我正在进行两个异步调用,第二个调用依赖于第一个调用。
因此,我进行了第一个NSURLSessionDataTask (firstUrlCall)调用,它返回一个对象数组。然后,对数组中的每个对象调用第二个NSURLSessionDataTask (secondUrlCall)并传入一个dataID。
正如我之前提到的,它有效。我只是看到很多行重复和重复代码是不性感的!,那么,我有什么可以做的,以防止这场灾难吗?我需要我的代码让性感!
@property (nonatomic, strong) NSURLSession *Session;优先调用
-(void) firstUrlCall {
NSString *urlString = @"https://api.FIRSTURLCALL.com";
NSURLSessionDataTask *dataTask = [session
dataTaskWithURL:[NSURL URLWithString:urlString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
NSDictionary *returnData = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
[returnData enumerateKeysAndObjectsUsingBlock:^(id dataID, id obj, BOOL *stop) {
/*
-->here is where I call secondUrlCall<--
*/
[self secondUrlCall:dataID];
}];
}
});
}];
[dataTask resume];
}第二次呼叫
-(void) secondUrlCall:(NSString *)dataID {
NSString *urlString = [NSString stringWithFormat:@"https://api.SECONDURLCALL.com?dataID=%@",dataID];
NSURLSessionDataTask *dataTask = [session
dataTaskWithURL:[NSURL URLWithString:urlString]
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (!error) {
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
if ([[json objectForKey:@"type"] isEqualToString:@"sexy"]) {
[tableArray addObject:json];
// Reload table data
[self.tableView reloadData];
}
}
});
}];
[dataTask resume];
}PS:对不起,如果你被我广泛使用的“性感”这个词激怒了, :)
发布于 2014-10-30 10:16:49
我的天哪!如果网络是断断续续的,或者中途下降了呢?
我将获取第一个调用的结果,并将每个调用放入一个操作队列中,然后当处理每个操作失败时,您可以重新对其进行排队。
https://stackoverflow.com/questions/26585746
复制相似问题