Swift 1.2 and Facebook’s New Login SDK

I’ve had the pleasure of working with Apple’s new Swift over the last few months, and recently ran into some problems integrating Facebook’s API with an iOS 8 app I’m building.

The problem I was having is that, immediately after login, I couldn’t seem to get the user’s access token.


was always returning nil, even with the user logged in.

You need to get this token so that you can send it to your Rails app (or whatever you’re using on the back end) and perform Facebook authentication on behalf of your user up there.

My viewDidLoad looked like this:

override func viewDidLoad() {
// Do any additional setup after loading the view, typically from a nib.
println(FBSDKAccessToken.currentAccessToken()) //prints nil
if (FBSDKAccessToken.currentAccessToken() != nil)
// User is already logged in, do work such as go to next view controller.
println("this never prints")
let loginView : FBSDKLoginButton = FBSDKLoginButton()
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self

I used Brian Coleman's helpful tutorial to get started, but it must not be updated for the latest SDK, because I followed it to a T and was definitely not getting the token. Here's what I needed to change:
//added the following line in my viewDidLoad 
Created a callback function to handle the updating of the FBSDKAccessToken state:
// in a LoginViewController.swift
func onTokenUpdated(notification: NSNotification) {
if ((FBSDKAccessToken.currentAccessToken()) != nil) {
println("token is not nil ")
} else {
println("token is nil")
finally, in my viewDidLoad function, I added:
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onProfileUpdated:", name:FBSDKAccessTokenDidChangeNotification, object: nil)
And this did it! Hope this helps you! Leave a comment if you have any questions.