我的代码工作得很好。我需要帮助或澄清的是Nested NSURLSessionDataTask
实例。 我正在进行两个异步调用,第二个调用依赖于第一个调用。在后台线程上嵌套NSURLSessionDataTask
因此,我做了第一个NSURLSessionDataTask
(firstUrlCall
)调用,它返回一个对象数组。对于我阵列中的每个对象,然后调用第二个NSURLSessionDataTask
(secondUrlCall
)并传入dataID
。
正如我前面提到的,它的工作原理。我只看到很多重复的行,并且重复的代码不是性感! 那么,有什么我可以做,以防止这种灾难?我需要我的代码是SEXY!
@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:很抱歉,如果你是从我的广泛使用这个词性感得罪 :)
我不认为代码有太多错误;块使得难以重复使用代码而不会使其复杂化。 – trojanfoe 2014-10-27 10:50:16
@trojanfoe这就是我害怕的。谢谢你 – 2014-10-27 14:35:33