How to implement native app login in ios?

541 views Asked by At

I’m building an iOS app and using UIStoryBoard.I have integrated Facebook SDK into my app.

I want to implement native app login means when user click on Facebook button in my app then it logged in through Facebook app install in the device otherwise through web view Facebook dialog.

I implemented same code as in Scrumptious sample in Facebook SDK but it is not working,same is happening on click on Facebook button web view popup dialog is open.

Is there need to make changes in app itself in Facebook developer account.

I’m rechecked the code 5-6 times everything is correct,someone help me,is any other project or tutorial help me to meet my requirements.

1

There are 1 answers

4
Hardik Kardani On

Add code in Appdelegate.m file

#import <FacebookSDK/FacebookSDK.h>
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[FBAppEvents activateApp];
}
- (BOOL)application:(UIApplication *)application
        openURL:(NSURL *)urlsourceApplication:(NSString *)sourceApplication
     annotation:(id)annotation {
// attempt to extract a token from the url
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
}

put this is viewcontrol.m file and call FacebookLogin method in Button Click event

#import <FacebookSDK/FacebookSDK.h>
#import <Social/Social.h>
#import "FBSignupVC.h"

NSString *const SCSessionStateChangedNotificationCamera1 = 
@"com.facebook.Scrumption:SCSessionStateChangedNotification";   
@interface HomeVC ()    
@property (nonatomic, retain) ACAccountStore*accountStore;    
@property (nonatomic, retain) ACAccount *facebookAccount;    
@end    
@implementation ViewController

Add “FBLoginViewDelegate” in view controller.h file

-(void)FacebookLogin
{
    FBLoginView *loginview = [[FBLoginView alloc] init];    
    loginview.delegate = self;

    [self.view addSubview:loginview];

    if(!_accountStore)
    {
        _accountStore = [[ACAccountStore alloc] init];
        [FBSession setActiveSession:nil];
    }

    ACAccountType *facebookTypeAccount = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];

    [_accountStore requestAccessToAccountsWithType:facebookTypeAccount
                                           options:@{ACFacebookAppIdKey: @“App”ID, ACFacebookPermissionsKey: @[@"email"]}
                                        completion:^(BOOL granted, NSError *error) {
                                            if(granted){
                                                NSArray *accounts = [_accountStore accountsWithAccountType:facebookTypeAccount];
                                                _facebookAccount = [accounts lastObject];
                                                ////NSLog(@"Success");
                                                ACAccountCredential *fbCredential = [self.facebookAccount credential];
                                                NSLog(@"fbCredential: %@",fbCredential);
                                                NSLog(@"fbAccessToken : %@", [fbCredential oauthToken]);
                                            }else{
                                                ////NSLog(@"Fail");
                                                NSLog(@"Error: %@", error);
                                                dispatch_async(dispatch_get_main_queue(), ^{
                                                    [self openSessionWithAllowLoginUI:YES];
                                                });
                                            }
                                        }];
}

- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
    NSArray *permissions = [[NSArray alloc] initWithObjects: @"publish_actions",@"public_profile",@"email",@"user_friends", nil];
    return [FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState state, NSError *error)
    {
        if (!error)
        {
            [self sessionStateChanged:session state:state error:error];
        }
        else
        {

            NSLog(@"%@",error);
        }
    }];
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
    switch (state) {
        case FBSessionStateOpen: {
            if (self != nil) {
                [[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                    if (error) {
                        NSLog(@"%@",error);
                        //error
                    }else{
                        if ([FBSession.activeSession.permissions indexOfObject:@"publish_actions"] == NSNotFound) {
                            NSArray *permissions = [[NSArray alloc] initWithObjects: @"publish_actions",@"public_profile",@"email",@"user_friends", nil];
                            [FBSession.activeSession reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
                                if (!error) {
                                    [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                                        if (!error) {
                                            dispatch_async(dispatch_get_main_queue(), ^{

                                            });
                                        }
                                    }];
                                }
                                else {
                                }
                            }];
                        }
                        else {
                            ////NSLog(@"session 2");
                            [[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                                if (!error) {
                                            dispatch_async(dispatch_get_main_queue(), ^{
                                    });
                                }
                            }];
                        }
                    }
                }];
            }
            FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
            [cacheDescriptor prefetchAndCacheForSession:session];
        }
            break;
        case FBSessionStateClosed: {
            UIViewController *topViewController = [self.navigationController topViewController];
            UIViewController *modalViewController = [topViewController modalViewController];
            if (modalViewController != nil) {
                [topViewController dismissViewControllerAnimated:YES completion:nil];
            }
            //[self.navigationController popToRootViewControllerAnimated:NO];
        }
            break;
        case FBSessionStateClosedLoginFailed: {
        }
            break;
        default:
            break;
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationCamera1 object:session];

    if (error) {
    }
}

+ (NSString *)FBErrorCodeDescription:(FBErrorCode) code
{
    switch(code)
    {
        case FBErrorInvalid :
        {
            return @"FBErrorInvalid";
        }
        case FBErrorOperationCancelled:
        {
            return @"FBErrorOperationCancelled";
        }
        case FBErrorLoginFailedOrCancelled:
        {
            return @"FBErrorLoginFailedOrCancelled";
        }
        case FBErrorRequestConnectionApi:
        {
            return @"FBErrorRequestConnectionApi";
        }case FBErrorProtocolMismatch:
        {
            return @"FBErrorProtocolMismatch";
        }
        case FBErrorHTTPError:
        {
            return @"FBErrorHTTPError";
        }
        case FBErrorNonTextMimeTypeReturned:
        {
            return @"FBErrorNonTextMimeTypeReturned";
        }
        default:
            return @"[Unknown]";
    }
}

- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user
{
    NSLog(@"User: %@",user);
    NSLog(@"UserName: %@",user.name);
    NSLog(@"usr_id::%@",user.id);
    NSLog(@"usr_first_name::%@",user.first_name);
    NSLog(@"usr_Username::%@",user.username);
    NSLog(@"location: %@",user.location.name);
    NSLog(@"birthday: %@",user.birthday);
    NSLog(@"gender: %@",[user objectForKey:@"gender"]);
}

- (void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView
{
    FBShareDialogParams *p = [[FBShareDialogParams alloc] init];
    p.link = [NSURL URLWithString:@"http://developers.facebook.com/ios"];
}

- (void)loginView:(FBLoginView *)loginView handleError:(NSError *)error
{
    [FBSession setActiveSession: [[FBSession alloc] initWithPermissions:FBSession.activeSession.permissions] ];

    [[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
        switch (status) {
            case FBSessionStateOpen:

                break;
            case FBSessionStateClosedLoginFailed:
            {
                NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
                NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
                BOOL userDidCancel = !errorCode && (!errorReason ||
                                                    [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
            }
                break;

            default:
                break;
        }
    }];

}

-(BOOL) application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    if (url != nil)
    {
        NSLog(@"url:%@",url);
        return [[FBSession activeSession] handleOpenURL:url];
    }

    return NO;
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    [[FBSession activeSession] close];
}

- (void) getAppUsers
{
    FBRequest *request = [FBRequest requestForMyFriends];
    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        NSLog(@"result : %@",result[@"data"]);
    }];
}