Logout of Active Twitter Session Using Fabric - ios

I have read through the forums and suggestions about how to logout of Twitter in Xcode for IOS using Fabric, but I can't get the logOut method to call and logout the user from the current session. Here is my current code for the login view controller:
- (IBAction)TESTT:(id)sender {
[[Twitter sharedInstance] logInWithCompletion:^
(TWTRSession *session, NSError *error) {
if (session != nil) {
NSLog(#"signed in as %#", [session userName]);
} else {
NSLog(#"error: %#", [error localizedDescription]);
}
}];
}
- (IBAction)LOGOUT:(id)sender {
[self logOut];
}
- (void)logOut{
[[Twitter sharedInstance] logOut];
}
I have imported and have the login functionality working well from the Fabric tutorial.
I just can't get the button that I made which is using the LOGOUT action to logout the user from the current Twitter session. I have even tried to clear the cookies to see if that could wipe the Twitter session from the memory and reset it - but nothing. If anyone could help me out I would really appreciate it - thanks!
FYI: PLEASE do not suggest only [[Twitter sharedInstance] logOut]; . This method does not do what I am asking by itself. If someone can tell me how to successfully logout using this method along with the rest of the procedure that would be fine.

After a long extensive series of methods, clearing of cookies, data, almost everything you could think of, I discovered it is actually quite simple.
The easiest way to sign out and clear the previous user session is as follows:
Go to settings
Go to your Twitter and Disallow Twitter access to your app (it should appear here)
Go back to the app and call the following method:
- (void)twitterLogout:(id)sender {
NSUserDefaults *twitterSession = [NSUserDefaults standardUserDefaults];
[twitterSession setObject:0 forKey:#"TwitterSession"];
[twitterSession synchronize];
NSLog(#"Twitter session = %#", twitterSession);
[[Twitter sharedInstance] logOut];
[self.view insertSubview:_logoutTwitter atIndex:16];
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"Twitter"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
for (NSHTTPCookie *cookie in cookies)
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
There is quite a lot in this method, and to be honest some of it is probably extraneous and not even needed, but anyone who needs this can mess around with what should and shouldn't stay. Either way hopefully this helps people - it certainly helped me!

You can use this simple code for Swift 3:
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}

Related

facebook does not logout properly in ios app.cannot switch users

i am using the facebook login button provided by the fb sdk for implementing the facebook login in my app.When i am logging out the facebook button does change back to login again.but when i click on it,the safari app opens showing "you have alreay authorised the app"click confirm or cancel.Actually i needed the facebook login and password screen here.I cannot switch user until i reset the simulator.how to reset the contents in safari programmatically each time i logout so that the login screen is shown each time.
Please note that when i clear the website data of safari manually it shows the login page again.can it be done programmatically.
code i am using for login is as follows
//creating the login button
FBLoginView *loginView =
[[FBLoginView alloc] initWithReadPermissions:
#[#"public_profile", #"email", #"user_friends"]];
loginView.frame=CGRectMake(50, 500, 225, 55);
loginView.delegate=self;
[self.view addSubview:loginView];
//delegate method when logged in
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:[user objectForKey:#"id"] forKey:#"LoggedInUserID"] ;
[self checkandsaveNewUserInBackend:user];
[self performSegueWithIdentifier:#"Login" sender:self];
}
//logout code
- (IBAction)logoutButtonPressed:(id)sender {
[FBSession.activeSession closeAndClearTokenInformation];
[self.navigationController popToRootViewControllerAnimated:YES];
}
try this it user clicks on logout and remove all keys stored in userdefault/cookies
NSLog(#"Logged out facebook");
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
Try this...
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
May work for you...
And for clear cookies from browser...follow this link \
http://www.iossnippet.com/snippets/web/how-to-delete-cookies-nshttpcookie-in-objective-c-ios/
In the
//logout code
- (IBAction)logoutButtonPressed:(id)sender {
Use following code
if (FBSession.activeSession.state == FBSessionStateOpen
|| FBSession.activeSession.state == FBSessionStateOpenTokenExtended) {
// Close the session and remove the access token from the cache
// The session state handler (in the app delegate) will be called automatically
[FBSession.activeSession closeAndClearTokenInformation];
// If the session state is not any of the two "open" states when the button is clicked
} else {
// Open a session showing the user the login UI
// You must ALWAYS ask for public_profile permissions when opening a session
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile"]
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
}];
}

How to make User logout from twitter fabric ios

I have made a basic app using Twitter's fabric that allows user to tweet within my app and Provide Login With Twitter.Every things works a I Wanted.
How my app Works
If the user doesn't logged in to twitter my app allows him to login and if he is login then directly allows him to tweet.
Now the Big Part Comes
As I saw in many Apps I Can Remove my signed account from the app.And I am not able to get any method that help me to achieve this. I want to allow user to logout from twitter within my app whenever he/She wants.
I googled but i doesn't find anything
Here Is my Code:
- (IBAction)LogOut:(id)sender
{
[[Twitter sharedInstance]logOut];
}
- (IBAction)LogMeIn:(id)sender
{
[[Twitter sharedInstance] logInWithCompletion:^
(TWTRSession *session, NSError *error) {
if (session) {
NSLog(#"signed in as %#", [session userName]);
[LoginButton setTitle:#"LogOut" forState:normal];
} else {
NSLog(#"error: %#", [error localizedDescription]);
}
}];
}
this was a problem with NSCookie from Foundation framework And i slove this issues with help of below code
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"];
NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:url];
for (NSHTTPCookie *cookie in cookies)
{
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
You need to use below code
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
Provide user id of the user you want to logout.
UPDATE: May 2016 - Framework has changed so this answer is no longer relevant.
See this answer:
https://stackoverflow.com/a/35765833/940709
and this answer:
https://stackoverflow.com/a/30916904/940709 instead.
[[[Twitter sharedInstance] sessionStore] logOutUserID:USERID];
This is the best simple answer for Swift 3:
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
or you can use Naeem's answer but add () after store.session
Logout Code From Twitter Docs:
Objective-C
TWTRSessionStore *store = [[Twitter sharedInstance] sessionStore];
NSString *userID = store.session.userID;
[store logOutUserID:userID];
Swift
let store = Twitter.sharedInstance().sessionStore
if let userID = store.session()?.userID {
store.logOutUserID(userID)
}
For Swift try this,
/**
* Deletes the local Twitter user session from this app. This will not remove the system Twitter account nor make a network request to invalidate the session.
*
* #param userID ID of the user to log out
*/
Twitter.sharedInstance().sessionStore.logOutUserID(userId)
First make sure some user is signed in, then perform logout.
NSString *signedInUserID = [TWTRAPIClient clientWithCurrentUser].userID;
if (signedInUserID) {
[[Twitter sharedInstance].sessionStore logoutUserID:signedInUserID];
}
While login mention method as webBasedForceLogin, so that it will not create entry into Safari Cache.
private func twitterLogin() {
Twitter.sharedInstance().logIn(withMethods: .webBasedForceLogin, completion: { (session, error) in
if let error = error {
print(error.localizedDescription)
}
guard let session = session else {
return
}
print("success! Welcome \(session.userName).")
self.twitterButton.setTitle("TWITTER LOGOUT", for: .normal)
})
}
private func twitterLogout() {
let sessionStore = Twitter.sharedInstance().sessionStore
if let userID = sessionStore.session()?.userID {
sessionStore.logOutUserID(userID)
}
twitterButton.setTitle("TWITTER LOGIN", for: .normal)
}
Use below:
[TWTRSessionStore logout]
Deprecated:
[Twitter logOut]
is deprecated.
Users are encouraged to call - [TWTRSessionStore logout] instead of calling this method on the Twitter instance directly.

How do I remove everything my App has stored about Facebook?

The Facebook SDK for iOS come with some sample applications. E.g. FriendPickerSample and SessionLoginSample. In both when I try to login it will remember my previous facebook users. But I don't want that because I want to use it with another facebook user. How do I clear the info Facebook has cached so that login will act the same as the very first time I tried to login on this device with this particular app?
Does facebook cache all its information in the app bundled? And what info does it store and in what files?
You need to remove all the keys stored by facebook once user logs out.
- (void)fbDidLogout
{
NSLog(#"Logged out of facebook");
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}
[[FBSession activeSession] close];
[[FBSession activeSession] closeAndClearTokenInformation];

ios Facebook integration error when logged out and logged in

I am trying to use Facebook integration into my app. I use the following code to log in.
After i am logged in and when i log out the app relaunches completely from the beginning and also each time the permission is asked. I only want it to ask permission in the first time when i login with a particular user. But it asks always when i log out and try to login back with the Facebook button.
- (IBAction)facebook:(id)sender
{
FBLoginView *loginView=[[FBLoginView alloc]init];
loginView.delegate=self;
loginView.readPermissions = #[#"first_name",
#"last_name",
#"location",
#"id",
#"access_token",
#"email"];
NSArray* permissions = [NSArray arrayWithObjects: #"email", nil];
loginView.readPermissions = #[#"email"];
loginView.readPermissions=permissions;
[FBSession openActiveSessionWithAllowLoginUI:YES];
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user1,
NSError *error)
{
if (!error)
{
firstname=user1.first_name;
lastname=user1.last_name;
city=[user1.location objectForKey:#"name"];
email=user1[#"email"];
fbid=user1.id;
Loggedin=#"Y";
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]synchronize];
}
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#action=currfbuser&email=%#&fb_id=%#",MainURL,email,fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
status = json[#"status"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
[self performSegueWithIdentifier: #"LogIN" sender: self];
}
else if (!([fbid isEqualToString:#""]))
{
[self performSegueWithIdentifier: #"Facebooksegue" sender: self];
}
NSLog(#"%#",firstname);
NSLog(#"%#",lastname);
NSLog(#"%#",city);
NSLog(#"%#",email);
NSLog(#"%#",fbid);
}];
}
The following code i have used to log out.
- (IBAction)Logout:(id)sender
{
_DetailsView.hidden=YES;
_fade.hidden=YES;
y=0;
Loggedin=#"N";
user=nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
[FBSession.activeSession closeAndClearTokenInformation];
[[NSUserDefaults standardUserDefaults]setObject:Loggedin forKey:#"token"];
[[NSUserDefaults standardUserDefaults]setObject:user forKey:#"user"];
[[NSUserDefaults standardUserDefaults]synchronize];
[self.navigationController popToRootViewControllerAnimated:YES];
}
This is the first time i am integrating Facebook. So i am not much kind of sure about the code i am using.
The user data fetching is working perfectly fine. The problem is that the app asks for permission each time and if i press Ok or skip for permission both does the same thing that is the app relaunches when i click ok or skip.
The output i obtained has been uploaded in youtube. Please check the following link.
http://youtu.be/ki7BXr8dXmw
I been stuck with this and can't move forward coz of this bug.
Please help me with this and i can give out 50 bounty for the solution when the bounty is available.
Thank you.
Well i have few suggestions. Here you are always opening FB session with login UI.
[FBSession openActiveSessionWithAllowLoginUI:YES];
That is not required always. Once you authorized the user and you got the required permission you no longer needed the login UI. So how will you decide my user is authorized or not?? Just try to login on behalf of user without Login UI (fallback login)
[FBSession openActiveSessionWithAllowLoginUI:NO]; // Should go in viewDidLoad or applicationDidFinishLaunching
If this login attempt success(Taking the cached token), well you have an active FBSession. Now the actual facebook api usage comes. Do a simple check
if (FBSession.activeSession.isOpen)
{
[self getFacebookFriends];
}
else
{
// User is not logged in
[FBSession openActiveSessionWithAllowLoginUI:YES];
}

Login Logout issue with facebook iOS sdk

We have got sruck in the iOS facebook login logout issue. When I login to facebook using my application it will prompt for user permission with 'login' and 'cancel' button. But this screen appears only on the very first time. ie Once we logged in using safari or the app and even if we logged out from facebook , application the screen prompting for user permission displays only an 'ok' button. It doesnt allow to sign in as a different user. Why the screen with 'login' and 'cancel' button not displaying each time the application launches? I tried by deleting cookies and removing NSUserDefaults but no luck.
The problem is after logout, I am unable to login to the facebook as another user. It still shows as the same user.
I am calling the below logout function in sdk
(void)logout:(id<FBSessionDelegate>)delegate {
self.sessionDelegate = delegate;
[_accessToken release];
_accessToken = nil;
[_expirationDate release];
_expirationDate = nil;
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:
[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
if ([self.sessionDelegate respondsToSelector:#selector(fbDidLogout)]) {
[_sessionDelegate fbDidLogout];
}
}
Also in fbDidLogout delegate function I removed all NSUserDefaults objects
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]) {
[defaults removeObjectForKey:#"FBAccessTokenKey"];
[defaults removeObjectForKey:#"FBExpirationDateKey"];
[defaults synchronize];
}
regrds
Shihab
You can clear the session as well as clearing the cookies with the following code:
FBSession* session = [FBSession activeSession];
[session closeAndClearTokenInformation];
[session close];
[FBSession setActiveSession:nil];
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:[NSURL URLWithString:#"https://facebook.com/"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
FBSession openWithBehavior:completionHandler: can be used..
FBSession *fbSession = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObjects:#"email",#"publish_actions",#"publish_stream", nil]];
[fbSession openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session,FBSessionState state, NSError *error){
[FBSession setActiveSession:fbSession]; // Retain the Active Session.
}];
For Logging out, Ans by Ellen S.. worked fine for iOS .
I modified fbDidLogout method and it worked, here is the code:
-(void) fbDidLogout
{
NSLog(#"Logged out of facebook");
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
NSString* domainName = [cookie domain];
NSRange domainRange = [domainName rangeOfString:#"facebook"];
if(domainRange.length > 0)
{
[storage deleteCookie:cookie];
}
}
}//End of Method
The method successfully logs out the user.
Hope this will help!
I just figure it out I got in the settings of my iPhone and got to privacy chose the Facebook tab and turn off where it says Applications that have requested access to you Facebook account will appear here. It works!!!
When login to set to loginBehavior, so when you exit, with the other account login, won't appear only authorized, without the login screen login.loginBehavior =FBSDKLoginBehaviorWeb; i use facebook 4.11,it's work

Resources