Wednesday, 21 February 2018

Login Authentication using Twitter Account - Objective C

Fabric Framework Download and Install in to the Project.

AppDelegate.m
#import <Fabric/Fabric.h>
#import <TwitterKit/TwitterKit.h>

Add the code into didFinishLaunchingWithOptions

[Fabric with:@[[Twitter class]]];


ViewController.h
#import <Twitter/Twitter.h>
#import <TwitterKit/TwitterKit.h>
#import <TwitterCore/TwitterCore.h>

@property (nonatomic,strong) IBOutlet TWTRLogInButton *customTwitterButton;

ViewController.m
@synthesize customTwitterButton;

-(void)viewDidLoad
{
    [super viewDidLoad];
    customTwitterButton = [TWTRLogInButton buttonWithLogInCompletion:^(TWTRSession *session, NSError *error) {}];
}


-(IBAction)btnTwitterLogin_pressed:(id)sender
{
    [[Twitter sharedInstance] logInWithCompletion:^
     (TWTRSession *session, NSError *error) {
         if (session)
         {
             NSLog(@"%@", [session userID]);
             NSLog(@"%@", [session userName]);
             NSLog(@"%@", [session authToken]);
             NSLog(@"%@", [session authTokenSecret]);
         }
         else
         {
             NSLog(@"Error: %@", [error localizedDescription]);
         }
     }];
}

-(IBAction)logout_Twitter:(id)sender
{
    NSURL *url = [NSURL URLWithString:@"https://api.twitter.com"];
    NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
    for (NSHTTPCookie *cookie in cookies)
    {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }
}


Login Authentication using Facebook Account
Facebook Developer Site Settings
1. Go to https://developers.facebook.com/ and Add a New App(Sample App).
2. Select a Sample App and go to Settings of Sample App.
3. Add Platform —> Select iOS —> Enter Bundle Id.
4. Click Quick Start. These steps are also given in Facebook Developer Site.
5. Go to App Review of Sample App. And Choose ‘Yes’ to Make SampleApp public?

Project Settings
Step 1: Download Facebook SDK and unzip the archive to ~/Documents/FacebookSDK
Download Facebook SDK Link : https://origincache.facebook.com/developers/resources/?id=facebook-ios-sdk-current.zip

Step 2: Add the Facebook SDK to your Xcode Project, drag the folder FBSDKCoreKit.Framework, FBSDKLoginKit.Framework, FBSDKShareKit.Framework into your Xcode Projects Framework folder.

Step 3: Right-click your info.plist file and choose "Open As Source Code".Copy & Paste the XML snippet into the body of your file ( <dict>...</dict> )

       <key>CFBundleURLTypes</key>
      <array>
        <dict>
        <key>CFBundleURLSchemes</key>
        <array>
          <string>fb{id}</string>
        </array>
        </dict>
      </array>
      <key>FacebookAppID</key>
      <string>{id}</string>
      <key>FacebookDisplayName</key>
      <string>{App Name}</string>
      <key>LSApplicationQueriesSchemes</key>
      <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>

      </array>

Step 4: Add the Bundle Identifier and Next Button.

Step 4: Add the Below Codes

AppDelegate.m

#import <FBSDKCoreKit/FBSDKCoreKit.h>

Add the code into didFinishLaunchingWithOptions

[[FBSDKApplicationDelegate sharedInstance] application:application
                             didFinishLaunchingWithOptions:launchOptions];

-(void)applicationDidBecomeActive:(UIApplication *)application
{
    [FBSDKAppEvents activateApp];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [[FBSDKApplicationDelegate sharedInstance] application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}

ViewController.h
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>

ViewController.m
-(IBAction)btnFB_LoginPressed:(id)sender
{
    FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
    
    [login logInWithReadPermissions:@[@"public_profile", @"email"]  handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
        
        if (error)
        {
            NSLog(@"Process error");
        }
        else if (result.isCancelled)
        {
            NSLog(@"Cancelled");
        }
        else
        {
            if ([result.grantedPermissions containsObject:@"email"] && [result.grantedPermissions containsObject:@"public_profile"])
            {
                
                if ([FBSDKAccessToken currentAccessToken])
                {
                    NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
                    [parameters setValue:@"id,name,email" forKey:@"fields"];
                    
                    [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]
                     startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
                     {
                         if (!error)
                         {
                             NSLog(@"Facebook result dict : %@", result);
                             NSMutableDictionary *profile = (NSMutableDictionary*)result;
                             
                             NSString *urlImageProfile = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture?type=large", [result objectForKey:@"id"]];
                             
                             [self showUserProfileWith:profile andImageProfile:urlImageProfile];
                         }
                     }];
                }
            }
        }
    }];
}

-(void)showUserProfileWith:(NSMutableDictionary*)userData andImageProfile:(NSString*)imageUrl
{
    NSLog(@"NAME - %@", [userData objectForKey:@"name"]);
    NSLog(@"EMAIL - %@", [userData objectForKey:@"email"]);
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSURL *url = [NSURL URLWithString:imageUrl];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImageView *imgProfile = [[UIImageView alloc]init];
        imgProfile.frame = CGRectMake(30, 30, 200, 150);
        imgProfile.center = self.view.center;
        imgProfile.image = [UIImage imageWithData:data];
        [self.view addSubview:imgProfile];
    });
}

-(IBAction)logout_fb:(id)sender
{
    FBSDKLoginManager *logmanager = [[FBSDKLoginManager alloc] init];
    [logmanager logOut];

    NSURL *url = [NSURL URLWithString:@"http://login.facebook.com"];
    NSArray *cookies_list = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
    for (NSHTTPCookie *cookie in cookies_list)
    {
        [[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
    }

    NSHTTPCookieStorage *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (NSHTTPCookie *_cookie in cookies.cookies)
    {
        NSRange domainRange = [[_cookie domain] rangeOfString:@"facebook"];
        if(domainRange.length > 0){
            [cookies deleteCookie:_cookie];
        }
    }
}

Links:




No comments: