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

时间:2014-11-18 09:52:36

标签: ios objective-c facebook-sdk-3.1

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

我希望实现native app登录意味着当用户点击我的应用中的Facebook按钮时 通过Facebook app安装在设备中登录,否则通过网络视图Facebook dialog

我在Scrumptious中的Facebook SDK示例中实现了相同的代码,但它无法正常工作,点击Facebook按钮时也会发生同样的情况。网页视图弹出对话框已打开。

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

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

1 个答案:

答案 0 :(得分:1)

在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文件并在Button Click事件中调用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"]);
    }];
}