Integrate twitter to IPhone application - iphone

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

Related

MGTwitter Sessions

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.

Getting Facebook Username in iPhone App

How can I get the username once anyone is logged in to facebook through my app ?
I am using :-
FBConnect API.
My Controller.m file-
#import "FacebookPOCViewController.h"
#implementation FacebookPOCViewController
#synthesize session = _session;
#synthesize logoutButton = _logoutButton;
#synthesize loginDialog = _loginDialog;
#synthesize facebookName = _facebookName;
- (void)viewDidLoad {
//PayTai Facebook App
static NSString* kApiKey = #"230600000000";
static NSString* kApiSecret = #"----------------------";
_session = [[FBSession sessionForApplication:kApiKey secret:kApiSecret delegate:self] retain];
// Load a previous session from disk if available. Note this will call session:didLogin if a valid session exists.
[_session resume];
[super viewDidLoad];
}
- (IBAction)loginTapped:(id)sender {
//_posting = YES;
// If we're not logged in, log in first...
if (![_session isConnected]) {
self.loginDialog = nil;
_loginDialog = [[FBLoginDialog alloc] init];
[_loginDialog show];
}
// If we have a session and a name, post to the wall!
else if (_facebookName != nil) {
//[self postToWall];
printf("Session");
}
// Otherwise, we don't have a name yet, just wait for that to come through.
}
- (IBAction)logoutButtonTapped:(id)sender {
[_session logout];
}
#pragma mark FBSessionDelegate methods
- (void)session:(FBSession*)session didLogin:(FBUID)uid {
[self getFacebookName];
}
- (void)session:(FBSession*)session willLogout:(FBUID)uid {
_logoutButton.hidden = YES;
_facebookName = nil;
}
pragma mark Get Facebook Name Helper
- (void)getFacebookName {
NSString* fql = [NSString stringWithFormat:#"select uid,name from user where uid == %lld", _session.uid];
//NSLog(#"%#",_session.uid);
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
#pragma mark FBRequestDelegate methods
- (void)request:(FBRequest*)request didLoad:(id)result {
if ([request.method isEqualToString:#"facebook.fql.query"]) {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
self.facebookName = name;
_logoutButton.hidden = NO;
[_logoutButton setTitle:[NSString stringWithFormat:#"Logout as %#", name] forState:UIControlStateNormal];
//if (_posting) {
// [self postToWall];
// _posting = NO;
// }
}
}
Take a look at this. You can get almost any info of the user with the GRAPH api.
http://developers.facebook.com/docs/reference/api/user/
Example
/**
* Request the facebook name for the user
* Response will be obtained on delegate
*/
- (void) getFacebookName {
[facebook requestWithGraphPath:#"me?fields=id,name" andDelegate:self];
}
#pragma mark - FBRequestDelegate methods
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Result: %#", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:#"name"];
fb_id = [userInfo objectForKey:#"id"];
}

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");
}

iphone NSURLConnection NSTimer works in initWithRequest but causes unrecognized selector error in sendSynchronousRequest

I need to use an NSTimer to cancel my NSURLRequest before 75 seconds (the time I measured regardless of the timeout I set). I'm using the XMLRPC classes by Eric Czarny. The XMLRPCConnection is basically an image of the NSURLConnection class.
Here's the interface and the implementation file:
#import <Foundation/Foundation.h>
#class XMLRPCRequest, XMLRPCResponse;
/* XML-RPC Connecion Notifications */
extern NSString *XMLRPCRequestFailedNotification;
extern NSString *XMLRPCSentRequestNotification;
extern NSString *XMLRPCReceivedResponseNotification;
#interface XMLRPCConnection : NSObject {
NSURLConnection *_connection;
NSString *_method;
NSMutableData *_data;
id _delegate;
UIViewController* _requester;
}
#property(nonatomic, retain) NSMutableData* _data;
- (id)initWithXMLRPCRequest: (XMLRPCRequest *)request delegate: (id)delegate;
- (id)initWithXMLRPCRequest: (XMLRPCRequest *)request delegate: (id)delegate requester:(UIViewController*)requester;
- (void) timedOut;
#pragma mark -
+ (XMLRPCResponse *)sendSynchronousXMLRPCRequest: (XMLRPCRequest *)request;
#pragma mark -
- (void)cancel;
#end
#pragma mark -
#interface NSObject (XMLRPCConnectionDelegate)
- (void)connection: (XMLRPCConnection *)connection didReceiveResponse: (XMLRPCResponse *)response
forMethod: (NSString *)method;
- (void)connection: (XMLRPCConnection *)connection didFailWithError: (NSError *)error
forMethod: (NSString *)method;
#end
Implementation file:
#import "XMLRPCConnection.h"
#import "XMLRPCRequest.h"
#import "XMLRPCResponse.h"
NSString *XMLRPCRequestFailedNotification = #"XML-RPC Failed Receiving Response";
NSString *XMLRPCSentRequestNotification = #"XML-RPC Sent Request";
NSString *XMLRPCReceivedResponseNotification = #"XML-RPC Successfully Received Response";
#interface XMLRPCConnection (XMLRPCConnectionPrivate)
- (void)connection: (NSURLConnection *)connection didReceiveData: (NSData *)data;
- (void)connection: (NSURLConnection *)connection didFailWithError: (NSError *)error;
- (void)connectionDidFinishLoading: (NSURLConnection *)connection;
- (void) timedOut;
#end
#pragma mark -
#implementation XMLRPCConnection
#synthesize _data;
- (id)initWithXMLRPCRequest: (XMLRPCRequest *)request delegate: (id)delegate requester:(UIViewController*)requester {
if (self = [super init])
{
_connection = [[NSURLConnection alloc] initWithRequest: [request request] delegate: self];
_delegate = delegate;
_requester = requester;
// set the timer for timed out requests here
NSTimer* connectionTimer = [NSTimer timerWithTimeInterval:10.0f target:self selector:#selector(timedOut) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:connectionTimer forMode:NSDefaultRunLoopMode];
if (_connection != nil)
{
_method = [[NSString alloc] initWithString: [request method]];
_data = [[NSMutableData alloc] init];
[[NSNotificationCenter defaultCenter] postNotificationName:
XMLRPCSentRequestNotification object: nil];
}
else
{
if ([_delegate respondsToSelector: #selector(connection:didFailWithError:forMethod:)])
{
[_delegate connection: self didFailWithError: nil forMethod: [request method]];
}
return nil;
}
}
return self;
}
- (void) timedOut {
NSLog(#"connection timed out now!");
}
#pragma mark -
+ (XMLRPCResponse *)sendSynchronousXMLRPCRequest: (XMLRPCRequest *)request
{
NSURLResponse *urlres;
//NSHTTPURLResponse *urlres;
NSError *err = NULL;
// set the timer for timed out requests here
NSTimer* connectionTimer = [NSTimer timerWithTimeInterval:10.0f target:self selector:#selector(timedOut) userInfo:nil repeats:NO];
[[NSRunLoop currentRunLoop] addTimer:connectionTimer forMode:NSDefaultRunLoopMode];
NSData *data = [NSURLConnection sendSynchronousRequest: [request request]
returningResponse: &urlres error: &err];
if ([urlres isKindOfClass:[NSHTTPURLResponse class]]) {
NSLog(#"Received status code: %d %#", [(NSHTTPURLResponse *) urlres statusCode],
[NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *) urlres statusCode]]) ;
NSDictionary* headerFields = [(NSHTTPURLResponse*)urlres allHeaderFields];
NSArray* cookie = [NSHTTPCookie cookiesWithResponseHeaderFields:headerFields forURL:[request host]];
if ([cookie count] != 0) {
NSString* cookieName = [[cookie objectAtIndex:0] name];
NSString* cookieValue = [[cookie objectAtIndex:0] value];
NSLog(#"cookie name=value: %#=%#", cookieName, cookieValue );
[[User getInstance] setCookieID:[NSString stringWithFormat:#"%#=%#", cookieName, cookieValue] ];
} else {
NSLog(#"cookie array empty!");
}
}
// if an error occured while processing the request, this variable will be set
if( err != NULL )
{
//TODO: we may need to create a XMLRPCResponse with the error. and return
return (id) err;
}
if (data != nil)
{
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response is: %#",str);
if ( ! str ) {
str = [[NSString alloc] initWithData:data encoding:[NSString defaultCStringEncoding]];
data = [str dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
}
//Check for HTML code 400 or greater in response statusCode (from header) and throw error if so
if ([urlres isKindOfClass:[NSHTTPURLResponse class]]) {
// HTTP codes equal or higher than 400 signifies an error
if ([(NSHTTPURLResponse *) urlres statusCode] >= 400) {
// NSLog(#"Received status code: %d %#", [(NSHTTPURLResponse *) urlres statusCode],
// [NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *) urlres statusCode]]) ;
NSString *errorIntString = [NSString stringWithFormat:#"%d", [(NSHTTPURLResponse *) urlres statusCode]];
NSString *stringForStatusCode = [NSHTTPURLResponse localizedStringForStatusCode:[(NSHTTPURLResponse *) urlres statusCode]];
NSString *errorString = [[errorIntString stringByAppendingString:#" "] stringByAppendingString:stringForStatusCode];
NSInteger code = -1; //This is not significant, just a number with no meaning
NSDictionary *usrInfo = [NSDictionary dictionaryWithObject:errorString forKey:NSLocalizedDescriptionKey];
err = [NSError errorWithDomain:#"org.wordpress.iphone" code:code userInfo:usrInfo];
return (id) err;
}
}
//[str release];
return [[[XMLRPCResponse alloc] initWithData: data] autorelease];
}
return nil;
}
#pragma mark -
- (void)cancel
{
[_connection cancel];
[_connection autorelease];
}
#pragma mark -
- (void)dealloc
{
[_method autorelease];
[_data autorelease];
[super dealloc];
}
#end
#pragma mark -
#implementation XMLRPCConnection (XMLRPCConnectionPrivate)
....
#end
The timer set in the initWithXMLRPCRequest method works fine, but if it's set in the sendSycnhronousXMLRPCRequest method, I get the following error:
2010-01-29 11:36:40.442 ActiveE[1071:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[XMLRPCConnection timedOut]: unrecognized selector sent to class 0x32610'
2010-01-29 11:36:40.443 ActiveE[1071:207] Stack: (
31044699,
2497855305,
31426811,
30996086,
30848706,
609709,
30829248,
30825544,
39135117,
39135314,
3100675
)
I don't understand, I did declare the timeOut method in the implementation file?
I think your timedOut method should be a public one. Not hidden in a category with private methods.
The method that the timer calls has to be of the form:
- (void)timerFireMethod:(NSTimer*)theTimer;
The name is arbitrary but you must return void and must accept a timer. I suspect that is the source of your error. In any case, you should change it to the standard form.