如何在 ios 中实现本机应用程序登录



我正在构建一个iOS app并使用UIStoryBoard.我已将Facebook SDK集成到我的应用程序中。

我想实现native应用程序登录意味着当用户单击我的应用程序中Facebook按钮时,它通过登录Facebook app否则通过 Web 视图Facebook dialog在设备中安装。

我在Facebook SDK中实现了与示例中相同的代码Scrumptious但它不起作用,单击按钮 Web 视图弹出对话框打开Facebook也会发生同样的情况。

是否需要在Facebook developer account中对应用程序本身进行更改。

重新检查了 5-6 次代码,一切都是正确的,有人帮助我,是否有任何其他项目或教程帮助我满足我的要求。

在 Appdelegate.m 文件中添加代码

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

把这是viewcontrol.m文件,并在按钮点击事件中调用FacebookLogin方法。

#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"]);
    }];
}

相关内容

  • 没有找到相关文章

最新更新