MGTwitter Sessions - iphone

I am using the MGTwitterEngine+Oauth library to integrate Twitter into my iPhone app. Using the below included code I am able to allow users to log into twitter.
if(_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = #"XXXXXX";
_engine.consumerSecret = #"XXXXXXXXX";
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
{
[self presentModalViewController: controller animated: YES];
}
I also have the following delegate methods for handling the callback.
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark SA_OAuthTwitterController Delegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenticated with user %#", username);
//tweets = [[NSMutableArray alloc] init];
[self updateStream:nil];
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failure");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled");
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
the users are able to tweet using the following code:
[_engine sendUpdate:#"Tweet"];
This all seems pretty standard but for some reason if I try to create another engine from another class or for a returning user, the user is forced to relogin in order to create a usable engine. What am I missing?

The code is right. You have created the new instance so it is asking for the authentication.

Related

NSUserDefaults remember view

My App contains a couple of views, I would like to display a small setup when the app launches and the user didn't complete the wizard yet.
I know I can achieve this with NSUserDefaults, But I'm unsure how I can make it to display a specific view depending on the input string of the NSUserDefaults storage.
My AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:#"WIZARD_VIEW"];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
UIViewController *controller = [[controllerClass alloc] init];
// Override point for customization after application launch.
return YES;
}
Then in the viewcontroller files I added the following code as suggestion from jfaller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: #{ #"WIZARD_VIEW" : [[self class]description]} ]; [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
NSUserDefaults* standard=[NSUserDefaults standardUserDefaults];
[standard registerDefaults: #{ #"WIZARD_VIEW" : [[self class]description]} ];
[[NSUserDefaults standardUserDefaults] synchronize];
}
But how can I make this so it will display the specific view that has been selected in the setup?
Personally, I would do the following:
Every time a user goes to a new view in your wizard, record the UIViewController in the user defaults:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[NSUserDefaults standardUserDefaults] setObject:[[self class] description] forKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:WIZARD_VIEW];
[[NSUserDefault standardUserDefaults] synchronize];
}
When the user restarts the app (hypothetically in the middle of the wizard), reload the view:
- (BOOL)application:(UIApplication *)application
willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// etc.
NSString *controllerName = [[NSUserDefaults standardUserDefaults] objectForKey:WIZARD_VIEW];
if ([controllerName length]) {
Class controllerClass = NSClassFromString(controllerName);
NSViewController *controller = [[controllerClass alloc] init];
// push the controller, or whatever....
}
// etc.
}
Write the view you are on to NSUserDefaults as the view loads. Then check for the value in didFinishLaunchingWithOptions.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
if ([[[NSUserDefaults standardUserDefaults] valueForKey:#"current_setup"] isEqualToString:#"1"]) {
//on view 1!
}
}

NSUserDefaults doubts in iphone SDK

I am integrating twitter in my app for sharing a text. My architecture of twitter integration is I have two Button _btnTwitter and _btntwitteLogout and when the user successfully login the twitter his name will display in _btntwitterLogout as title.
When the user tap the _btntwitterLogout it logs out the twitter and logout button hides and login button comes.every thing went ok.but when the user tap the login button(_btnTwitter) the Twitter login popup cmes for login purpose,here is the problem that am facing ,when the popup comes the user tap the cancel button of that popup the popup disappears and here the previous username of the user in the logout button.it didn't changes. I have put user defaults to check.
-(IBAction)_clickbtnTwitter:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:YES forKey:#"Twitter_logged"];
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = NO;
_btnTwitter.hidden=YES;
if (_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
}
}
}
then logout code
-(IBAction)_clickbtntwitterlogeout:(id)sender
{
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btntwitterLogeout.hidden = YES;
_btnTwitter.hidden=NO;
_btnTwittermain.enabled = NO;
[_engine clearAccessToken];
[_engine clearsCookies];
[_engine setClearsCookies:YES];
[[NSUserDefaults standardUserDefaults] removeObjectForKey:#"authData"];
[[NSUserDefaults standardUserDefaults]removeObjectForKey:#"authName"];
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authName"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"authData"]);
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:#"Twitter_logged"];
[_engine release];
_engine=nil;
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];
}
}
}
in viewwillappear
BOOL logged = [[NSUserDefaults standardUserDefaults] boolForKey:#"Twitter_logged"];
;
if (logged == YES) {
_btnTwitter. hidden = YES;
_btntwitterLogeout.hidden = NO;
crosstwitterimage.hidden = NO;
_btnTwittermain.enabled =YES;
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
//Checks if there is a saved User Name
if([defaults objectForKey:#"kTwitterUserName"])
{
NSString *username = [defaults objectForKey:#"kTwitterUserName"];
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
crosstwitterimage.hidden = NO;
}
}
else
{
_btnTwitter. hidden = NO;
crosstwitterimage.hidden = YES;
[_btntwitterLogeout setTitle:nil forState:UIControlStateNormal];
_btnTwittermain.enabled =NO;
crosstwitterimage.hidden = YES;
}
but when i tap the cancel button in loginwindow of twitter,an comes back the username with the logout button shows ,if the user is already logedout from twitter.
is there any problem in my code.
thanks in advance.
EDIT
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults synchronize];
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failed!");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled.");
}
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
NSLog(#"Request %# succeeded", requestIdentifier);
}
- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
NSLog(#"Request %# failed with error: %#", requestIdentifier, error);
}
Yes there is a problem. Whenever you hit the _btnTwitter, you are setting the Twitter_logged to yes. That's not correct. You should only set it to yes when there is a successful login. That is when the user has NOT hit cancel on the twitter login window.
In other words, you need to set the Twitter_logged to YES once the user has actually logged in, not when the user clicked on the button _btnTwitter
Seems like SA_OAuthTwitterController has a delegate property pointing to self. You should handle code to set Twitter_logged YES in that delegate method.
Hope that helps.
Edit:
Given the latest code here is where you should add the NsUserDefaults data
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenicated for %#", username);
[_btntwitterLogeout setTitle:username forState:UIControlStateNormal];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:username forKey:#"kTwitterUserName"];
[defaults setBool:YES forKey:#"Twitter_logged"]; // Right here - mbh
[defaults synchronize];
}

Integrate twitter to IPhone application

I am hoping to integrate Twitter to my application. My project is created with ARC support. When i added the Twitter framework i also flagged the .m files with -fno-objc-arc.
I could login to twitter (meaning, the authentication process works), and after the authentication that application crashes when i click the tweet button.
1.) This is what gets called first, twitter authentication works fine.
-(void)loginTwitterUser{
if(_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = #"xxxxxx";
_engine.consumerSecret = #"xxxxxx";
if (![_engine isAuthorized]) {
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
if (controller) {
[self presentModalViewController:controller animated:YES];
}
}
_engine - i have declared this is the .h file, but did not synthesize it in the .m
This is where we are going to tweet
-(void)tweetThis:(id)sender{
[_engine sendUpdate:#"Tweet something"];
}
3.) other delagate methods
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark TwitterEngineDelegate
- (void) requestSucceeded: (NSString *) requestIdentifier {
NSLog(#"Request %# succeeded", requestIdentifier);
}
- (void) requestFailed: (NSString *) requestIdentifier withError: (NSError *) error {
NSLog(#"Request %# failed with error: %#", requestIdentifier, error);
}
#pragma mark SA_OAuthTwitterController Delegate
In the NSLog username is null. Why is this ?
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenticated with user %#", username);
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failure");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled");
}
The application crashes in the MGTwitterEngine.m at the return statement.
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
How can i resolve this ?
Check your SA_OAuthTwitterEngine.m and try to implement the changes below. You should change http to https.
- (SA_OAuthTwitterEngine *) initOAuthWithDelegate: (NSObject *) delegate {
if (self = (id) [super initWithDelegate: delegate])
{
self.requestTokenURL = [NSURL URLWithString: #"https://twitter.com/oauth/request_token"];
self.accessTokenURL = [NSURL URLWithString: #"https://twitter.com/oauth/access_token"];
self.authorizeURL = [NSURL URLWithString: #"https://twitter.com/oauth/authorize"];
}
return self;
}
There's no reason for you to do that, twitter integration has been optimized.
Check this link http://www.raywenderlich.com/5519/beginning-twitter-in-ios-5

IOS : SA_OAuthTwitterController callback after authorization

I m using for the first time the twitter rush exemple to handle posts on twitter , all goes well excepts I want to post the message immedialy after the autorization , and I dont know how to make a callback after autorization
if(!_engine){
NSLog(#"init SA_OAuthTwitterEngine");
_engine = [[[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self] retain];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
}
if(![_engine isAuthorized]){
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
if (controller){
[self presentModalViewController: controller animated: YES];
}
}
Here are the callbacks , but I dont know how to access _engine inside it :
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSLog(#"storeCachedTwitterOAuthData");
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
NSLog(#"cachedTwitterOAuth");
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
Can be done with this delagate:
#pragma mark SA_OAuthTwitterControllerDelegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username{
}

Twitter not working

i used MGTwitterEngine and its not working the application crashes after successful login attempt please help me
here is my code #Yorxxx
I just use the MGTwitterEngine:
following are the website i take the tutorial for help but its not working :(
#pragma mark twitter
- (void) twitterAction{
if(_engine) return;
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = #"pDFl6Og4Uwq2qEoJaOiuw";
_engine.consumerSecret = #"p3gxIDewgK3nxueJIRKPoSoFEpp8RtIryglvOrwSQA";
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else {
tweets = [[NSMutableArray alloc] init];
[self updateStream:nil];
}
}
-(IBAction)updateStream:(id)sender {
[_engine getFollowedTimelineSinceID:1 startingAtPage:1 count:100];
}
-(IBAction)tweet:(id)sender {
[_engine sendUpdate:#"Testing Testing Testing ... Please Wait"];
[self updateStream:nil];
}
#pragma mark SA_OAuthTwitterEngineDelegate
- (void) storeCachedTwitterOAuthData: (NSString *) data forUsername: (NSString *) username {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject: data forKey: #"authData"];
[defaults synchronize];
}
- (NSString *) cachedTwitterOAuthDataForUsername: (NSString *) username {
return [[NSUserDefaults standardUserDefaults] objectForKey: #"authData"];
}
#pragma mark SA_OAuthTwitterController Delegate
- (void) OAuthTwitterController: (SA_OAuthTwitterController *) controller authenticatedWithUsername: (NSString *) username {
NSLog(#"Authenticated with user %#", username);
tweets = [[NSMutableArray alloc] init];
[self updateStream:nil];
}
- (void) OAuthTwitterControllerFailed: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Failure");
}
- (void) OAuthTwitterControllerCanceled: (SA_OAuthTwitterController *) controller {
NSLog(#"Authentication Canceled");
}