在我的 iOS 应用程序中,我在 Utility 类中从 Twitter 获取推文,然后更新主类 UITableView(单元格显示单个推文)。下面是我的代码:
NSMutableArray *tweetsArray = [[NSMutableArray alloc]init];
+ (NSMutableArray *)getTweetStatus:(NSString *)myData{
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterAccountType =
[store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
dispatch_queue_t myCustomQueue;
myCustomQueue = dispatch_queue_create("com.example.MyCustomQueue", NULL);
[store requestAccessToAccountsWithType:twitterAccountType
withCompletionHandler:^(BOOL granted, NSError *error) {
dispatch_sync(myCustomQueue, ^{
if (!granted) {
// The user rejected your request
NSLog(@"User rejected access to the account.");
}
else {
// Grab the available accounts
NSArray *twitterAccounts =
[store accountsWithAccountType:twitterAccountType];
if ([twitterAccounts count] > 0) {
// Use the first account for simplicity
ACAccount *account = [twitterAccounts objectAtIndex:0];
// Now make an authenticated request to our endpoint
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
[params setObject:@"1" forKey:@"include_entities"];
// The endpoint that we wish to call
NSURL *url = [NSURL URLWithString:@"http://api.twitter.com/1/statuses/home_timeline.json"];
// Build the request with our parameter
TWRequest *request =
[[TWRequest alloc] initWithURL:url
parameters:params
requestMethod:TWRequestMethodGET];
// Attach the account object to this request
[request setAccount:account];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_sync(myCustomQueue, ^{
if (!responseData) {
// inspect the contents of error
NSLog(@"%@", error);
}
else {
NSError *jsonError;
NSMutableArray *tweets =[NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&jsonError];
if (tweets) {
// at this point, we have an object that we can parse
NSLog(@"%@", tweets);
}
else {
// inspect the contents of jsonError
NSLog(@"%@", jsonError);
}
[tweetsArray addObjectsFromArray:tweets];
}
});
}];
}
}
});
}];
return tweetsArray;
}
问题是我不想在收到响应之前“返回 tweetsArray”(即从 TWRequest performRequestWithHandler 方法获取响应,该方法将推文响应添加到“tweetsArray”中),为此我将“dispatch_sync”放在两个地方:
- 在
requestAccessToAccountsWithType:twitterAccountType
- 在
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
但我不能这样做。