在我的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方法,将tweets响应添加到“tweetsArray”)并为此我在两个地方放置“dispatch_sync” :
requestAccessToAccountsWithType:twitterAccountType
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
但是我无法做到这一点。
答案 0 :(得分:0)
也许您应该将代码更改为以下内容:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// put you twitter request here
dispatch_async(dispatch_get_main_queue(), ^{
[self changeMyInterfaceMethod: tweetsArray];
});
});