我正在开发一个使用oAuth的Twitter应用程序,但我无法找到如何获取当前用户信息的任何信息。
所谓当前用户,是指授予我的应用程序权限并对其进行API请求的用户。
有什么建议吗?
所谓当前用户,是指授予我的应用程序权限并对其进行API请求的用户。
有什么建议吗?
实际上它是 "account/verify_credentials",如下所示:
API v. 1.1 的文档链接:https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
(该链接指向 Twitter 开发者文档中有关验证凭据的 API 的页面)$oauth = new TwitterOAuth([keys here]);
$credentials = $oauth->get('account/verify_credentials');
echo "Connected as @" . $credentials->screen_name ."\n";
针对iOS的解决方案:
1)如果您在设备上有Twitter帐户(即ACAccountStore
中的ACAccount
),您唯一需要做的就是将其附加到SLRequest并从返回的字典中获取所有用户信息:
NSURL *url = [NSURL URLWithString:@"https://api.twitter.com/1.1/account/verify_credentials.json"];
NSMutableDictionary *params = [NSMutableDictionary new];
[params setObject:[Twitter sharedInstance].session.userID forKey:@"user_id"];
[params setObject:@"0" forKey:@"include_entities"];
[params setObject:@"1" forKey:@"skip_status"];
[params setObject:@"1" forKey:@"include_email"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:params];
[request setAccount:twitterAccount]; //one of the Twitter Acc
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
NSDictionary *twitterData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:NULL];
});
}else {
NSLog(@"Error while downloading Twitter user data: %@", error);
}
}];
2) 否则 - 您需要发送OAuth(X-Auth)用户凭据。最简单的方法是使用TWTROAuthSigning类检索OAuth参数:
TWTROAuthSigning *oauthSigning =
[[TWTROAuthSigning alloc]
initWithAuthConfig:
[Twitter sharedInstance].authConfig
authSession:session];
NSDictionary *authHeaders =
[oauthSigning OAuthEchoHeadersToVerifyCredentials];
然后发送普通请求,将凭据作为头字段附加:
NSString *oauthParameters = authHeaders[@"X-Verify-Credentials-Authorization"];
NSString *urlString = authHeaders[@"X-Auth-Service-Provider"];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
request.allHTTPHeaderFields = @{@"Authorization":oauthParameters};
[request setHTTPMethod:@"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
NSDictionary *twitterData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
}];
如果您支持旧版本的Twitter SDK或正在寻找更多选项,我建议查看STTwitter库
include_email
设置为false https://dev.twitter.com/rest/reference/get/account/verify_credentials,否则您将收到“您的凭据不允许访问此资源”错误。 - shukshin.ivan