我想为 Fitbit 实施 OAuth 身份验证,以在我的 iOS 应用程序中从 FitBit Api 读取数据。我注册了我的应用程序,并获得了 clientId 和客户端密码。从过去 2 天开始,我一直在搜索教程、库。我对此一无所知。请给我建议。
问问题
1077 次
1 回答
4
注意- 根据 https://dev.fitbit.com/docs/oauth2/
- 应用程序应在 2016 年 3 月 14 日之前升级到 OAuth 2.0
- 使用 safari 或 SFSafariViewController 打开授权页面
解决方案从这里开始
请替换 CLIENT_ID、REDIRECT_URI 和其他文本以更正信息
点1-
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=REDIRECT_URI&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"]];
提供正确的方案 url,以便在成功登录后您将被重定向到您的应用程序。在 openURL 方法中你会得到一个 OAUTHCODE
点2-
现在通过使用此 OAUTHCODE 获取 OAUTHTOKEN
-(void)toGetRequestToken:(id)sender
{
NSString *strCode = [[NSUserDefaults standardUserDefaults] valueForKey:@"auth_code"];
NSURL *baseURL = [NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize"];
AFOAuth2Manager *OAuth2Manager = [AFOAuth2Manager managerWithBaseURL:baseURL clientID:CLIENT_ID secret:CONSUMER_SECRET];
OAuth2Manager.responseSerializer.acceptableContentTypes = [OAuth2Manager.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
NSDictionary *dict = @{@"client_id":CLIENT_ID, @"grant_type":@"authorization_code",@"redirect_uri":@"Pro-Fit://fitbit",@"code":strCode};
[OAuth2Manager authenticateUsingOAuthWithURLString:@"https://api.fitbit.com/oauth2/token" parameters:dict success:^(AFOAuthCredential *credential) {
// you can save this credential object for further use
// inside it you can find access token also
NSLog(@"Token: %@", credential.accessToken);
} failure:^(NSError *error) {
NSLog(@"Error: %@", error);
}];
}
点3-
现在您可以点击其他 FitBit 请求,例如“UserProfile”——
-(void)getFitbitUserProfile:(AFOAuthCredential*)credential{
NSURL *baseURL = [NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize"];
AFHTTPSessionManager *manager =
[[AFHTTPSessionManager alloc] initWithBaseURL:baseURL];
[manager.requestSerializer setAuthorizationHeaderFieldWithCredential:credential];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"https://api.fitbit.com/1/user/-/profile.json"
parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *userDict =[dictResponse valueForKey:@"user"];
NSLog(@"Success: %@", userDict);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"Failure: %@", error);
}];
}
于 2016-06-02T10:58:58.200 回答