我的代碼工作得很好。我需要幫助或澄清的是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