gpt4 book ai didi

ios - 如何从 iOS 调用 OAuth 2.0 API

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:36:44 24 4
gpt4 key购买 nike

我正在研究 Fitbit一体化。我如何提出请求并授权其 OAuth 2.0 API。我检查了 ASIHTTPRequest但它在 ARC 上不可用。我可以用 AFNetworking 来做吗? ?我正在使用 Objective-C。

最佳答案

使用 AFNetworking 使用 AFOAuth2Manager 完成这是代码

在 ViewController.m 中

#define CLIENT_ID         @"your client id"
#define CONSUMER_SECRET @"your consumer secret"

使用 safari 开始授权。

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize?response_type=code&client_id=227FKJ&redirect_uri=http%3A%2F%2Fcallback.com%2Ffitbit&scope=activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight"]];

NSUserDefaults获取响应码

NSString *string  = [[NSUserDefaults standardUserDefaults] valueForKey:@"auth_code"];
NSURL *baseURL = [NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize"];
AFOAuth2Manager *OAuth2Manager =
[[AFOAuth2Manager alloc] initWithBaseURL:baseURL
clientID:CLIENT_ID secret:CONSUMER_SECRET];
NSDictionary *dict = @{@"client_id":CLIENT_ID, @"grant_type":@"authorization_code",@"redirect_uri":@"http://lampdemos.com/fitbit",@"code":string};

[OAuth2Manager authenticateUsingOAuthWithURLString:@"https://api.fitbit.com/oauth2/token" parameters:dict success:^(AFOAuthCredential *credential) {
NSLog(@"Token: %@", credential.accessToken);
AppDelegate *adddel = (AppDelegate *)[[UIApplication sharedApplication]delegate];
adddel.credential = credential;
[self getUserProfileWithCredentials:credential];
} failure:^(NSError *error) {
NSLog(@"Error: %@", error);
}];

调用进一步的请求

-(void)getUserProfileWithCredentials:(AFOAuthCredential*)credential{
NSURL *baseURL = [NSURL URLWithString:@"https://www.fitbit.com/oauth2/authorize"];

AFHTTPRequestOperationManager *manager =
[[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];
[manager.requestSerializer setAuthorizationHeaderFieldWithCredential:credential];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager GET:@"https://api.fitbit.com/1/user/-/profile.json"
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {

NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
NSDictionary *userDict =[dictResponse valueForKey:@"user"];
NSLog(@"Success: %@", userDict);
NSMutableString *str =[NSMutableString stringWithFormat:@"%@",@""];
for (NSString *key in [userDict allKeys]) {
[str appendFormat:@"%@ %@\n",key,[NSString stringWithFormat:@"%@",[userDict valueForKey:key]]];
}
self.profileDetails.text =str;

}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Failure: %@", error);
}];
}

关于ios - 如何从 iOS 调用 OAuth 2.0 API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35289513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com