2014-04-17 43 views
4

我想在我的應用中加入「使用LinkedIn註冊」功能。從LinkedIn獲取電子郵件地址API

我希望能夠獲得一些信息,例如姓名和電子郵件。

默認情況下,我能夠獲得一個名稱,但我一直在獲取電子郵件。

我的結果是JSON。

這裏是我的代碼:

- (IBAction)logInWithLinkedIn:(id)sender 
{ 
    if ([_client validToken]) 
    { 
     [self requestMeWithToken:[_client accessToken]]; 
    } 
    else 
    { 
     [_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); 

    }]; 
} 

- (LIALinkedInHttpClient *)client 
{ 
    LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:@"redirectURL" 
                        clientId:@"key" 
                       clientSecret:@"secret" 
                         state:@"state" 
                       grantedAccess:@[@"r_emailaddress"]]; 
    return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil]; 
} 

我的結果是:

的firstName

標題

lastName的

siteStandardProfileRequest

任何人都可以看到我如何獲得電子郵件?

回答

7

你應該使用:

[self.client GET:[NSString stringWithFormat:@"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?oauth2_access_token=%@&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) 

這可能有助於:)

+1

而且你還應該添加在你的應用程序 'EMAILADDRESS' 權限:http://developer.linkedin.com/documents/authentication#granting – androniennn

+0

我所用這個庫https://github.com/jeyben/IOSLinkedInAPI/tree/master/IOSLinkedInAPI然後它可以很好地與上面的解決方案。非常感謝:-) – byJeevan

2

您可以使用LinkedIn SDK

+ (void)loginToLinkedInAndFetchProfileData:(RequestResult)resultHandler 
{ 
    void (^PerformDataFetch)() = ^() { 
     if ([LISDKSessionManager hasValidSession]) { 
      NSString *urlString = [NSString stringWithFormat:@"%@/people/~:(id,first-name,last-name,maiden-name,email-address)", LINKEDIN_API_URL]; 
      [[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) { 
       NSString *token = [[LISDKSessionManager sharedInstance].session.accessToken serializedString]; 
       [[NSUserDefaults standardUserDefaults] setValue:token forKey:LinkedInAccessTokenKey]; 
       [[NSUserDefaults standardUserDefaults] synchronize]; 

       NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding]; 
       id value = [NSJSONSerialization JSONObjectWithData:objectData options:kNilOptions error:nil]; 
       resultHandler(value, nil); 
      } error:^(LISDKAPIError *error) { 
       resultHandler(nil, error); 
      }]; 
     } 
    }; 

    NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:LinkedInAccessTokenKey]; 

    if (token.length) { 
     LISDKAccessToken *accessToken = [LISDKAccessToken LISDKAccessTokenWithSerializedString:token]; 
     if ([accessToken.expiration isLaterThan:[NSDate date]]) { 
      [LISDKSessionManager createSessionWithAccessToken:accessToken]; 
      PerformDataFetch(); 
     } 
    } else { 
     [LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) { 
      PerformDataFetch(); 
     } errorBlock:^(NSError *error) { 
      resultHandler(nil, error); 
     }]; 
    } 
} 

響應

> { 
>  emailAddress = "[email protected]"; 
>  firstName = Name; 
>  id = "2342d-6Y"; 
>  lastName = LastName; 
> } 

而且這link可能是有用的

-1
-(void)syncLinkedInWithCompetionHandler:(CompletionBlock)block{ 

    [LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] 
             state:@"some state" 
         showGoToAppStoreDialog:YES 
            successBlock:^(NSString *returnState) { 

             NSLog(@"%s","success called!"); 
             LISDKSession *session = [[LISDKSessionManager sharedInstance] session]; 
             NSLog(@"value=%@ \nisvalid=%@",[session value],[session isValid] ? @"YES" : @"NO"); 
             block(returnState, nil); 
            } 
            errorBlock:^(NSError *error) { 
             NSLog(@"%s %@","error called! ", [error description]); 
             block(nil, error); 
            } 
    ]; 
} 

-(void)getProfileDataWithCompletion:(CompletionBlock)block { 

    NSString *urlString = [NSString stringWithFormat:@"%@/people/~:(id,first-name,last-name,headline,location,email-address)", LINKEDIN_API_URL]; 
    NSLog(@"urlString = %@",urlString); 

    [[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) { 
     NSError *jsonError; 
     NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding]; 
     NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:objectData 
                  options:NSJSONReadingMutableContainers 
                   error:&jsonError]; 
     NSLog(@"responseDict = %@",responseDict); 
     block(responseDict, nil); 

    } error:^(LISDKAPIError *error) { 
     NSLog(@"error = %@",error); 
     block(error, nil); 
    }]; 
} 
+0

您可以在[編輯]中解釋爲什麼這段代碼回答這個問題?僅限代碼答案[阻止](http://meta.stackexchange.com/q/148272/274165),因爲他們沒有教導解決方案。 –

1

更新斯威夫特3:

// Set preferred scope. 
    let scope = "r_basicprofile%20r_emailaddress" 

// Then 

if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") { 
     // Specify the URL string that we'll get the profile info from. 
     let targetURLString = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?format=json" 
相關問題