iphone - 如何使用 twitter api v1.1 获取用户详细信息(Twitter 错误 215)

标签 iphone ios xcode ipad mgtwitterengine

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

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];

错误如下:

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

最佳答案

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

其次,请参阅这些步骤:

1.下载FHSTwitterEngine Twitter 库。

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

3.添加SystemConfiguration.framework到您的项目。

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];

并且不要忘记导入委托(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!!!");
    }];
}

出现登录窗口时,输入您的 Twitter UsernamePasswordauthenticate您的要求。

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

就是这样。 我刚刚从搜索查询中获得了屏幕名称,您可以使用以下方法获得用户的时间线:

// 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知道你需要使用什么方法。 注意:获取<consumer_key><consumer_secret>你需要访问这个link 在 Twitter 中注册您的应用程序。

关于iphone - 如何使用 twitter api v1.1 获取用户详细信息(Twitter 错误 215),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17081012/

相关文章:

iphone - Xcode 中的 Target 到底是什么?

ios - 无法在 bundle 中加载 NIB

ios - Cordova 在 CLI 上构建 iOS 版本失败的代码签名检查

ios - 如何在没有收到警告的情况下将套接字转换为SSLConnectionRef?

iphone - NSRunLoop长时间延迟后正在调用我的选择器

iphone - SDWebImage清除缓存

ios - 将 Google Cast SDK 添加到 64 位版本

iphone - 从 xib 加载 UIView,尝试访问 IBOutlet 时崩溃

iphone - 标签栏中的自定义字体

iphone - 判断 NSString 的第一个字符是否为数字