Search code examples
iosauthenticationtwitteraccess-tokenmgtwitterengine

MGTwitterEngine for iOS : how to get accessToken? Error 401


I'm using MGTwitterEngine library for my iOS app to post tweets.

NSString *username = dataBase.twiLog;
NSString *password = dataBase.twiPas;                    

NSString *consumerKey = cons_key;
NSString *consumerSecret = cons_secret;

// Most API calls require a name and password to be set...
    if (! username || ! password || !consumerKey || !consumerSecret) {
       NSLog(@"You forgot to specify your username/password/key/secret in AppController.m, things might not work!");
       NSLog(@"And if things are mysteriously working without the username/password, it's because NSURLConnection is using a session cookie from another connection.");
 }       
// Create a TwitterEngine and set our login details.
MGTwitterEngine *twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
twitterEngine setClearsCookies:YES];                        
[twitterEngine setUsesSecureConnection:NO];
[twitterEngine setConsumerKey:consumerKey secret:consumerSecret];

[twitterEngine setUsername:username password:password];
[twitterEngine sendUpdate: @"This message was sent via myApp for iOS"];

However I can't send tweet until I get accessToken. Here's output:

Request failed for connectionIdentifier = 5E7C9D2E-1467-45EF-B748-CCBF8F211F8D, error = The operation couldn’t be completed. (HTTP error 401.) ({
    body = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<hash>\n  <error>Could not authenticate you.</error>\n  <request>/1/statuses/update.xml</request>\n</hash>\n";
    response = "<NSHTTPURLResponse: 0x6e26a10>";
})

How can I sent tweet using MGTwitterEngine? (without manually getting my access token from dev.twitter.com because other users should be able to send tweets from themselves too)


Solution

  • I had a similar problem and after many hours of searching I found the solution. My logout button is showing only when the user is logged in by checking if engine isAuthorized. Then after the user taps the button this is the code which is executed.

    - (void)logoutTwitter {
    
    if(![_engine isAuthorized]){  
        UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];  
    
        if (controller){  
            [self presentModalViewController: controller animated: YES];  
        } 
    } else {
        [_engine clearAccessToken]; //This is a method called from SA_OAuthTwitterEngine.h
    

    }