How to get Token using Twitter API 1.1 in iOS - ios

I am using "STTwitter" for getting token from below URL and request body
https://dev.twitter.com/docs/api/1.1/post/oauth2/token
request body code with URL is below
- (void)verifyCredentialsWithSuccessBlock:(void(^)(NSString *username))successBlock errorBlock:(void(^)(NSError *error))errorBlock {
[self postResource:#"oauth2/token"
baseURLString:#"https://api.twitter.com"
parameters:#{ #"grant_type" : #"client_credentials" }
useBasicAuth:YES
uploadProgressBlock:nil
downloadProgressBlock:nil
successBlock:^(id request, NSDictionary *requestHeaders, NSDictionary *responseHeaders, id json) {
NSString *tokenType = [json valueForKey:#"token_type"];
if([tokenType isEqualToString:#"bearer"] == NO) {
NSError *error = [NSError errorWithDomain:NSStringFromClass([self class]) code:STTwitterAppOnlyCannotFindBearerTokenInResponse userInfo:#{NSLocalizedDescriptionKey : #"Cannot find bearer token in server response"}];
errorBlock(error);
return;
}
self.bearerToken = [json valueForKey:#"access_token"];
successBlock(_bearerToken);
} errorBlock:^(id request, NSDictionary *requestHeaders, NSDictionary *responseHeaders, NSError *error) {
errorBlock(error);
NSLog(#"ERROR %#",[error description]);
}];
}
For Calling above method i am doing below code
STTwitterAppOnly *twitter1 = [[STTwitterAppOnly alloc] init];
[twitter1 verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
NSLog(#"sd");
[self.twitter getUserTimelineWithScreenName:#"SEREEN_NAME"
successBlock:^(NSArray *statuses) {
NSLog(#"ERROR ::: %#",[statuses description]);
// ...
} errorBlock:^(NSError *error) {
// ...
}];
} errorBlock:^(NSError *error) {
// ...
}];
I got below Error when perform above code...
**Error Domain=STHTTPRequest Code=99 "Unable to verify your credentials"**
Can you suggest me what I missed in my code?
My concern is that, I want to read twitter feed without login in Twitter.Only using "Consumer Key" and "Secret Key" with Twitter API V1.1.
Thanks

if you have ConsumerKey and ConsumerSecret you can try it
STTwitterAPIWrapper *twitterAPI = [[STTwitterAPIWrapper twitterAPIApplicationOnlyWithConsumerKey:#"Your Consumer Key" consumerSecret:#"Your Consumer Secret"] autorelease];
[twitterAPI verifyCredentialsWithSuccessBlock:^(NSString *username) {
[twitterAPI getUserTimelineWithScreenName:#"your ScreenName" count:25 successBlock:^(NSArray *statuses) {
NSLog(#"Success:%#", statuses);
} errorBlock:^(NSError *error){
NSLog(#"Error : %#",error.description);
}];
} errorBlock:^(NSError *error) {
NSLog(#"Error : %#",error.description);
}];

Verify that you have enter Consumer key and Consumer Secret in both plist and header prefix...

The code you posted has several issues. First, you're making a request from the verify method error block instead of the success block. Second, you're using the postResource method directly, instead of the higher level one to do what you want.
If all that you want is a bearer token for your consumer tokens, you can just copy / paste the sample code from STTwitter README in the App Only Authentication section.

Related

Integrate Office-365-SDK-for-iOS

I am creating an iOS application in which I am integrating Office-365-SDK-for-iOS for import contacts from outlook365.I am successfully able to authenticate with Microsoft Azure. But when I am fetching user and user's contacts then following error is coming-
Error Domain=Error in the Request Code=401 "The operation couldn’t be completed. (Error in the Request error 401.)
Here is my code for authentication and get client
//Acquire access and refresh tokens from Azure AD for the user.
-(void)acquireAuthTokenWithResourceId:(NSString *)resourceId completionHandler:(void (^)(BOOL authenticated))completionBlock
{
ADAuthenticationError *error;
self.authContext = [ADAuthenticationContext authenticationContextWithAuthority:OutlookAuthority error:&error];
[self.authContext acquireTokenWithResource:OutlookRsourceId
clientId:OutlookClientId
redirectUri:[NSURL URLWithString:OutlookRedirectUrl]
completionBlock:^(ADAuthenticationResult *result)
{
if (AD_SUCCEEDED != result.status)
{
completionBlock(NO);
}
else
{
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:result.tokenCacheStoreItem.userInformation.userId
forKey:#"LogInUser"];
[userDefaults synchronize];
self.dependencyResolver = [[ADALDependencyResolver alloc] initWithContext:self.authContext
resourceId:OutlookRsourceId
clientId:OutlookClientId
redirectUri:[NSURL URLWithString:OutlookRedirectUrl]];
completionBlock(YES);
}
}];
}
- (void) getClient:(void (^) (MSOutlookServicesClient *))callback
{
OutlookAuthManager* authenticationController = [OutlookAuthManager sharedInstance];
[authenticationController acquireAuthTokenWithResourceId:OutlookRsourceId completionHandler:^(BOOL authenticated)
{
if (authenticated)
{
callback([[MSOutlookServicesClient alloc] initWithUrl:#"https://outlook.office365.com/api/v1.0" dependencyResolver:[authenticationController dependencyResolver]]);
}
else
{
NSLog(#"Error in authentication");
}
}];
}
And following I am getting user-
[[OutlookAuthManager sharedInstance] getClient:^(MSOutlookServicesClient *client)
{
NSURLSessionTask* task = [[client getMe] readWithCallback:^(MSOutlookServicesUser *user, NSError *error)
{
if(error == nil)
{
dispatch_async(dispatch_get_main_queue(),
^{
NSLog(#"------>%#",user.DisplayName);
NSLog(#"------>%#",user.Alias);
NSLog(#"------>%#",user.Id);
NSLog(#"------>%#",user.MailboxGuid);
});
}
else
{
[client.resolver.logger logMessage:error.description withLevel:LOG_LEVEL_ERROR];
}
}];
[task resume];
}];
But That error is coming here.
Please help me
Thanks
Start by validating your access token. Since it's a 401 it's likely a problem there.

Simple twitter timeline iOS (only read tweets for no register user)

I want a twitter timeline to be displayed in a View, without the user having to put your twitter account, simplemete read the tweets and hashtag, of the accounts that I have selected during the programming of the app.
Is it possible? Where do I can find info for this?
All I see includes login in twitter.
Thank you.
You can use STTwitterAPIWrapper
Firstly using Twitter you must create an app , because you must use key and secret of your app in the code.
For example :
STTwitterAPIWrapper *twitter = [STTwitterAPIWrapper twitterAPIApplicationOnlyWithConsumerKey:YourTwitterConsumerKey
consumerSecret:YourTwitterConsumerSecret];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *username)
{
NSDictionary *parameters = #{#"q" : #"anyHashTag", #"result_type": #"recent", #"count": #"100"};
[twitter getSearchTweetsWithQuery:parameters successBlock:^(NSDictionary *searchMetadata, NSArray *statuses, NSString *refreshUrl) {
_refreshUrl = refreshUrl;
[self parseJSONString:statuses];
} errorBlock:^(NSError *error) {
//NSLog(#"-- error: %#", error);
}];
} errorBlock:^(NSError *error) {
//NSLog(#"--** error %#", error);
}];

Google + AFOAuth2Client

I'm trying to login on Google + through AFOAuth2Client (AFNetworking extension).
I wrote this code :
NSURL *url = [NSURL URLWithString:#"https://accounts.google.com/"];
AFOAuth2Client *oauthClient = [AFOAuth2Client clientWithBaseURL:url clientID:#"MY_ID" secret:#"MY_SECRET"];
[oauthClient authenticateUsingOAuthWithPath:#"/o/oauth2/token"
parameters:#{#"scope": #"https://www.googleapis.com/auth/plus.me", #"response_type" : #"code", #"redirect_uri" : #"https://www.domain.com/oauth2callback"}
success:^(AFOAuthCredential *credential) {
NSLog(#"I have a token! %#", credential.accessToken);
} failure:^(NSError *error) {
NSLog(#"Error: %#", error);
}];
But the error block is called with an invalid_request (Error 400).
Am I missing something? (A missing parameter?)
Please Look into the OAuth2 Doc carefully, The Parameters in your code is wrong. scope should be openid or email, and there're other parameters missing.

STTwitter Library returns an error when getting tweets list for keyword with special characters

I want to get tweets list using Twitter Search API. But Recently twitter has launched New version-1.1 and it requires authorization. I'm using STTwitter library for interacting with Twitter API.
I'm using STTwitter_ios project which you can find from here :
https://github.com/nst/STTwitter/tree/master/ios
Now, I have written one sample function: fetchTweets. Authorization works successful and I'm getting the list if i search for the word (Without spaces or special characters). But When I try to search keyword with spaces or Special characters like "New york", #"New or York", etc.. then it returns error :
In the method ,
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
I'm getting error :
{"errors":[{"message":"Could not authenticate you","code":32}]}
- (void) fetchTweets {
STTwitterAPIWrapper *twitter = [STTwitterAPIWrapper twitterAPIWithOAuthConsumerName:OAUTH_CONSUMER_NAME consumerKey:OAUTH_CONSUMER_KEY consumerSecret:OAUTH_CONSUMER_SECRET oauthToken:OAUTH_TOKEN oauthTokenSecret:OAUTH_SECRET_TOKEN];
NSString *query = #"New york";
NSString *searchQuery = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[twitter getSearchTweetsWithQuery:searchQuery successBlock:^(NSDictionary *searchMetadata, NSArray *statuses) {
NSLog(#"Search data : %#",searchMetadata);
NSLog(#"\n\n Status : %#",statuses);
} errorBlock:^(NSError *error) {
NSLog(#"Error : %#",error);
}];
}
Any help or suggestions will be appreciated !
Thanks !
Finally, I removed OAuth token and it works fine !
See code below :
STTwitterAPIWrapper *twitter = [STTwitterAPIWrapper twitterAPIApplicationOnlyWithConsumerKey:OAUTH_CONSUMER_KEY consumerSecret:OAUTH_CONSUMER_SECRET];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *username) {
[twitter getSearchTweetsWithQuery:searchQuery successBlock:^(NSDictionary *searchMetadata, NSArray *statuses) {
NSLog(#"Search data : %#",searchMetadata);
NSLog(#"\n\n Status : %#",statuses);
} errorBlock:^(NSError *error) {
NSLog(#"Error : %#",error);
}];
} errorBlock:^(NSError *error) {
NSLog(#"-- error %#", error);
}];
I am Nicolas Seriot the creator of STTwitter.
The issue you encountered was a bug and I just fixed it.
Try to add HTML encode the keywords. For example with
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

Posting image with caption with Facebook IOS SDK 3.1 and Graph API

I'm new to facebook SDK.
Last time I used facebook IOS SDK 3.0 and posting image through graph API. It is working but now it's not. I upgraded to 3.1 but still, it always return HTTP ERROR 200. Is there anyone can help me?
this is the code
- (void) facebookPostPhoto:(UIImage *)photo withMessage:(NSString *)msg withOkAction:(SEL)okAction andNGAction:(SEL)ngAction withTarget:(id)target {
ok = okAction;
ng = ngAction;
curView = target;
NSMutableDictionary *params;
params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
UIImageJPEGRepresentation(photo, 90), #"source",
msg, #"message",
nil];
if ([FBSession.activeSession.permissions indexOfObject:FacebookPermission_3] == NSNotFound) {
NSLog(#"permission not found");
// No permissions found in session, ask for it
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObjects:FacebookPermission_1, FacebookPermission_3, nil] defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error)
{
// If permissions granted, publish the story
if (!error) [self initPostFacebookWithParams:params];
}];
} else {
[self initPostFacebookWithParams:params];
} }
- (void)initPostFacebookWithParams:(NSMutableDictionary *)params {
[FBRequestConnection startWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"ERROR : %#", error.localizedDescription);
if (!error) {
NSLog(#"Facebook Post Success..");
if (ok && curView) {
[curView performSelector:ok];
}
} else {
NSLog(#"Facebook Post Failed..");
if (ng && curView) {
[curView performSelector:ng withObject:error];
}
}
}]; }
I appreciate your fast response and help! Thank You!!
I think it's either facebook upload's server is down or there is a new policy about image size. When I down sized the image to 320x320 it returns no error, sometimes error too by the way.
So for those who see this question, try to resize your image to smaller size.

Resources