Objective C how to get a Facebook access token - objective-c

I'm having some trouble pulling a Facebook access token from the web for a Facebook Feed App I'm writing. The problem isn't strictly related to gaining a Facebook token; this just frames the problem. When I go to https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id=[APP_ID]&client_secret=[APP_SECRET], I am returned a token on a page that simply says:
access_token=464483653570261|cY9NHFBWCDJ9hSQfswWFg0FDZvw
How can I parse that from the webpage into my app? I'm relatively new to Objective C (and I've only got a year of basic coding experience), so I tried to use part of a method that I found online to get a JSON feed, combined with a simple parsing method, but it didn't work. The code is as follows:
id getToken = [self objectWithUrl:[NSURL URLWithString:#"https://graph.facebook.com/
oauth/access_token?grant_type=client_credentials&
client_id=464483653570261&
client_secret=55bb8395ed0293bf37af695f6cdaa1fb"]];
NSString *fullToken = (NSString *)getToken;
NSLog(#"fullToken: %#", fullToken);
NSArray *components = [fullToken componentsSeparatedByString:#"="];
NSString *token = [components objectAtIndex:1];
NSLog(#"token: %#", token);
Both of my NSLogs say that the respective Strings point to (null). I'm not really certain what I'm doing wrong, and I haven't had much luck finding answers on the internet, as I'm not sure what to call what I'm trying to do. I'd appreciate any help, or alternate methods, that you might have.

By the look of it, the value you're getting isn't JSON, it's just a string.
Try something like this:
NSURL * url = [NSURL URLWithString:#"https://graph.facebook.com/
oauth/access_token?grant_type=client_credentials&
client_id=464483653570261&
client_secret=55bb8395ed0293bf37af695f6cdaa1fb"]];
NSString * fullToken = [NSString stringWithContentsOfUrl: url];
NSLog(#"fullToken: %#", fullToken);
NSArray *components = [fullToken componentsSeparatedByString:#"="];
NSString *token = [components objectAtIndex:1];
NSLog(#"token: %#", token);

There is a more simple way of getting User's access_token using the ACAccountStore & ACAccountType. Check the Full Code Below:
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *FBOptions = [NSDictionary dictionaryWithObjectsAndKeys:FACEBOOK_APP_ID, ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[accountStore requestAccessToAccountsWithType:accountType options:FBOptions completion:
^(BOOL granted, NSError *error) {
if (granted) {
NSArray *facebookAccounts = [accountStore accountsWithAccountType:accountType];
FBAccount = [facebookAccounts firstObject];
NSLog(#"token :%#",[[FBAccount credential] oauthToken]);
} else {
NSLog(#"error getting permission %#",error);
if([error code]== ACErrorAccountNotFound){
NSLog(#"Account not found. Please setup your account in settings app");
}
else {
NSLog(#"Account access denied");
}
}
}];

Related

How can I use MailCore to fetch emails using the token I got from gmail?

I am new to IOS developement.I have use oauth 2.0 for authentication and access token.now i want to fetch the emails using token in mailcore2. how can I do it.I had google lots of stuff but it does not worth it . So,Please help to solve this problem..
Thanks in advance. Here is my code.
- (void)viewDidLoad {
[super viewDidLoad];
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSString *accessToken = [def objectForKey:#"sessionToken"];
NSLog(#"Access token:%#",accessToken);//token from google api authentication
session = [[MCOIMAPSession alloc] init];
session.hostname = #"imap.gmail.com";
session.port = 993;
session.authType =MCOAuthTypeXOAuth2;
session.OAuth2Token = accessToken;
session.username = emailId;
session.connectionType = MCOConnectionTypeTLS;
session.password = nil;
[session setConnectionLogger:^(void * connectionID, MCOConnectionLogType type,
NSData * data){
NSLog(#"MCOIMAPSession: [%i] %#", type, [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
}];
MCOIMAPMessagesRequestKind requestKind = (MCOIMAPMessagesRequestKind (MCOIMAPMessagesRequestKindHeaders | MCOIMAPMessagesRequestKindStructure |MCOIMAPMessagesRequestKindInternalDate | MCOIMAPMessagesRequestKindHeaderSubject |MCOIMAPMessagesRequestKindFlags);
MCOIMAPFolderInfoOperation *inboxFolderInfo = [session folderInfoOperation:Folder];
[inboxFolderInfo start:^(NSError *error, MCOIMAPFolderInfo *info){
NSLog(#"INFO:%#",info);
}];
}
I got INFO:(null).correct me If i am doing wrong stuff.

Sharing my ios app details on facebook along with a facebook share

I am adding share functionalities on my facebook app.Like When a "saying" is selected there is a button for sharing that "saying" on facebook.And while clicking this button I can only see the shared saying on my facebook page,there isnt any information about my ios app.How can I make everyone knows that this saying is shared through my iOS app? Please help me....
I may be a little late. Hope this helps.
You have to use the Accounts framework and the Social framework to share with your app name.
First make sure you have set up your App on Facebook correctly. Then you can use the Facebook App ID to share your posts through your app.
Here is a sample code that shows you how to use the Accounts framework with the Social Framework :
ACAccountType * facebookAccountType = [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// At first, we only ask for the basic read permission
NSArray * permissions = #[#"email"];
NSMutableDictionary *dict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"275485699289493", ACFacebookAppIdKey, permissions, ACFacebookPermissionsKey, ACFacebookAudienceOnlyMe, ACFacebookAudienceKey, nil];
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookAccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if (granted && error == nil) {
/**
* The user granted us the basic read permission.
* Now we can ask for more permissions
**/
NSArray *readPermissions = #[ #"publish_actions"];
[dict setObject:readPermissions forKey: ACFacebookPermissionsKey];
[self.accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error) {
if(granted && error == nil) {
NSDictionary *parameters = #{#"message": #"This Should Work Perfectly !! "};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/feed"];
SLRequest *feedRequest = [SLRequest
requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:feedURL
parameters:parameters];
feedRequest.account = self.facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
// Handle response
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
} else {
NSLog(#"error is: %#",[error description]);
}
}];
}

how to deactivate twitter account in iPhone app that used for Integration

I have app where I am doing the Twitter integration.
I am able to successfully tweets.
Now when I want to de-activate, I am using below.
SLRequest *postRequest1 = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST URL:
[NSURL URLWithString:#"https://api.twitter.com/1/account/end_session.json"]
parameters: [NSDictionary dictionaryWithObject:#"" forKey:#"status"]];
Problem is API with 1 is deprecated and I don't find this method in 1.1.
Is there any alternate for this?
Also what I notice is when I try to activate again, the permission is not asked. It directly send tweet. It ask tweet permission for the first time only. Not after de-activate -- Re-activate process. Is this is how Twitter behaves?
Edit 1
Code I use for all tweet is as below...
if ([self userHasAccessToTwitter]) {
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:NULL completion:^(BOOL granted, NSError *error)
{
if (granted == YES)
{
///////////////////////////////////////////////
// SEND TEXT ONLY ///
///////////////////////////////////////////////
[[NSUserDefaults standardUserDefaults] setValue:#"yes" forKey:#"twitterLogin"];
[[NSUserDefaults standardUserDefaults] synchronize];
// Populate array with all available Twitter accounts
NSString *message1 = [NSString stringWithFormat:#"Hi! I am using twitter integration."];
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
//use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
SLRequest *postRequest1 = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"http://api.twitter.com/1.1/statuses/update.json"] parameters: [NSDictionary dictionaryWithObject:message1 forKey:#"status"]];
[postRequest1 setAccount:acct];//set account
[postRequest1 performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if(error) {
NSLog(#"error == %#", error);
} else {
NSLog(#"good to go -1- %i", [urlResponse statusCode]);
}
}];
}
}
}];
}
end_session in API v1 never worked as it should anyway. Starting from 1.1 this method was removed and there's no alternative method. The user should decide if he wants to revoke your application access to his twitter account. The only thing you could do is to delete the auth_token.

How to process multiple SLRequest to get friends list in twitter?

I m using the following twitter api to get the friends list:
https://api.twitter.com/1.1/friends/list.json?
And using [SLRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) to get the response data, and perform UI Changes and model data changes in performRequestWithHandler block.
But a single request at the maximum retrieves only 20 friends.(if you set the cursor parameter in api to -1).
I can use the cursor parameter of the api to send request to get the next 20 friends and so on until the cursor value is 0.
cursor parameter can be set to the 'next_cursor' parameter in the response data of the previous request.
But i m not aware of how to call another SLRequest with in the performRequestWithHandler of the previous request, until the 'next_cursor' value in response data of previous request is 0.
Can anybody tell me how to get all the friends using SLRequest or using any other way.
Any help is appreciated.
Thank you.
u can call the next request in the request handler just after you get the response of twitter friends.
Sorry for not elaborating. I thought you would understand.
Here is the code.
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
// Sanity check
if ([arrayOfAccounts count] > 0)
{
[self postRequest];
}
}
}];
- (void)PostRequest
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"Posting video" forKey:#"status"];
// Build a twitter request
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/update.json"] parameters:tempDict];
[postRequest setAccount:acct];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Twitter response, HTTP response: %i", [urlResponse statusCode]);
NSString *output = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"%#", output);
**// calling this again and again will help you with multiple post request.**
[self postRequest]
}];
}
Similar thing can be done for friend list too.
Hope I helped.

Getting all tweets of a specific twitter account?

I just want to fetch all tweets of an specific twitter account. I want to use below url but don't know how we can get user_id or screen_name of a twitter account, whose tweets we want to fetch.
Resource URL http://api.twitter.com/1/statuses/user_timeline.format Parameters Always specify either an user_id or screen_name when requesting a user timeline.
Does any one have any idea or source code or reference. Any help will be highly appreciable.
I am using following function for getting 200 tweets but it shows in NSLog
HTTP response status: 403 message
Function
- (IBAction)followOnTwitter:(id)sender
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
// Get the list of Twitter accounts.
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
// For the sake of brevity, we'll assume there is only one Twitter account present.
// You would ideally ask the user which account they want to tweet from, if there is more than one Twitter account present.
if ([accountsArray count] > 0) {
// Grab the initial Twitter account to tweet from.
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];
[tempDict setValue:#"rohit40793982" forKey:#"screen_name"];
//[tempDict setValue:#"true" forKey:#"follow"];
// [tempDict setValue:#"683286" forKey:#"user_id "];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"http://api.twitter.com/1/statuses/user_timeline.format"]
parameters:tempDict
requestMethod:TWRequestMethodPOST];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"%#",urlResponse);
tweets = [NSJSONSerialization JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
NSLog(#"%#", output);
[self performSelectorOnMainThread:#selector(displayText:) withObject:output waitUntilDone:NO];
}];
}
}
}];
}
I am not receiving array of all tweets.
Your mistake, I think, is with this line
http://api.twitter.com/1/statuses/user_timeline.format
the ".format" is the format you want the response. For example, if you want XML, use
https://api.twitter.com/1/statuses/user_timeline.xml
or for JSON, use
https://api.twitter.com/1/statuses/user_timeline.json
You will also need to append the screen_name as a query. For example, to get all of my tweets as JSON, use
https://api.twitter.com/1/statuses/user_timeline.xml?screen_name=edent
screen_name is basically, the account name. It's the name right after the '#'. Like WOW's screen_name is #Warcraft.
Oh and in fact the .format was the problem. You have to specify one of the 3: atom, json, or xml. (I think that getting the user timeline don't allow xml return, just read the API)
As I'm a Java programmer I'm afraid I can't help any further :/