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

使用Fabric SDK iOS访问Twitter用户时间线,第1张

概述我试图在这个问题上挣扎两天.我正在使用Fabric SDK和Rest工具包,试图为Twitter使用不同的Rest API Web服务.我可以使用具有authTokenSecret,authToken和其他值的会话对象的TWTRLogInButton成功登录.当我尝试获取用户时间线时,我总是得到失败的响应,作为: {“errors”:[{“code”:215,“message”:“Bad Auth 我试图在这个问题上挣扎两天.我正在使用Fabric SDK和Rest工具包,试图为Twitter使用不同的Rest API Web服务.我可以使用具有authTokenSecret,authToken和其他值的会话对象的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}

码:

- (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会话.即使您关闭应用程序并重新打开它,它也会持续.

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

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

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)要从会话注销,请使用[[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

总结

以上是内存溢出为你收集整理的使用Fabric SDK iOS访问Twitter用户时间线全部内容,希望文章能够帮你解决使用Fabric SDK iOS访问Twitter用户时间线所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1101256.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存