2014-02-25 140 views
14

的代碼,我從這個代碼,我需要獲得用戶名和郵件ID使用如何獲取Facebook SDK的用戶名和電子郵件ID?

if (FBSession.activeSession.state == FBSessionStateOpen 
     || FBSession.activeSession.state == FBSessionStateOpenTokenExtended) { 

     // Close the session and remove the access token from the cache 
     // The session state handler (in the app delegate) will be called automatically 
     [FBSession.activeSession closeAndClearTokenInformation]; 


     // If the session state is not any of the two "open" states when the button is clicked 
    } else { 
     // Open a session showing the user the login UI 
     // You must ALWAYS ask for basic_info permissions when opening a session 
     [FBSession openActiveSessionWithReadPermissions:@[@"basic_info,email"] 
              allowLoginUI:YES 
             completionHandler: 
     ^(FBSession *session, FBSessionState state, NSError *error) { 




      // Retrieve the app delegate 
      AppDelegate* appDelegate = [UIApplication sharedApplication].delegate; 
      // Call the app delegate's sessionStateChanged:state:error method to handle session state changes 
      [appDelegate sessionStateChanged:session state:state error:error]; 
     }]; 
    } 

。如果有人知道解決方案,請提前幫助我。

+0

[\ [Facebook-iOS-SDK 4.0 \]可能的重複如何從FBSDKProfile獲取用戶電子郵件地址](http://stackoverflow.com/questions/29323244/facebook-ios-sdk-4-0how-to- get-user-email-address-from-fbsdkprofile) – AechoLiu

回答

12

使用下面的代碼

FBSession *session = [[FBSession alloc] initWithPermissions:@[@"basic_info", @"email"]]; 
    [FBSession setActiveSession:session]; 

    [session openWithBehavior:FBSessionLoginBehaviorForcingWebView 
      completionHandler:^(FBSession *session, 
           FBSessionState status, 
           NSError *error) { 
       if (FBSession.activeSession.isOpen) { 
        [[FBRequest requestForMe] startWithCompletionHandler: 
        ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) { 
         if (!error) { 
           NSLog(@"accesstoken %@",[NSString stringWithFormat:@"%@",session.accessTokenData]); 
          NSLog(@"user id %@",user.id); 
          NSLog(@"Email %@",[user objectForKey:@"email"]); 
          NSLog(@"User Name %@",user.username); 
         } 
        }]; 
       } 
      }]; 
+0

「user.username」不起作用。改用「user [@」name「]」。 – Sebyddd

+2

「basic_info」不再可用,您應該使用「public_info」權限。資料來源:http://stackoverflow.com/questions/24762791/facebook-sdk-invalide-scope-basic-info-use-public-profile-user-friends-inst –

3

對新代碼的Facebook SDK版本4.0及以上

看到這個link

下面

// use facebook SDK 3.8 

加入的AppDelegate下面的方法。 m

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication: (NSString *)sourceApplication annotation:(id)annotation 
{ 
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication fallbackHandler:^(FBAppCall *call) 
     { 
      NSLog(@"Facebook handler"); 
     } 
     ]; 
} 


- (void)applicationDidBecomeActive:(UIApplication *)application 
{ 
[FBAppEvents activateApp]; 
[FBAppCall handleDidBecomeActive]; 
// 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. 
} 

- (void)applicationWillTerminate:(UIApplication *)application 
{ 
[FBSession.activeSession close]; 
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
} 

本身在viewcontroler的follwing代碼.H

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

@interface ViewController : UIViewController<FBLoginViewDelegate> 


@property (strong, nonatomic) IBOutlet UILabel *lblUserName; 
@property (strong, nonatomic) IBOutlet UITextField *txtEmailId; 
@property (strong, nonatomic) IBOutlet UIButton *lblCreate; 
@property (strong, nonatomic) IBOutlet FBProfilePictureView *profilePic; 

@property (strong, nonatomic) id<FBGraphUser> loggedInUser; 

- (IBAction)butCreate:(id)sender; 

- (void)showAlert:(NSString *)message 
     result:(id)result 
     error:(NSError *)error; 

@end 

//應用下面的代碼到視圖Controller.m或者

- (void)viewDidLoad 
{ 
[super viewDidLoad]; 
FBLoginView *loginview=[[FBLoginView alloc]initWithReadPermissions:@[@"email",@"user_likes"]]; 
loginview.frame=CGRectMake(60, 50, 200, 50); 
loginview.delegate=self; 
[loginview sizeToFit]; 
[self.view addSubview:loginview]; 

} 

-(void)loginViewShowingLoggedInUser:(FBLoginView *)loginView 
{ 
self.lblCreate.enabled=YES; 
self.txtEmailId.enabled=YES; 
self.lblUserName.enabled=YES; 


} 

-(void)loginViewFetchedUserInfo:(FBLoginView *)loginView user:(id<FBGraphUser>)user 
{ 
self.lblUserName.text=[NSString stringWithFormat:@"%@",user.name]; 
self.txtEmailId.text=[user objectForKey:@"email"]; 
//self.profilePic.profileID=user.id; 
self.loggedInUser=user; 
} 

-(void)loginViewShowingLoggedOutUser:(FBLoginView *)loginView 
{ 

self.txtEmailId.text=nil; 
self.lblUserName.text=nil; 
self.loggedInUser=nil; 
self.lblCreate.enabled=NO; 

} 
-(void)loginView:(FBLoginView *)loginView handleError:(NSError *)error{ 
    NSLog(@"Show the Error ==%@",error); 
} 

夫特1.2 &上述

創建詞典:

class ViewController: UIViewController { 
    var dict : NSDictionary! 
} 

獲取數據:

if((FBSDKAccessToken.currentAccessToken()) != nil){ 
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in 
     if (error == nil){ 
      self.dict = result as NSDictionary    
      println(self.dict) 
      NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String) 
     } 
    }) 
} 

輸出應該是:

{ 
    email = "[email protected]"; 
    "first_name" = Karthi; 
    id = 924483474253864; 
    "last_name" = keyan; 
    name = "karthi keyan"; 
    picture =  { 
     data =   { 
      "is_silhouette" = 0; 
      url = "XXXXXXX"; 
     }; 
    }; 
} 
+2

它是隻是我還是這個答案奇怪的組合Objective-C和Swift? – RobP

1

提出以下要求後成功登錄,你不爲她讀publish_actions權限。

/* make the API call */ 
[FBRequestConnection startWithGraphPath:@"/me" 
          parameters:nil 
          HTTPMethod:@"GET" 
         completionHandler:^(
          FBRequestConnection *connection, 
          id result, 
          NSError *error 
        ) { 
          /* handle the result */ 
         }]; 

請點擊此鏈接:

[user objectForKey:@"id"], 

[user objectForKey:@"username"], 

[user objectForKey:@"email"]. 

希望它會:https://developers.facebook.com/docs/graph-api/reference/user

1

您可以通過使用NSDictionary: NSDictionary<FBGraphUser> *user, 你只需要使用objectforkey訪問這樣的價值觀得到這些信息爲你工作。

-2
  1. 首先,您必須通過GraphAPI獲取您的應用程序的訪問權限。

用objectandKey創建一個NSMutableDictionary。 你的對象將是你正在接受的價值,例如你的名字和你的emailId。

代碼片段:

NSMutableDictionary *params=[[NSMutableDictionary alloc]init]; 

[params setObject:nameStr forKey:@"name"]; 

[params setObject:emailStr forKey:@"email"]; 
0
[FBRequestConnection startWithGraphPath:@"/me" 
          parameters:nil 
          HTTPMethod:@"GET" 
         completionHandler:^(
              FBRequestConnection *connection, 
              NSDictionary *result, 
              NSError *error 
             ) { 
          /* handle the result */ 
          _fbId = [result objectForKey:@"id"]; 
          _fbName = [result objectForKey:@"name"]; 
          _fbEmail = [result objectForKey:@"email"]; 

          NSLog(@"%@",_fbId); 
          NSLog(@"%@",_fbName); 
          NSLog(@"%@",_fbEmail); 
         }]; 
0

使用此代碼:

FBSession *session = [[FBSession alloc] initWithPermissions:@[@"public_profile"]]; 
    [FBSession setActiveSession:session]; 

    [session openWithBehavior:FBSessionLoginBehaviorForcingWebView 
      completionHandler:^(FBSession *session, 
           FBSessionState status, 
           NSError *error) { 
       if (FBSession.activeSession.isOpen) 
       { 
        [[FBRequest requestForMe] startWithCompletionHandler: 
        ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) 
        { 
         if (!error) 
         { 
          NSLog(@"%@", user); 
          [[[UIAlertView alloc] initWithTitle:@"welcome" 
                 message:[NSString stringWithFormat:@"%@\n%@\n%@\n%@\n%@\n%@", 
                    user[@"name"], 
                    user[@"gender"], 
                    user[@"id"], 
                    user[@"link"], 
                    user[@"email"], 
                    user[@"timezone"]] 
                 delegate:nil 
               cancelButtonTitle:@"OK" 
               otherButtonTitles:nil] 
           show]; 
         } 
        }]; 
       } 
      }]; 
16
if ([FBSDKAccessToken currentAccessToken]) { 
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@{@"fields": @"email,name,first_name"}] 
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) { 
          if (!error) { 
           NSLog(@"fetched user:%@", result); 
           NSLog(@"%@",result[@"email"]); 

          } 
         }]; 


       } 
+0

謝謝,它爲我工作 – Anshul

1

這個目前與最新版本的FB SDK的:

某處設置之前正確設置FB登錄按鈕(假設爲self.facebookLoginButton通過IB初始化):

self.facebookLoginButton.readPermissions = @[@"public_profile", @"email"]; 
self.facebookLoginButton.delegate = self; 

然後在loginButton:didCompleteWithResult:error:

- (void)loginButton:(FBSDKLoginButton *)loginButton 
didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result 
       error:(NSError *)error 
{ 
    NSDictionary *parameters = @{@"fields":@"email,name"}; 
    FBSDKGraphRequest *graphRequest = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:parameters]; 
    [graphRequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) 
    { 
     LogInfo(@"fetched user:%@", result); 
    }]; 
} 

下面是引用頁面,幫助:https://developers.facebook.com/docs/graph-api/reference/user

0

Facebook的IOS SDK獲取用戶名和電子郵件迅速3

FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in 
      if (error == nil){ 
       let fbDetails = result as! NSDictionary 
       print(fbDetails) 
      }else{ 
       print(error?.localizedDescription ?? "Not found") 
      } 
     }) 
0

用戶對象的用戶名字段已被刪除,並且在Graph API v2.0中不存在。在API的v2.0中,沒有辦法獲得用戶的FB用戶名。您可以使用應用作用域ID作爲用戶名。

Facebook擺脫了用戶名,因爲用戶名是通過Facebook發送電子郵件的一種方式。 例如,給定URL http://www.facebook.com/sebastian.trug 相應的Facebook電子郵件將是[email protected] ,如果通過電子郵件發送,它將直接收到消息(如果消息設置設爲公開),否則將收到其他收件箱。

來源:https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api

這裏是任何地方的查殺後主動登錄信息爲SWIFT 3.0

代碼
 let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", 
    parameters: ["fields":"first_name,email, picture.type(large)"]) 

      graphRequest.start(completionHandler: { (connection, result, 
      error) -> Void in 

       if ((error) != nil) 
       { 
        print("Error: \(error)") 
       } 
       else 
       { 
        let data:[String:AnyObject] = result as! [String : AnyObject] 
        print(data) 

       } 
      }) 
0

的Xcode 8.2.1和Objective-C

應用程序

FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/?fields=name,picture,birthday,email,location"]; 
       [friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) 
        { 
         if(error == nil) { 

          UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Success in fetching Facebook information." delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil]; 
          [alert show]; 

         } 
         else 
         { 
          UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"Facebook" message:@"Problem in fetching Facebook Information. Try Later!" delegate:self cancelButtonTitle:@"OK"otherButtonTitles:nil, nil]; 
          [alert show]; 
         } 


        }]; 
相關問題