How to save and access Twitter Twitter login (iOS / Swift)?

I can log in to Twitter through my application using this Twitter cloth code:

let logInButton = TWTRLogInButton(logInCompletion: { (session: TWTRSession!, error: NSError!) in // play with Twitter session if (session != nil) { println("signed in as \(session.userName)"); self.TWUsernameLabel.text = "Logged in as @" + session.userName } else { println("error: \(error.localizedDescription)"); } }) 

When I press the login button, I am asked to approve the login, and then enters me into the system, or he knows that I have already approved the login, and he registers me. It works like a charm and takes all ten minutes to set up. Amazing

I already have an email to enter the application. I would like to keep the user registered in the Twitter account in the same database, so when the user logs in with his email, I already know their Twitter (if they logged in earlier), and they do not need to log in again to the system, The reason I am registering by email is that Twitter is an important feature in my application, but not a general requirement.

The problem is that I have no idea how to access session outside of the button click and logInCompletion , and I don’t know which variables to store at the first login / check when using the application.

I've read Twitter documentation many times, but it’s not written fast, so it’s pretty confusing. Any ideas? Thanks

+6
source share
3 answers

If a session is currently active, you must have access to it, as the docs say,

 Twitter.sharedInstance().session() 

If the user has not logged into this method, it will return zero. If you want to find out if someone has already passed authentication, just check if this method returns a value or not.

+3
source

Twitter automatically displays the login screen if the user is not logged in (the session does not exist ..). But before calling any future API, just check if the session is valid or not. In some APIs, you may need this session as well.

 if ([[Twitter sharedInstance] session]) { TWTRShareEmailViewController *shareEmailViewController = [[TWTRShareEmailViewController alloc] initWithCompletion:^(NSString *email, NSError *error) { NSLog(@"Email %@ | Error: %@", email, error); }]; [self presentViewController:shareEmailViewController animated:YES completion:nil]; } else { // Handle user not signed in (eg attempt to log in or show an alert) } } 

You don’t even have to worry about maintaining and managing access token and access token secret .

+1
source

To access authToken, the username or user ID for the login session in Swift 4 is:

 Twitter.sharedInstance().logIn(completion: { (session, error) in if (session != nil) { print(session!.authToken) print(session!.userName) print(session!.userID) } else { print(error?.localizedDescription) } }) 
0
source

Source: https://habr.com/ru/post/985728/


All Articles