2014-09-19 1 views
0

В моем приложении есть facebook login, создающий пользовательский ui для входа в facebook. Я получаю общий профиль пользователей и электронную почту. время входа в систему с facebook есть экран авторизации, показанный, как показано в 1.jpg. На этом экране есть опция для пользователя, который отображает редактирование информации, которую вы предоставляете. Нажав эту кнопку редактирования, пользователь переходит на следующий экран, где он может отрицать доступ для электронной почты. Моя проблема в том, есть ли какое-либо положение, которое редактирует скрытую информацию, которую вы предоставляете, или есть ли возможность, чтобы пользователь снова попросил разрешения электронной почты.как запросить разрешения для электронной почты еще раз, если его разрешение отклонено в авторизации на facebook login в приложении iOS

1.jpg

Мой код ниже: ********* Appdelegate.h

#import <UIKit/UIKit.h> 
#import <FacebookSDK/FacebookSDK.h> 

@interface AppDelegate : UIResponder <UIApplicationDelegate> 


@property (strong, nonatomic) UIWindow *window; 
@property (strong, nonatomic) NSString *strBasePath; 
-(void)openActiveSessionWithPermissions:(NSArray *)permissions allowLoginUI:(BOOL)allowLoginUI; 

@end 

******Appdelegate.m 


#import "AppDelegate.h" 

@implementation AppDelegate 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
// Override point for customization after application launch. 



return YES; 
} 

-(void)openActiveSessionWithPermissions:(NSArray *)permissions allowLoginUI:(BOOL)allowLoginUI{ 
[FBSession openActiveSessionWithReadPermissions:permissions 
            allowLoginUI:allowLoginUI 
           completionHandler:^(FBSession *session, FBSessionState status, NSError *error) { 

            // Create a NSDictionary object and set the parameter values. 
            NSDictionary *sessionStateInfo = [[NSDictionary alloc] initWithObjectsAndKeys: 
                    session, @"session", 
                    [NSNumber numberWithInteger:status], @"state", 
                    error, @"error", 
                    nil]; 

            // Create a new notification, add the sessionStateInfo dictionary to it and post it. 
            [[NSNotificationCenter defaultCenter] postNotificationName:@"SessionStateChangeNotification" 
                         object:nil 
                        userInfo:sessionStateInfo]; 

           }]; 
} 

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

- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 

if ([FBSession activeSession].state == FBSessionStateCreatedTokenLoaded) { 
    [self openActiveSessionWithPermissions:nil allowLoginUI:NO]; 
} 

[FBAppCall handleDidBecomeActive]; 

} 
#import "ViewController.h" 
#import "AppDelegate.h" 
#import <QuartzCore/QuartzCore.h> 
#import <FacebookSDK/FacebookSDK.h> 

@interface ViewController() 

@property (nonatomic, strong) AppDelegate *appDelegate; 

-(void)hideUserInfo:(BOOL)shouldHide; 

-(void)handleFBSessionStateChangeWithNotification:(NSNotification *)notification; 

@end 

@implementation ViewController 

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
// Do any additional setup after loading the view, typically from a nib. 

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; 


self.imgProfilePicture.layer.masksToBounds = YES; 
self.imgProfilePicture.layer.cornerRadius = 30.0; 
self.imgProfilePicture.layer.borderColor = [UIColor whiteColor].CGColor; 
self.imgProfilePicture.layer.borderWidth = 1.0; 

[self hideUserInfo:YES]; 
self.activityIndicator.hidden = YES; 

self.appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleFBSessionStateChangeWithNotification:) name:@"SessionStateChangeNotification" object:nil]; 



} 

-(void)hideUserInfo:(BOOL)shouldHide{ 
self.imgProfilePicture.hidden = shouldHide; 
self.lblFullname.hidden = shouldHide; 
self.lblEmail.hidden = shouldHide; 
} 

- (IBAction)toggleLoginState:(id)sender { 
if ([FBSession activeSession].state != FBSessionStateOpen && 
    [FBSession activeSession].state != FBSessionStateOpenTokenExtended) { 

[self.appDelegate openActiveSessionWithPermissions:@[@"public_profile", @"email"] allowLoginUI:YES]; 


} 
else{ 
    // Close an existing session. 
    [[FBSession activeSession] closeAndClearTokenInformation]; 

    // Update the UI. 
    [self hideUserInfo:YES]; 
    self.lblStatus.hidden = NO; 
    self.lblStatus.text = @"You are not logged in."; 
    } 

    } 

-(void)handleFBSessionStateChangeWithNotification:(NSNotification *)notification{ 
// Get the session, state and error values from the notification's userInfo dictionary. 
NSDictionary *userInfo = [notification userInfo]; 

FBSessionState sessionState = [[userInfo objectForKey:@"state"] integerValue]; 
NSError *error = [userInfo objectForKey:@"error"]; 

self.lblStatus.text = @"Logging you in..."; 
[self.activityIndicator startAnimating]; 
self.activityIndicator.hidden = NO; 

// Handle the session state. 
// Usually, the only interesting states are the opened session, the closed session and the failed login. 
if (!error) { 
    // In case that there's not any error, then check if the session opened or closed. 
    if (sessionState == FBSessionStateOpen) { 
     // The session is open. Get the user information and update the UI. 
     [FBRequestConnection startWithGraphPath:@"me" 
            parameters:@{@"fields": @"first_name, last_name, picture.type(normal), email"} 
            HTTPMethod:@"GET" 
           completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { 
            if (!error) { 

             // Set the use full name. 
             self.lblFullname.text = [NSString stringWithFormat:@"%@ %@", 
                   [result objectForKey:@"first_name"], 
                   [result objectForKey:@"last_name"] 
                   ]; 

             // Set the e-mail address. 
             self.lblEmail.text = [result objectForKey:@"email"]; 

             // Get the user's profile picture. 
             NSURL *pictureURL = [NSURL URLWithString:[[[result objectForKey:@"picture"] objectForKey:@"data"] objectForKey:@"url"]]; 
             self.imgProfilePicture.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:pictureURL]]; 


             strFbEmail=[result objectForKey:@"email"]; 

             strFbFirstName=[result objectForKey:@"first_name"]; 
             strFbLastName=[result objectForKey:@"last_name"]; 
             strFbAccessToken = [[[FBSession activeSession] accessTokenData] accessToken]; 
             NSLog(@"%@ -------- %@ -------- %@ -------%@",strFbAccessToken,strFbEmail,strFbFirstName,strFbLastName); 

             //[self sendFbData]; 
             // Make the user info visible. 
             [self hideUserInfo:NO]; 

             // Stop the activity indicator from animating and hide the status label. 
             self.lblStatus.hidden = YES; 
             [self.activityIndicator stopAnimating]; 
             self.activityIndicator.hidden = YES; 
            } 
            else{ 
             NSLog(@"%@", [error localizedDescription]); 
            } 
           }]; 

     [self.btnToggleLoginState setTitle:@"Logout" forState:UIControlStateNormal]; 
    } 
    else if (sessionState == FBSessionStateClosed || sessionState == FBSessionStateClosedLoginFailed){ 
     // A session was closed or the login was failed. Update the UI accordingly. 
     [self.btnToggleLoginState setTitle:@"Login" forState:UIControlStateNormal]; 
     self.lblStatus.text = @"You are not logged in."; 
     self.activityIndicator.hidden = YES; 
    } 
} 
else{ 
    // In case an error has occurred, then just log the error and update the UI accordingly. 
    NSLog(@"Error: %@", [error localizedDescription]); 
    [self hideUserInfo:YES];   
    [self.btnToggleLoginState setTitle:@"Login" forState:UIControlStateNormal]; 

} 


} 

ответ

1
if ([FBSession.activeSession.permissions indexOfObject:@"email"] == NSNotFound) { 
    [FBSession.activeSession requestNewReadPermissions:@[@"email"] 
         completionHandler:^(FBSession *session, 
              NSError *error) 
    { 
     // Handle new permissions callback 
    }]; 
} else { 
    // permission exists 
} 

Попробуйте это. Надеюсь, это поможет

Смежные вопросы