注意:截至2015年5月12日,LinkedIn对非合作伙伴的API使用施加了限制:请参阅https://developer.linkedin.com/blog/posts/2015/developer-program-changes
这是一个小巧、不会打扰到用户的库,可以方便地使用OAuth2在LinkedIn上进行身份验证和授权。API使用UIWebView对LinkedIn进行身份验证。
如果终端用户进行了身份验证,您将获得一个accesstoken,这是从LinkedIn获取数据所必需的。
为什么还需要另一个LinkedIn库?尽管已经存在几个iOS库,它们都是围绕LinkedIn API进行包装的,但据我所知,它们没有一个使用OAuth2,而LinkedIn首选该协议。
可以从cocoapods将库作为Pod获取。
如果您不使用CocoaPods,您始终可以从文件夹IOSLinkedInAPI中下载库并将文件导入到现有项目中。
使用LIALinkedInApplication创建一个LinkedIn客户端。LIALinkedInApplication定义了有权访问用户LinkedIn数据的应用程序。
LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:@"http://www.ancientprogramming.com/liaexample"
clientId:@"clientId"
clientSecret:@"clientSecret"
state:@"DCEEFWF45453sdffef424"
grantedAccess:@[@"r_fullprofile", @"r_network"]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil];
之后,可以使用客户端检索accesstoken并通过LinkedIn API访问数据。
- (IBAction)didTapConnectWithLinkedIn:(id)sender {
[self.client getAuthorizationCode:^(NSString *code) {
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:@"access_token"];
[self requestMeWithToken:accessToken];
} failure:^(NSError *error) {
NSLog(@"Quering accessToken failed %@", error);
}];
} cancel:^{
NSLog(@"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(@"Authorization failed %@", error);
}];
}
- (void)requestMeWithToken:(NSString *)accessToken {
[self.client GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~?oauth2_access_token=%@&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(@"current user %@", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"failed to fetch current user %@", error);
}];
}
代码示例从应用中检索访问令牌,并使用它获取授予访问权限的用户的数据。如果在UIWebView中点击取消按钮,则会执行取消回调,表示用户主动拒绝授权(参见图上说明)。如果上述步骤中的任意一步失败,则会执行失败回调。
可以在此处找到一个小的示例应用程序: https://github.com/jeyben/IOSLinkedInAPI/tree/master/Example/IOSLinkedInAPI-Podexample/IOSLinkedInAPI-Podexample
该应用程序使用 Cocoapods。在克隆后,只需在目录中运行 'pods install',然后您就应该能够运行该应用程序了。
库当前负责处理身份验证和授权。我想改进库,使其更容易执行实际的 API 调用。我的当前想法是让客户端在获取访问令牌后将 accessToken 记录下来,并在随后的调用中自动将其与 format=json GET 参数一起追加。
如果您有关于如何实现的任何想法,请告诉我。