Question

I want to include a "Sign Up using LinkedIn" feature in my app.

I'd like to be able to get some information, such as name and email.

By default I am able to get a name, but I'm stuck on getting the email.

My results are in JSON.

Here's my code:

- (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];
}

My result is:

firstName

headline

lastName

siteStandardProfileRequest

Anyone see how I can get the email?

Was it helpful?

Solution

You should use:

[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)

This may helps :)

OTHER TIPS

You can use 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);
        }];
    }
}

Response

> {
>     emailAddress = "someEmail@email.com";
>     firstName = Name;
>     id = "2342d-6Y";
>     lastName = LastName;
> }

Also this link can be useful

Update for Swift 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"
-(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);
    }];
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top