我尝试了以下代码来访问Twitter时间线。它没有从服务器收到任何数据。这里出了什么问题?
ACAccount *twitterAccount=[arrayOfAccounts lastObject];
NSURL *requestURL=[NSURL URLWithString:@"http://api.twitter.com/1/statuses/user_timeline.json"];
NSMutableDictionary *parameters=[NSMutableDictionary new];
//[parameters setObject:@"100" forKey:@"count"];
//[parameters setObject:@"1" forKey:@"include_entities"];
SLRequest *post=[SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:requestURL parameters:parameters];
post.account=twitterAccount;
[post performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
self.array=[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&error];
if(self.array.count !=0)
NSLog(@"%@",self.array);
else
NSLog(@"No Data Recived");
提前致谢。
答案 0 :(得分:4)
Twitter建议使用版本1.1而不是建议v1。在版本1.1 api https中,请尝试使用此网址https://api.twitter.com/1.1/statuses/user_timeline.json设置的此网址http://api.twitter.com/1/statuses/user_timeline.json。这项工作很好。
答案 1 :(得分:3)
API为您提供的NSError
个对象?他们的目的是告诉你出了什么问题。使用它们。
您的问题是您不知道发生了什么,因为您只是尝试转换为JSON。这可能是出错的原因:
要编写防御性代码(如果您想向公众发布此内容,那就是您想要的),您必须检查每个步骤以找出问题所在,以便您可以采取相应措施。是的,这将需要更多的代码,但更少的代码并不总是最好的选择。
具有更好错误处理的代码将更像这样。请注意它如何检查可能出错的每个步骤的结果:
[post performRequestWithHandler:^(NSData *response, NSHTTPURLResponse *urlResponse, NSError *error) {
if (response) {
// TODO: might want to check urlResponse.statusCode to stop early
NSError *jsonError; // use new instance here, you don't want to overwrite the error you got from the SLRequest
NSArray *array =[NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingMutableLeaves error:&jsonError];
if (array) {
if ([array isKindOfClass:[NSArray class]]) {
self.array = array;
NSLog(@"resulted array: %@",self.array);
}
else {
// This should never happen
NSLog(@"Not an array! %@ - %@", NSStringFromClass([array class]), array);
}
}
else {
// TODO: Handle error in release version, don't just dump out this information
NSLog(@"JSON Error %@", jsonError);
NSString *dataString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(@"Received data: %@", dataString ? dataString : response); // print string representation if response is a string, or print the raw data object
}
}
else {
// TODO: show error information to user if request failed
NSLog(@"request failed %@", error);
}
}];