I use FirebaseAuthUi to manage authentication in my app.
When users are logged in, I need their Facebook access token to make a graph request. It works fine the first time users log in, but when the app is re-launched the graph API call doesn’t work because I don’t have the Facebook access token anymore.
So I need to save this token in UserDefaults or Keychain. My issue is that I don’t manage to save this token as an AccessToken. I can save it as a String, but then when I want to make my graph call I need an AccessToken and I think that I cannot get an AccessToken from the String saved.
Do you see how I could make it ? Here is my code :
//checkLoggedIn
authHandle = Auth.auth().addStateDidChangeListener { auth, user in
if let user = user {
// User is signed in.
UserDefaults.standard.set(String(describing: AccessToken.current), forKey: "savedFacebookToken")
UserDefaults.standard.synchronize()
let savedFacebookToken = UserDefaults.standard.object(forKey: "savedFacebookToken")
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/me/friends", accessToken: savedFacebookToken as! AccessToken)) { httpResponse, result in
I get the following error message :
Could not cast value of type 'Swift._NSContiguousString' (0x10a0f4f50) to 'FacebookCore.AccessToken' (0x1068aa9f0).
Edit :
I haven’t been able to test it on a real device yet.
3
Answers
Your access token is integer it is not type casting in string. you can save value as this or according your save value you can use last line code.
Get token value
or you can typecast into string
FacebookCore.AccessToken is a struct, which means you can’t save it directly to UserDefaults but you need it to create graph request.
It means the SDK must provide you access token value for cases where user has already logged in. There is a method in AccessToken class which gives you exactly that
You just need to refresh current Token and extend the token’s expiration.
More better way of doing this-:
Create extension for userDefaults-:
In your controller class just call methods like -:
To set -:
To get-:
According to your code-:
REAMRK-:
Please refer below link-:
Storing authentication tokens on iOS – NSUserDefaults vs Keychain?
And i would say no need to save token it can expire or change which can create issues in your app.
Read Facebook document regarding Access Token for more clarification-:
https://developers.facebook.com/docs/facebook-login/access-tokens