如何使用 twitter api v1.1 获取用户详细信息(Twitter 错误 215) [英] How to get user details using twitter api v1.1 (Twitter error 215)

查看:27
本文介绍了如何使用 twitter api v1.1 获取用户详细信息(Twitter 错误 215)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用了 twitter 提供的 twitter api 来获取详细信息,但是无法执行,甚至试图通过身份验证数据像消费者密钥、消费者密钥、令牌但结果是一样的.
我可以登录并接收 Twitter 身份验证令牌,但无法获取用户详细信息.下面的代码是我使用的(我使用的是 MGtwitter 引擎):

NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@",用户名]]];NSData *returnData = [ NSURLConnection sendSynchronousRequest: 请求返回响应: nil 错误: nil ];NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];NSError *err = nil;twitterLogin = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers 错误:&err];

错误如下:

错误 = ({代码 = 215;message = "错误的认证数据";});

解决方案

首先,您需要Authenticate您的请求(获得许可).

其次,请参阅这些步骤:

1.下载 FHSTwitterEngine Twitter 库.

2. 将文件夹 FHSTwitterEngine" 添加到您的项目中并#import "FHSTwitterEngine.h".

3.将 SystemConfiguration.framework 添加到您的项目中.

<块引用>

用法:1.在[ViewDidLoad]中加入如下代码.

UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];登录.frame = CGRectMake(100, 100, 100, 100);[logIn setTitle:@"Login" forState:UIControlStateNormal];[登录 addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];[self.view addSubview:logIn];[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@""andSecret:@""];[[FHSTwitterEngine sharedEngine]setDelegate:self];

并且不要忘记导入委托FHSTwitterEngineAccessTokenDelegate.

<块引用>

  1. 您需要获得您的请求的许可,使用以下方法将显示登录窗口:

- (void)showLoginWindow:(id)sender {[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");}];}

出现登录窗口时,输入您的 Twitter 用户名密码验证您的请求.

<块引用>

  1. 将以下方法添加到您的代码中:

-(void)viewWillAppear:(BOOL)animated{[super viewWillAppear:animated];[[FHSTwitterEngine sharedEngine]loadAccessToken];NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];//self.engine.loggedInUsername;如果(用户名.长度 > 0){lbl.text = [NSString stringWithFormat:@"以%@登录",用户名];[自我列表结果];} 别的 {lbl.text = @"您还没有登录.";}}- (void)storeAccessToken:(NSString *)accessToken {[[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];}- (NSString *)loadAccessToken {返回 [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];}

<块引用>

4.现在您已准备好使用以下方法获取您的请求(在此方法中,我创建了一个 Twitter 搜索一些 Hashtag,以获取 screen_name 例如):

- (void)listResults {dispatch_async(GCDBackgroundThread,^{@autoreleasepool {[UIApplication sharedApplication].networkActivityIndi​​catorVisible = YES;//以下行包含一个 FHSTwitterEngine 方法,用于搜索.dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:@"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];//NSLog(@"%@",dict);NSArray *results = [dict objectForKey:@"statuses"];//NSLog(@"array text = %@",results);对于(NSDictionary *结果中的项目){NSLog(@"text == %@",[item objectForKey:@"text"]);NSLog(@"name == %@",[[item objectForKey:@"user"]objectForKey:@"name"]);NSLog(@"screen name == %@",[[item objectForKey:@"user"]objectForKey:@"screen_name"]);NSLog(@"pic == %@",[[item objectForKey:@"user"]objectForKey:@"profile_image_url_https"]);}dispatch_sync(GCDMainThread,^{@autoreleasepool {UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"完成!"message:@"您的关注者列表已被获取" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];【影音秀】;[UIApplication sharedApplication].networkActivityIndi​​catorVisible = NO;}});}});}

仅此而已.我刚刚从搜索查询中获取了 screen_name,您可以使用以下方法获取用户的时间线:

//statuses/user_timeline- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID;

代替上面的搜索方法.

注意:查看 FHSTwitterEngine.h 以了解您需要使用的方法.注意:要获取 ,您需要访问此 链接在 Twitter 中注册您的应用程序.

I have used the twitter api provided by twitter,to get the details but not able to execute it, even tried to pass the authentication data like consumer secret key, consumer key, token but the result is same.
I am able to login and receiving twitter authentication token but not able to get user details. Below code is used by me (I am using MGtwitter engine) :

NSMutableURLRequest *request =[[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.twitter.com/1.1/users/show.json?screen_name=%@",username]]];

NSData *returnData = [ NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil ];

NSString *returnString = [[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
    NSError *err = nil;

twitterLogin = [NSJSONSerialization JSONObjectWithData:[returnString dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&err];

Error is shown as below:

errors = (
{
    code = 215;
    message = "Bad Authentication data";
} );

解决方案

First, you need to Authenticate your request (Get permission).

second, see follow these steps:

1.Download FHSTwitterEngine Twitter Library.

2.Add the folder FHSTwitterEngine" to your project and #import "FHSTwitterEngine.h".

3.add SystemConfiguration.framework to your project.

Usage : 1.in the [ViewDidLoad] add the following code.

UIButton *logIn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    logIn.frame = CGRectMake(100, 100, 100, 100);
    [logIn setTitle:@"Login" forState:UIControlStateNormal];
    [logIn addTarget:self action:@selector(showLoginWindow:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:logIn];

[[FHSTwitterEngine sharedEngine]permanentlySetConsumerKey:@"<consumer_key>" andSecret:@"<consumer_secret>"];
    [[FHSTwitterEngine sharedEngine]setDelegate:self];

and don't forget to import the delegate FHSTwitterEngineAccessTokenDelegate.

  1. you need to get the permission for your request, with the following method which will present Login window:

- (void)showLoginWindow:(id)sender {
    [[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
        NSLog(success?@"L0L success":@"O noes!!! Loggen faylur!!!");
    }];
}

when the Login window is presented, enter your Twitter Username and Password to authenticate your request.

  1. add the following methods to your code:

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[FHSTwitterEngine sharedEngine]loadAccessToken];
    NSString *username = [[FHSTwitterEngine sharedEngine]loggedInUsername];// self.engine.loggedInUsername;
    if (username.length > 0) {
        lbl.text = [NSString stringWithFormat:@"Logged in as %@",username];
        [self listResults];


    } else {
        lbl.text = @"You are not logged in.";
    }

}
- (void)storeAccessToken:(NSString *)accessToken {
    [[NSUserDefaults standardUserDefaults]setObject:accessToken forKey:@"SavedAccessHTTPBody"];
}

- (NSString *)loadAccessToken {
    return [[NSUserDefaults standardUserDefaults]objectForKey:@"SavedAccessHTTPBody"];
}

4.Now you are ready to get your request, with the following method(in this method I created a Twitter search for some Hashtag, to get the screen_name for example):

- (void)listResults {

    dispatch_async(GCDBackgroundThread, ^{
        @autoreleasepool {
            [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

        // the following line contains a FHSTwitterEngine method wich do the search.

            dict = [[FHSTwitterEngine sharedEngine]searchTweetsWithQuery:@"#iOS" count:100 resultType:FHSTwitterEngineResultTypeRecent unil:nil sinceID:nil maxID:nil];
          // NSLog(@"%@",dict);
            NSArray *results = [dict objectForKey:@"statuses"];

          //  NSLog(@"array text = %@",results);
            for (NSDictionary *item in results) {
                NSLog(@"text == %@",[item objectForKey:@"text"]);
                NSLog(@"name == %@",[[item objectForKey:@"user"]objectForKey:@"name"]);
                NSLog(@"screen name == %@",[[item objectForKey:@"user"]objectForKey:@"screen_name"]);
                NSLog(@"pic == %@",[[item objectForKey:@"user"]objectForKey:@"profile_image_url_https"]);
            }

            dispatch_sync(GCDMainThread, ^{
                @autoreleasepool {
                    UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Complete!" message:@"Your list of followers has been fetched" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                    [av show];
                    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
                }
            });
        }
    });
}

That's all. I just got the screen_name from a search Query, you can get a timeline for a user using the following methods:

// statuses/user_timeline
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count;
- (id)getTimelineForUser:(NSString *)user isID:(BOOL)isID count:(int)count sinceID:(NSString *)sinceID maxID:(NSString *)maxID; 

instead of the search method above.

Note: see the FHSTwitterEngine.h to know what method you need to use. Note: to get the <consumer_key> and the <consumer_secret> you need to to visit this link to register your app in Twitter.

这篇关于如何使用 twitter api v1.1 获取用户详细信息(Twitter 错误 215)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆