访问Twitter时间表帐户出了什么问题?

我尝试了下面的代码来获取访问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"); 

提前致谢。

Twitter有build议使用版本1.1不build议v1。 在版本1.1 api的https,所以尝试使用这个urlhttps://api.twitter.com/1.1/statuses/user_timeline.json固定的这个urlhttp://api.twitter.com/1/statuses/user_timeline.json 。 这项工作很好。

API提供的那些NSError对象? 他们的目的是告诉你哪里出了问题。 使用它们。

你的问题是,你不知道发生了什么,因为你只是试图转换为JSON。 那可能是错误的:

  • 请求失败(例如networking问题)
  • 你无权做任何你所做的事情
  • 返回的数据实际上不是JSON
  • JSON对象不是一个数组(会导致崩溃)。

要编写防御性代码(如果你想把这个东西发布给公众,这就是你想要的),你必须检查每个步骤来找出错误,所以你可以采取相应的行动。 是的,这将需要更多的代码,但更less的代码并不总是最好的select。

更好的error handling代码会更像这样。 注意它是如何检查每一步可能出错的结果:

 [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); } }];