senty
senty

Reputation: 12857

FBSDKAccessToken.currentAccessToken().userID sometimes returning Nil

I am trying to create a Profile signup page, and assigning image from Facebook after segued from 'Login with Facebook' page. However on this line...

        let userID = FBSDKAccessToken.currentAccessToken().userID

... sometimes it's working excellent but sometimes returning 'nil', and I am getting

  ' 2015-04-16 15:08:41.195 FacebookLogin[65906:4225996] [Error]: invalid session token (Code: 209, Version: 1.7.1) 
 fatal error: unexpectedly found nil while unwrapping an Optional value
 (lldb) '

Here is the full code:

 override func viewDidLoad() {
    super.viewDidLoad()



    if let currentUser = PFUser.currentUser() {

        let accessToken = FBSDKAccessToken.currentAccessToken()

        let userID = FBSDKAccessToken.currentAccessToken().userID

        println(userID)
        let url = NSURL(string: "https://graph.facebook.com/"+userID+"/picture?width=300&height=300")

        let urlRequest = NSURLRequest(URL: url!)


        NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
            response, data, error in



            let image = UIImage(data: data)

            self.profilePicture.image = image


            currentUser.saveInBackground()

            })



    }

}

How can I find a workaround?

Upvotes: 3

Views: 4070

Answers (2)

kalpeshdeo
kalpeshdeo

Reputation: 1274

You should return this from didFinishLaunchingWithOptions

return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

Upvotes: 2

Utku Dalmaz
Utku Dalmaz

Reputation: 10172

I was having the same issue

Try adding these

self.fbLoginButton.delegate = self
FBSDKProfile.enableUpdatesOnAccessTokenChange(true)

Upvotes: 3

Related Questions