我想为Fitbit实施OAuth身份验证,以便在我的iOS应用中从FitBit Api读取数据。我注册了我的应用程序,我得到了clientId和客户端的秘密。我从过去2天开始搜索教程,库。我对此一无所知。请建议我。
答案 0 :(得分:4)
注意 - 根据https://dev.fitbit.com/docs/oauth2/
请替换CLIENT_ID,REDIRECT_URI和其他文字以更正信息
<强> POINT1 - 强>
[[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"]];
提供适当的方案网址,以便在成功登录后,您将被重定向到您的应用程序。在openURL方法中,您将获得OAUTHCODE
<强> POINT2 - 强>
现在使用此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);
}];
}
Point3 -
现在您可以点击其他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);
}];
}