iOS Facebook SDK 4 会话

Posted

技术标签:

【中文标题】iOS Facebook SDK 4 会话【英文标题】:iOS Facebook SDK 4 Session 【发布时间】:2015-05-20 10:22:28 【问题描述】:

我在使用适用于 ios 的新 FacebookSDK 时遇到问题。

我可以成功登录并取回必要的信息,但是当我再次打开我的应用并打算跳过登录过程时,我正在验证的会话为空。

这是我的 AppDelegate:

class AppDelegate: UIResponder, UIApplicationDelegate 

var window: UIWindow?

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 

    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    self.window!.rootViewController = LogInViewController()
    self.window!.makeKeyAndVisible()

    FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
    return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)


func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject?) -> Bool 
        return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)


func applicationDidBecomeActive(application: UIApplication) 
    FBSDKAppEvents.activateApp()


这是我的 Facebook 登录视图控制器:

class LogInViewController: UIViewController, FBSDKLoginButtonDelegate 
// MARK: Properties
@IBOutlet weak var logInView: FBSDKLoginButton!

// MARK: Init
init()  super.init(nibName: "LogInViewController", bundle: nil) 
required init(coder aDecoder: NSCoder)  fatalError("init(coder:) has not been implemented") 

// MARK: View Delegates
override func viewDidLoad() 
    super.viewDidLoad()

    if (FBSDKAccessToken.currentAccessToken() != nil) 
        // User is already logged in, do work such as go to next view controller.
        println(FBSDKAccessToken.currentAccessToken().tokenString)
        self.goToNavigation()
     else 
        logInView.readPermissions = ["public_profile", "email", "user_friends"]
        logInView.delegate = self
    


// MARK: Facebook Delegate Methods
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) 
    println("User Logged In")

    if ((error) != nil) 
        // Process error
     else if result.isCancelled 
        // Handle cancellations
     else 
        // If you ask for multiple permissions at once, you
        // should check if specific permissions missing
        if result.grantedPermissions.contains("email") 
            // Do work
            returnUserData()
        
    


func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) 
    println("User Logged Out")


func returnUserData() 
    let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphpath: "me", parameters: nil)
    graphRequest.startWithCompletionHandler( (connection, result, error) -> Void in

        if ((error) != nil) 
            // Process error
            println("Error: \(error)")
         else 
            println("fetched user: \(result)")
            let userName : NSString = result.valueForKey("name") as! NSString
            println("User Name is: \(userName)")
            let userEmail : NSString = result.valueForKey("email") as! NSString
            println("User Email is: \(userEmail)")
        
        self.goToNavigation()
    )


func goToNavigation() 
    // Creating a navigation controller with MainMenuViewController at the root of the navigation stack.
    let navController = UINavigationController(rootViewController: MainMenuViewController())
    self.presentViewController(navController, animated:true, completion: nil)


当我检查if (FBSDKAccessToken.currentAccessToken() != nil) 时,会话总是为空,尽管按钮标题是“注销”。

这可能是什么问题? 欢迎提出任何建议!

【问题讨论】:

用问题和答案检查这篇文章 - ***.com/questions/30205396/… 你也可以检查一下 - ***.com/questions/30042905/… 【参考方案1】:

你自己的答案是好的。有关更多信息,您可以使用自定义 facebook 按钮,当登录过程实际获取访问令牌时,您可以调用获取数据请求。

使用自定义按钮和访问令牌登录。

在 facebook sdk 4.x 中获取用户信息

斯威夫特

@IBAction func btnFBLoginPressed(sender: AnyObject) 
    var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager .logInWithReadPermissions(["email"], handler:  (result, error) -> Void in
        if (error == nil)
            var fbloginresult : FBSDKLoginManagerLoginResult = result
            if(fbloginresult.grantedPermissions.containsObject("email"))
            
                self.getFBUserData()
                fbLoginManager.logOut()
            
        
    )


func getFBUserData()
    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)
                println(result)
            
        )
    

输出:


    email = "ashishkakkad8@gmail.com";
    "first_name" = Ashish;
    id = 910855688971343;
    "last_name" = Kakkad;
    name = "Ashish Kakkad";
    picture =     
        data =         
            "is_silhouette" = 0;
            url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/10394859_900936369963275_5557870055628103117_n.jpg?oh=fefbfca1272966fc78286c36741f9ac6&oe=55C89225&__gda__=1438608579_9133f15e55b594f6ac2306d61fa6b6b3";
        ;
    ;

目标-C

使用 Facebook SDK 4.x 登录

将以下代码添加到facebook登录按钮点击:

FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:@[@"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
 
     if (error)
     
         // Error
     
     else if (result.isCancelled)
     
         // Cancelled
     
     else
     
         if ([result.grantedPermissions containsObject:@"email"])
         
             [self getFBResult];
         
     
];

获取Facebook结果方法:

-(void)getFBResult

    if ([FBSDKAccessToken currentAccessToken])
    
        [[[FBSDKGraphRequest alloc] initWithGraphPath:@"me" parameters:@@"fields": @"id, name, first_name, last_name, picture.type(large), email"]
         startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) 
             if (!error)
             
                 NSLog(@"fb user info : %@",result);
             
             else
             
                 NSLog(@"error : %@",error);
             
         ];   
    

您可以根据需要更改权限字段。

【讨论】:

你可以为 Objective C 发布相同的内容,那么它会好得多 查看开发者账号@Imran的facebook状态,应用状态应该是公开的(绿色) 让我们continue this discussion in chat。【参考方案2】:

解决了! 非常感谢 Vijay Masiwal 的建议!

就像在建议的帖子中一样,我通过对 FBSDKAccessTokenDidChangeNotification 使用 NSNotificationCenter 观察者解决了这个问题:

    override func viewDidLoad() 
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkLogIn", name: FBSDKAccessTokenDidChangeNotification, object: nil)


func checkLogIn() 
    if (FBSDKAccessToken.currentAccessToken() != nil) 
        // User is already logged in, do work such as go to next view controller.
        println(FBSDKAccessToken.currentAccessToken().tokenString)
        self.goToNavigation()
     else 
        logInView.readPermissions = ["public_profile", "email", "user_friends"]
        logInView.delegate = self
    

【讨论】:

以上是关于iOS Facebook SDK 4 会话的主要内容,如果未能解决你的问题,请参考以下文章

Facebook iOS SDK > 4.0 替代 initWithAppId?

Facebook iOS SDK - 打开会话并请求读取权限

Facebook iOS SDK 3.0 - 会话未打开

在 iOS 上使用带有 UIActivityViewController 的 Facebook SDK 会话对象

iOS Facebook SDK 在设备上进行身份验证后未重定向

使用 Facebook PHP SDK 4,但没有存储会话