Facebook SDK v4.0 for iOS - FBSDKProfile currentProfile not being set

fanfan picture fanfan · Mar 27, 2015 · Viewed 10.4k times · Source

I've just "upgraded" my Facebook SDK to 4.0 for my iOS app.

I've got the log in working okay, however, according to the documentation, I'm now supposed to use FBSDKProfile.currentProfile() to access profile information.

However, this value always seems to be nil, even though my profile picture is being displayed (through a FBSDKProfilePictureView) and my FBSDKAccessToken.currentAccessToken() is not nil.

This is my login ViewController:

import UIKit

class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {

    @IBOutlet weak var fbLoginButton: FBSDKLoginButton!
    @IBOutlet weak var fbProfilePicture: FBSDKProfilePictureView! //displays a picture

    override func viewDidLoad() {
        super.viewDidLoad()
        self.fbLoginButton.delegate = self
        FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
        if FBSDKAccessToken.currentAccessToken() != nil {
            println("\(FBSDKAccessToken.currentAccessToken().userID)") //works
        }
        self.fbLoginButton.readPermissions = ["public_profile", "email", "user_friends"]
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        println(FBSDKProfile.currentProfile()) //is nil
    }

    func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
    }
}

Any ideas?

Answer

Johnny Z picture Johnny Z · Mar 29, 2015

Don't forget FBSDKProfile.enableUpdatesOnAccessTokenChange(true)!! I struggled with this for awhile until I found that in the docs. Then subscribing to notifications on FBSDKProfileDidChangeNotification should work for the FBSDKLoginButton.

Full Example... I hook up loginButton via Interface Builder

class LoginController: UIViewController, FBSDKLoginButtonDelegate {

@IBOutlet var loginButton: FBSDKLoginButton!

override func viewDidLoad() {
    super.viewDidLoad()
    loginButton.delegate = self;
    FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "onProfileUpdated:", name:FBSDKProfileDidChangeNotification, object: nil)

}

func onProfileUpdated(notification: NSNotification)
{
}

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!){

}

func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {

}

}