Thursday, April 3, 2014

Twitter and Facebook user ID

Since iOS 6 there is both Facebook and Twitter support in iOS Social framework. But by default - You can get only limited information about Your Facebook and Twitter account. In one of projects, I had to have user ID from Facebook and twitter.

In order to get this user ID from Facebook, You need to import FacebookSDK in Your project and:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];

ACAccountType *FBaccountType= [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

NSDictionary *options = @{
    ACFacebookAppIdKey: @"13569412415218",
    ACFacebookPermissionsKey: @[@"user_birthday"],
    ACFacebookAudienceKey: ACFacebookAudienceFriends
};

[accountStore requestAccessToAccountsWithType:FBaccountType options:options completion: ^(BOOL granted, NSError *e)
{
    if (granted)
    {
        NSLog(@"access granted");
    }
    else
    {
        NSLog(@"error getting permission %@",e);
    }
}];

ACAccountStore *account = [[ACAccountStore alloc] init];

ACAccountType *facebookAccountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

NSArray *accounts = [account accountsWithAccountType:facebookAccountType];

if(accounts && [accounts count])
{
    ACAccount *account = [accounts objectAtIndex:0];
    
    [FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,
        FBSessionState status, NSError *error)
    {
        [FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result,
        NSError *error2)
        {
            NSLog(@"user id %@", [result objectForKey:@"id"]);
        }];
    }];
}

For twitter it is simpler:

ACAccountStore *account = [[ACAccountStore alloc] init];

ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
    NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

    if(arrayOfAccounts && [arrayOfAccounts count])
    {
        ACAccount *account = [arrayOfAccounts objectAtIndex:0];

        NSDictionary *properties = [account dictionaryWithValuesForKeys:[NSArray arrayWithObject:@"properties"]];

        NSDictionary *details = [properties objectForKey:@"properties"];
        
        NSLog(@"user id %@", [details objectForKey:@"user_id"]);
    }
}];

No comments:

Post a Comment