Getting Email Address from LinkedIn API
Asked Answered
A

4

5

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?

Ashjian answered 17/4, 2014 at 2:3 Comment(0)
R
10

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

Remit answered 20/4, 2014 at 13:5 Comment(2)
And you should also add 'emailaddress' permission in your application : developer.linkedin.com/documents/authentication#grantingIso
I was using this library github.com/jeyben/IOSLinkedInAPI/tree/master/IOSLinkedInAPI then it works fine with above solution . Thanks a lot :-)Isomagnetic
D
2

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 = "[email protected]";
>     firstName = Name;
>     id = "2342d-6Y";
>     lastName = LastName;
> }

Also this link can be useful

Deoxyribose answered 4/12, 2015 at 13:5 Comment(0)
A
1

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"
Areaway answered 31/8, 2017 at 12:7 Comment(0)
T
-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);
    }];
}
Tierell answered 24/3, 2017 at 6:40 Comment(1)
Could you please edit in an explanation of why this code answers the question? Code-only answers are discouraged, because they don't teach the solution.Chole

© 2022 - 2024 — McMap. All rights reserved.