ios - 使用 Fabric SDK iOS 访问 Twitter 用户时间线

标签 ios twitter restkit twitter-fabric

这两天我一直在努力解决这个问题。我正在使用 Fabric SDK 和 Rest 工具包,尝试为 Twitter 使用不同的 Rest API Web 服务。我可以使用具有 authTokenSecretauthToken 和其他值的 session 对象的 TWTRLogInButton 成功登录。当我尝试获取用户时间线时,我总是会收到失败响应:

{"errors":[{"code":215,"message":"Bad Authentication data."}]}

完整的错误日志是:

E restkit.network:RKObjectRequestOperation.m:297 Object request failed: Underlying HTTP request operation failed with error: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x1780f6f80 {NSLocalizedRecoverySuggestion={"errors":[{"code":215,"message":"Bad Authentication data."}]}, NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0x178202740> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p }, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x1702271e0> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p } { status code: 400, headers {
    "Content-Encoding" = gzip;
    "Content-Length" = 87;
    "Content-Type" = "application/json;charset=utf-8";
    Date = "Wed, 01 Apr 2015 09:46:42 GMT";
    Server = "tsa_a";
    "Strict-Transport-Security" = "max-age=631138519";
    "x-connection-hash" = 4c123a59a023cd86b2e9a3e9fc84cd7b;
    "x-response-time" = 4;
} }, NSLocalizedDescription=Expected status code in (200-299), got 400}


2015-04-01 14:47:13.223 TwitterIntegration[1086:60b] I restkit.network:RKHTTPRequestOperation.m:154 GET 'https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p'
2015-04-01 14:47:13.225 TwitterIntegration[1086:60b] E restkit.network:RKHTTPRequestOperation.m:178 GET 'https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p' (400 Bad Request) [0.0013 s]: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x1780f6f80 {NSLocalizedRecoverySuggestion={"errors":[{"code":215,"message":"Bad Authentication data."}]}, NSErrorFailingURLKey=https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0x178202740> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p }, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0x1702271e0> { URL: https://api.twitter.com/1.1/statuses/user_timeline.json?user_id=3116882322&count=2&screen_name=ann_10p } { status code: 400, headers {
    "Content-Encoding" = gzip;
    "Content-Length" = 87;
    "Content-Type" = "application/json;charset=utf-8";
    Date = "Wed, 01 Apr 2015 09:46:42 GMT";
    Server = "tsa_a";
    "Strict-Transport-Security" = "max-age=631138519";
    "x-connection-hash" = 4c123a59a023cd86b2e9a3e9fc84cd7b;
    "x-response-time" = 4;
} }, NSLocalizedDescription=Expected status code in (200-299), got 400}

代码:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self addLoginButton];

}

-(void) addLoginButton
{
    TWTRLogInButton *logInButton = [TWTRLogInButton buttonWithLogInCompletion:^(TWTRSession *session, NSError *error) {
        // play with Twitter session


        if(session)
        {
            NSLog(@"logged in success! with session : %@", session);
            [Global sharedInstance].session = session;
            [self requestUserTimeline];
        }
        else
        {
            NSLog(@"session is null");

        }

    }];
    logInButton.center = self.view.center;
    [self.view addSubview:logInButton];

}

-(void) requestUserTimeline
{
    RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[UserTimeline class]];
    [mapping addAttributeMappingsFromDictionary:@{
                                                  @"text":   @"tweetText",
                                                  @"favorited":     @"favourited",
                                                  @"created_at":        @"createdAt",
                                                  @"user.name":        @"name",
                                                  @"id":        @"tweetID",
                                                  @"user.profile_image_url":  @"profileImageURL"
                                                  }];

    NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful); // Anything in 2xx
    RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:mapping pathPattern:nil keyPath:nil statusCodes:statusCodes];
    NSString *params = [NSString stringWithFormat:@"?user_id=3116882322&count=2&screen_name=ann_10p",[Global sharedInstance].session.userID,[Global sharedInstance].session.userName];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[@"https://api.twitter.com/1.1/statuses/user_timeline.json" stringByAppendingString:params]]];
    [request setHTTPMethod:@"GET"];
    RKObjectRequestOperation *operation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[responseDescriptor]];
    [operation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
        UserTimeline *timeline = [result firstObject];
        NSLog(@"Mapped the article: %@", timeline);
    } failure:^(RKObjectRequestOperation *operation, NSError *error) {
        NSLog(@"Failed with error: %@", [error localizedDescription]);
    }];
    [operation start];
}

请帮助我调试这个问题。谢谢。

最佳答案

在尝试使用 Fabric SDK 后,我成功地集成了它。我得出了一些结论,想与大家分享。

1) 当您第一次成功登录 twitter 时,TWTRSession session 已为用户创建。即使您关闭应用程序并重新打开它,它也会持续存在。

2) 如果已经为您创建了 session ,并且您尝试登录获取另一个 session 对象而不注销,将返回身份验证错误。

3) 您可以使用以下方法检查 session 是否存在:

if([[Twitter sharedInstance] session])
{
   NSLog(@"session already present!!!");
   NSLog(@"signed in as %@", [[[Twitter sharedInstance] session] userName]);
}
else
{
NSLog(@"you need to login!!");
}

4) 我会推荐使用

登录

[[Twitter sharedInstance] logInWithCompletion:^(TWTRSession *session, NSError *error)];

代替:

[TWTRLogInButton buttonWithLogInCompletion:^(TWTRSession *session, NSError *error)];

Use Twitter's login button only, when you are sure that no session exists currently.

5) 如果 Twitter 的身份验证真的让您感到厌烦,请卸载该应用程序并尝试全新安装。 这是最后的解决方案!

6) 要退出 session ,请使用 [[Twitter sharedInstance] logOut];

编码部分:

我假设您已经完成了 fabric mac app 的所有步骤。

先登录用户,再进行时间线请求。

-(void) loginUserToTwitter
{
    if([[Twitter sharedInstance] session])
    {
        NSLog(@"session already present!!!");
        NSLog(@"signed in as %@", [[[Twitter sharedInstance] session] userName]);
        [self getUserTimeline];
    }
    else
    {
        NSLog(@"session not found. Make new request!");

        [[Twitter sharedInstance] logInWithCompletion:^(TWTRSession *session, NSError *error) {

            if(error)
                NSLog(@"error occurred... %@",error.localizedDescription);
            else
            {
                NSLog(@"Successfully logged in with session :%@",session);
               [self getUserTimeline];
            }

        }];
    }

}

-(void) getUserTimeline
{
    NSURLRequest *request = [[[Twitter sharedInstance] APIClient] URLRequestWithMethod:@"GET" URL:@"https://api.twitter.com/1.1/statuses/user_timeline.json"
       parameters:@{@"userid": [Twitter sharedInstance].session.userID,
       @"count" : @"5",
        @"screen_name" : [Twitter sharedInstance].session.userName} error:nil];

    NSURLResponse *response;
    NSError *error;
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if(!data)
    {
        NSLog(@"error....: %@",error.localizedDescription);
    }
    else
    {
        NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
        NSLog(@"%@",string);

        [twitterResponse removeAllObjects];

        NSArray *arrayRep = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        twitterResponse = [NSMutableArray arrayWithArray:[TWTRTweet tweetsWithJSONArray:arrayRep]];

        [_tableView reloadData];
    }
}

我更喜欢 Twitter SDK 的方法来使用 [TWTRTweet tweetsWithJSONArray:arrayRep] 而不是 Restkit 来提取推文。在这里事情会很容易处理。

以 Twitter 的标准样式显示推文:

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    // Setup tableview
    self.tableView.estimatedRowHeight = 150;
    self.tableView.rowHeight = UITableViewAutomaticDimension; // Explicitly set on iOS 8 if using automatic row height calculation
    self.tableView.allowsSelection = NO;
    [self.tableView registerClass:[TWTRTweetTableViewCell class] forCellReuseIdentifier:@"TweetCell"];

}

#pragma mark - Tableview Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return twitterResponse.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"TweetCell";

    TWTRTweetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID forIndexPath:indexPath];

    TWTRTweet *tweet = twitterResponse[indexPath.row];
    [cell configureWithTweet:tweet];

    return cell;
}

// Calculate the height of each row. Must to implement
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        TWTRTweet *tweet = twitterResponse[indexPath.row];
        return [TWTRTweetTableViewCell heightForTweet:tweet width:CGRectGetWidth(self.view.bounds)];

}

注意:

here下载Fabric SDK .您将必须输入电子邮件地址。他们会通过电子邮件向您发送一些下载链接,您必须按照一些步骤操作。 Fabric Mac App 将让您完全配置 xcode 项目。

希望对您有所帮助!

引用资料:

Twitter Login

Show Tweets

Cannonball Sample Project

关于ios - 使用 Fabric SDK iOS 访问 Twitter 用户时间线,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389474/

相关文章:

php - GET 到 POST 更改后身份验证不再有效

ios - 使用 RestKit,有没有一种方法可以在单个对象上的对象映射完成时运行代码?

ios - 当推送通知到达设备并将有效负载值传递给目标 ViewController 时,如何在 Appdelegate 上执行 Segue?

ios - 如何添加两个标签作为空的 UITableView 背景而不是 swift 中的一个?

iphone - 自定义 UITableViewCell 未显示时始终为 null

iphone - iOS 中的多个对象管理器

objective-c - RESTKit 通信错误

ios - 通知中心未在我的 obj c 类( utills 类或对象类)中触发。不是 View Controller

java - Twitter4j TwitterStream 无法获取所有推文

php - 不使用 MySQL 的资源 ID #3