I have to integrate Twitter API in iPhone(4.2 and above).For this I am using SA_OAuthTwitterEngine + MGTwitterEngine classes.
I register applicaiton to www.twitter.com/apps and pass Consumer key and Consumer secret to controller my code is this.
if(!_engine){
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate:self];
_engine.consumerKey = KCONSKEY;
_engine.consumerSecret = KCONSECKEY;
}
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine:_engine delegate:self];
if (controller){
[self presentModalViewController: controller animated: YES];
}
I have seen this and this example also. In both example we can’t able to twit.. Also, in both example, I ‘m getting error:
failed with error: Error Domain=HTTP Code=401 "The operation couldn’t be completed. (HTTP error 401.)”
Can Please, any one give me suggestion how to overcome this problem?
There are changes for API, I guess the MGTwitterEngine is not updated and please do refer the developer site for more information.
http://www.readwriteweb.com/archives/twitter_changes_api_fails_to_notify_developers.php
https://dev.twitter.com/docs
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. \n%#", [NSDate date]]];
Related
I am using sharekit to upload the image on twitter.
I have set keys and callback URL perfectly.
But after entering my login and password credentials
to upload image on twitter I got following error message.
"There was a problem requesting access from Twitter."
Earlier before few months in the same app I was able to upload
the image with same code.
But right now I am facing the problem
can you tell me what is the exact problem
thanks in advance.
There is some changes occur in share kit. To resolve this issue. You have to change some piece of lines in SHKTwitter.mfile under this method:
- (void)tokenAccessModifyRequest:(OAMutableURLRequest *)oRequest
For detail info follow this link & make changes according to this link & then check:
https://github.com/SteveLeviathan/ShareKit/commit/7aab77655c1cbb1bf79092fcb3bb24dd80ab6380
UPDATE:
Replace your this method with my & then check:
- (void)tokenAccessModifyRequest:(OAMutableURLRequest *)oRequest
{
if (xAuth)
{
NSDictionary *formValues = [pendingForm formValues];
OARequestParameter *username = [[[OARequestParameter alloc] initWithName:#"x_auth_username"
value:[formValues objectForKey:#"username"]] autorelease];
OARequestParameter *password = [[[OARequestParameter alloc] initWithName:#"x_auth_password"
value:[formValues objectForKey:#"password"]] autorelease];
OARequestParameter *mode = [[[OARequestParameter alloc] initWithName:#"x_auth_mode"
value:#"client_auth"] autorelease];
[oRequest setParameters:[NSArray arrayWithObjects:username, password, mode, nil]];
}
else {
if (self.pendingAction == SHKPendingRefreshToken)
{
if (accessToken.sessionHandle != nil)
[oRequest setOAuthParameterName:#"oauth_session_handle" withValue:accessToken.sessionHandle];
}
else
[oRequest setOAuthParameterName:#"oauth_verifier" withValue:[authorizeResponseQueryVars objectForKey:#"oauth_verifier"]];
}
}
You can switch to ShareKit 2 - it is being updated frequently.
i need to implement GTMOAuth to my iOS app..for this i have downloaded the OAuth Library and write some code
- (GTMOAuthAuthentication *)myCustomAuth {
NSString *myConsumerKey = #"f964039f2d7bc82054"; // pre-registered with service
NSString *myConsumerSecret = #"c9a749c0f1e30c9246a3be7b2586434f"; // pre-assigned by service
GTMOAuthAuthentication *auth;
auth = [[[GTMOAuthAuthentication alloc] initWithSignatureMethod:kGTMOAuthSignatureMethodHMAC_SHA1
consumerKey:myConsumerKey
privateKey:myConsumerSecret] autorelease];
// setting the service name lets us inspect the auth object later to know
// what service it is for
auth.serviceProvider = #"Custom Auth Service";
return auth;
}
- (void)signInToCustomService {
NSURL *requestURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/request_token"];
NSURL *accessURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/access_token"];
NSURL *authorizeURL = [NSURL URLWithString:#"http://alpha.easyreceipts.com/api/v1/oauth/authorize"];
NSString *scope = #"http://alpha.easyreceipts.com/api/v1/";
GTMOAuthAuthentication *auth = [self myCustomAuth];
// set the callback URL to which the site should redirect, and for which
// the OAuth controller should look to determine when sign-in has
// finished or been canceled
//
// This URL does not need to be for an actual web page
[auth setCallback:#"http://alpha.easyreceipts.com/api/v1/"];
// Display the autentication view
GTMOAuthViewControllerTouch *viewController;
viewController = [[[GTMOAuthViewControllerTouch alloc] initWithScope:scope
language:nil
requestTokenURL:requestURL
authorizeTokenURL:authorizeURL
accessTokenURL:accessURL
authentication:auth
appServiceName:#"My App: Custom Service"
delegate:self
finishedSelector:#selector(viewController:finishedWithAuth:error:)] autorelease];
viewController = [self.storyboard instantiateViewControllerWithIdentifier:#"myID"];
[[self navigationController] pushViewController:viewController
animated:YES];
}
but further i don't know how to implement it.Please help me Thanks in advance
First, if you want to implement an OAuth authentication system with the GTM library, you should get this one.
You can find the complete sources of GTMOAuth here.
Secondly, you can find an example of how to use it in the git repository too. You should find everything you need to at least authenticate.
If you have any more problem, please provide more informations.
Originally I needed the ability to use the search API with twitter. I did this using Matt Gemmell's great MGTwitterEngine. That code was very very simple and looked something like this:
- (void)viewDidLoad {
[super viewDidLoad];
tweetArrays = nil;
tweetNameArray = nil;
NSString *username = #"<username>";
NSString *password = #"<password>";
NSString *consumerKey = #"<consumerKey>";
NSString *consumerSecret = #"<consumerSecret>";
// 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.
twitterEngine = [[MGTwitterEngine alloc] initWithDelegate:self];
[twitterEngine setUsesSecureConnection:NO];
[twitterEngine setConsumerKey:consumerKey secret:consumerSecret];
// This has been undepreciated for the purposes of dealing with Lists.
// At present the list API calls require you to specify a user that owns the list.
[twitterEngine setUsername:username];
[twitterEngine getSearchResultsForQuery:#"#HelloWorld" sinceID:0 startingAtPage:1 count:100];
}
This would end up calling the function:
- (void)searchResultsReceived:(NSArray *)searchResults forRequest:(NSString *)connectionIdentifier
And then I could do what I wanted with the searchResults. This required me to include the yajl library.
I then wanted to expand my code to allow users to tweet. I downloaded Ben Gottlieb's great code Twitter-OAuth-iPhone
So there's only one problem. The getSearchResultsForQuery returns a requestFailed with the following error:
Error Domain=HTTP Code=400 "The operation couldn’t be completed. (HTTP error 400.)"
To call this code I simply took the demo project in Twitter-OAuth-iPhone and added a call to getSearchResultsForQuery as seen here:
- (void) viewDidAppear: (BOOL)animated {
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 getSearchResultsForQuery:#"HelloWorld"];
// [_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
}
}
This as stated above returns a 400 error. Every other twitter API call I add here does work such as:
- (NSString *)getRepliesStartingAtPage:(int)pageNum;
Am I doing anything wrong? Or does getSearchResultsForQuery no longer work? The two code bases seem to use different versions of MGTwitterEngine, could that be causing the problem?
Thanks!
The problem is that you have to instantiate the twitter engine as an instance of SA_OAuthTwitterEngine, instead of MGTwitterEngine. When you call getSearchResultsForQuery, it uses a call to _sendRequestWithMethod to actually send the search request. SA_OAuthTwitterEngine overrides the MGTwitterEngine's implementation, but its version of that function doesn't work with getSearchResultsForQuery.
So, you need to go to getSearchResultsForQuery and make it use the MGTwitterEngine's version of the function.
I have the following steps completed in the OAuth process:
1) Request token
2) Authorize token
3) Receive PIN number
What I can't get to work is getting the access token with the PIN I receive. It always hits my accessTokenTicket:didFailWithError selector.
Here's the URL that's getting passed to it:
http://www.formspring.me/oauth/access_token?oauth_token=TOKEN_KEY_HERE&oauth_verifier=PIN_HERE
And here's the code that's being called:
- (void)successfulAuthorizationWithPin:(NSString *)pin {
NSLog(#"successfulAuthorizationWithPin:%#", pin);<br>
OAMutableURLRequest *request;<br>
OADataFetcher *fetcher;
NSURL *url = [NSURL URLWithString:kOAuthAccessTokenURL];
request = [[[OAMutableURLRequest alloc] initWithURL:url
consumer:self.consumer
token:self.accessToken
realm:nil
signatureProvider:nil] autorelease];
OARequestParameter *p0 = [[OARequestParameter alloc] initWithName:#"oauth_token" value:self.accessToken.key];
OARequestParameter *p1 = [[OARequestParameter alloc] initWithName:#"oauth_verifier"
value:pin];
NSArray *params = [NSArray arrayWithObjects:p0, p1, nil];
[request setParameters:params];
[request prepare];
NSLog(#"%#", request.URL);
fetcher = [[[OADataFetcher alloc] init] autorelease];
[fetcher fetchDataWithRequest:request
delegate:self
didFinishSelector:#selector(accessTokenTicket:didFinishWithData:)
didFailSelector:#selector(accessTokenTicket:didFailWithError:)];
[p0 release];
[p1 release];
}
And the didFail method (just an NSLog of the error) produces this error:
Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x6160c20 {NSErrorFailingURLKey=http://www.formspring.me/oauth/access_token?oauth_token=TOKEN_KEY_HERE&oauth_verifier=PIN_HERE, NSErrorFailingURLStringKey=http://www.formspring.me/oauth/access_token?oauth_token=TOKEN_KEY_HERE&oauth_verifier=PIN_HERE, NSUnderlyingError=0x61321f0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}
Am I formatting the URL wrong or supplying wrong or not enough parameters?
Thanks!
John
Did you check if the oauth token generated was correct? I would suggest starting there. Here's a good resource to check your OAuth tokens.
The message comes up if there is an authentication error. Generate the URL via the Netflix Oauth verification and run it on a browser. See if it loads then.
I'm trying to implement a custom login view to Twitter (I don't want that UIWebView).
I've downloaded many classes, and I'm so far having a nightmare with this. Now I'm trying to make Twitter + oAuth work. Here's the demo code (that works):
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
[_engine requestRequestToken];
UIViewController *controller = [SA_OAuthTwitterController controllerToEnterCredentialsWithTwitterEngine: _engine delegate: self];
if (controller)
[self presentModalViewController: controller animated: YES];
else
[_engine sendUpdate: [NSString stringWithFormat: #"Already Updated. %#", [NSDate date]]];
Now what I wanna do is replace that SA_OAuthTwitterController with custom UITextFields. So I'm trying this:
_engine = [[SA_OAuthTwitterEngine alloc] initOAuthWithDelegate: self];
_engine.consumerKey = kOAuthConsumerKey;
_engine.consumerSecret = kOAuthConsumerSecret;
[_engine requestRequestToken];
[_engine requestAccessToken];
[_engine setUsername:#"username" password:#"password"];
[_engine sendUpdate:#"tweet"];
But I keep getting error 401. I'm probably missing a step. Anyone?
The view controller you are eliminating loads a webview that prompts the user to authenticate your application with twitter. If you don't ever have the user authenticate, you won't be able to make authenticated twitter calls. There is a way to do what you are wanting, however, you have to go through all of the OAuth steps yourself. Here are the steps as specified from a different web service (Vimeo), but the same rules apply:
Your application sends a request
with your consumer key, and signed
with your consumer secret, for a
something called a request token. If
we verify your application
correctly, we'll send you back a
request token and a token secret.
You'll then create a link for the user to click on with the request token.
When the user gets to Vimeo, they'll be prompted to allow your
application access to their account.
If they click yes, we'll send them
back to your application, along with
a verifier.
You'll then use the request token, verifier, and token secret to make
another call to us to get an access
token. The access token is what
you'll use to access the user's
information on Vimeo.
OAuth is a real pain in the rump, so good luck. ;-)
I think the bit you're missing is here, SA_OAuthTwitterEngine.m:103:
//This generates a URL request that can be passed to a UIWebView. It will open a page in which the user must enter their Twitter creds to validate
- (NSURLRequest *) authorizeURLRequest {
if (!_requestToken.key && _requestToken.secret) return nil; // we need a valid request token to generate the URL
OAMutableURLRequest *request = [[[OAMutableURLRequest alloc] initWithURL: self.authorizeURL consumer: nil token: _requestToken realm: nil signatureProvider: nil] autorelease];
[request setParameters: [NSArray arrayWithObject: [[[OARequestParameter alloc] initWithName: #"oauth_token" value: _requestToken.key] autorelease]]];
return request;
}
You will have to "fake" this user login out yourself, I believe by sending twitter the login credentials as a separate request. It appears that the setUsername method you're calling is actually called as a post operation once a valid access token has been received. See SA_OAuthTwitterEngine.m:185
//
// access token callback
// when twitter sends us an access token this callback will fire
// we store it in our ivar as well as writing it to the keychain
//
- (void) setAccessToken: (OAServiceTicket *) ticket withData: (NSData *) data {
if (!ticket.didSucceed || !data) return;
NSString *dataString = [[[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding] autorelease];
if (!dataString) return;
if (self.pin.length && [dataString rangeOfString: #"oauth_verifier"].location == NSNotFound) dataString = [dataString stringByAppendingFormat: #"&oauth_verifier=%#", self.pin];
NSString *username = [self extractUsernameFromHTTPBody:dataString];
if (username.length > 0) {
[[self class] setUsername: username password: nil];
if ([_delegate respondsToSelector: #selector(storeCachedTwitterOAuthData:forUsername:)]) [(id) _delegate storeCachedTwitterOAuthData: dataString forUsername: username];
}
[_accessToken release];
_accessToken = [[OAToken alloc] initWithHTTPResponseBody:dataString];
}
So the steps are as follows:
Request request token
Fake user login to twitter and get the pin value
Set the pin on the engine
Request access token
You can see where SA_OAuthTwitterController parses the pin out of the webview content in SA_OAuthTwitterController.m:156
#pragma mark Webview Delegate stuff
- (void) webViewDidFinishLoad: (UIWebView *) webView {
NSError *error;
NSString *path = [[NSBundle mainBundle] pathForResource: #"jQueryInject" ofType: #"txt"];
NSString *dataSource = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:&error];
if (dataSource == nil) {
NSLog(#"An error occured while processing the jQueryInject file");
}
[_webView stringByEvaluatingJavaScriptFromString:dataSource]; //This line injects the jQuery to make it look better
NSString *authPin = [[_webView stringByEvaluatingJavaScriptFromString: #"document.getElementById('oauth_pin').innerHTML"] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
if (authPin.length == 0) authPin = [[_webView stringByEvaluatingJavaScriptFromString: #"document.getElementById('oauth_pin').getElementsByTagName('a')[0].innerHTML"] stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
[_activityIndicator stopAnimating];
if (authPin.length) {
[self gotPin: authPin];
}
if ([_webView isLoading] || authPin.length) {
[_webView setHidden:YES];
} else {
[_webView setHidden:NO];
}
}
hope this helps.
You have to use xAuth for custom user/pass controls. But it requires the permission from Twitter.