I get the Malformed access token for Facebook in ios 6 - iphone

I want to fetch the facebook friends profile picture.I also give the access_token for it.
I search a lot on net but didn't got any good solution.
my code is as follow:
- (IBAction)advancedButtonPressed:(id)sender {
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
//NSString *key = #"xxxxxx";
NSString *key = #"xxxxxx";
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
NSLog(#"facebook account =%#",self.facebookAccount);
ACAccountCredential *fbCredential = [self.facebookAccount credential];
accessToken = [fbCredential oauthToken];
NSLog(#"Facebook Access Token: %#", accessToken);
[self get];
} else {
//Fail gracefully...
NSLog(#"error getting permission %#",e);
}
}];
}
-(void)fr
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends?fields=id,name,picture,first_name,last_name,gender&access_token=BAAFcRQZCZAUeUBAICacM2q1V5UzRHee6xHGnbEdu19v6CZBIEDJmTwHBKtMZBwtVuFiEeuXqt4yKeSkeI17QZBGaZCeszBfOKdbZAfR4E9RN2nFqHalKPXZBga96WQCU8CSNG4ZCJCK1V7JIbqZAPRgNl6mjjO4Ns1CEaLpbXUYtum1CXbNqTtT82YpVVKoZCmMEBpqHfwYMx1OKu9RZBsjPZA6DlhKA1uGyU32EGJ8QOQZASJVQZDZD"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error) {
if(!error)
{
list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains data: %#", list );
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
nameLabel.text = [list objectForKey:#"username"];
});
}
else{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
}
But i always got the error like this:
error = {
code = 190;
message = "Malformed access token BAAFcRQZCZAUeUBAICacM2q1V5UzRHee6xHGnbEdu19v6CZBIEDJmTwHBKtMZBwtVuFiEeuXqt4yKeSkeI17QZBGaZCeszBfOKdbZAfR4E9RN2nFqHalKPXZBga96WQCU8CSNG4ZCJCK1V7JIbqZAPRgNl6mjjO4Ns1CEaLpbXUYtum1CXbNqTtT82YpVVKoZCmMEBpqHfwYMx1OKu9RZBsjPZA6DlhKA1uGyU32EGJ8QOQZASJVQZDZD?access_token=BAAFcRQZCZAUeUBAHBZBSdTL9wWFDOVthxj78bBJlrNEkPiKHdxZA1HaRmO9dtBTJdsZCtZCu2vaE5ByZAdK7Ox30BpIR0KTg0ZC6pi1IOE0KnZCZBSxqbycG0C6Ws5Ct4ferL3G0VU1wIfDypKekFM3zB4r5gAiUREQ66Yuz2Fu2mp5NGqZCBE1p357H41P2lKOAQN9EZAmu4q3SRtjMuVIw4dtdC00l4RhMuDWTOIUQlO54bgZDZD";
type = OAuthException;
};
}
I can't able to solve this. Help me!

If you're using an SLRequest, it will auto append the access token for you, and you also should not have any request params in the URL itself. Instead, you should do something like:
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:#{#"fields":#"id,name,picture,first_name,last_name,gender"}];

You can also use this instead of using SLRequest.It is also
NSURL *meurl = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=%#",fbAccessToken]];
NSURLRequest *req = [[NSURLRequest alloc]initWithURL:meurl];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSString *userDataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];

Related

is it possible to tag a post/photo using ios social framework?

In my app I need to tag my photo/posts. Is this possible using social framework or Should I use Facebook-sdk for this?. Also can I get friends list from social framework? any help to achieve this?
Tagging a photo or post can only be done using the FacebookSDK for iOS while getting your friends list is possible using both the SocialFramework and the FacebookSDK for iOS.
You can use this code to get your friends list using the SocialFramework.
- (void)getFbFriends
{
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *facebookTypeAccount = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = #{
ACFacebookAppIdKey: facebookAppId,
ACFacebookPermissionsKey: #[#"email"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[store requestAccessToAccountsWithType:facebookTypeAccount
options:options
completion:^(BOOL granted, NSError *error){
if(granted)
{
NSArray *accounts = [store accountsWithAccountType:facebookTypeAccount];
ACAccount *facebookAccount = [accounts lastObject];
NSURL *meurl = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
merequest.account = facebookAccount;
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL parameters:#{#"fields":#"id,name,picture,first_name,last_name,gender"}];
request.account = facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error) {
if(!error)
{
NSDictionary *list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
if([list objectForKey:#"error"]!=nil)
{
// if error occured e.g. Invalid Auth etc.
}
else
{
NSMutableArray *FBFriends = [[NSMutableArray alloc] init];
[FBFriends addObject:[userInfo objectForKey:#"id"]];
NSLog(#"friends %#", list);
}
}
else
{
NSLog(#"Error");
}
}];
}
else
{
NSLog(#"Error grant access");
}
}];
}

get the facebook access token in iOS 6.0

I had implemented facebook SDK with the help of which able to get the facebook authentication as well as user info with the following code.
if(!self.accountStore)
self.accountStore = [[ACAccountStore alloc] init];
if(NSClassFromString(#"SLComposeViewController") != nil)
{
ACAccountType *facebookTypeAccount = [self.accountStore
accountTypeWithAccountTypeIdentifier:#"com.apple.facebook"];
NSLog(#"facebookTypeAccount..:%#",facebookTypeAccount);
NSArray *accounts = [self.accountStore accountsWithAccountType:facebookTypeAccount];
if (facebookTypeAccount) {
if ([accounts respondsToSelector:#selector(count)]) {
[self.accountStore requestAccessToAccountsWithType:facebookTypeAccount
options:#{ACFacebookAppIdKey:
#"key", ACFacebookPermissionsKey: #[#"email"]}
completion:^(BOOL granted, NSError
*error) {
if(granted){
NSArray *accounts = [self.accountStore
accountsWithAccountType:facebookTypeAccount];
[self fetchuserinfo];
}
}];
}
-(void)fetchuserinfo
{
NSString *accessToken = [FBSession activeSession].accessToken;
NSString *url=[NSString stringWithFormat:#"https://graph.facebook.com/me"];
NSURL *meurl = [NSURL URLWithString:url];
SLRequest *merequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:meurl
parameters:nil];
NSLog(#" setting account %#",_facebookAccount);
merequest.account = _facebookAccount;
[merequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *meDataString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
returnedData = responseData;
NSLog(#" meRequest Respnse %#", meDataString);
if (returnedData!=nil) {
if(NSClassFromString(#"NSJSONSerialization"))
{
NSError *error = nil;
id object = [NSJSONSerialization
JSONObjectWithData:returnedData
options:0
error:&error];
if(error) { }
if([object isKindOfClass:[NSDictionary class]])
{
NSDictionary *results = object;
NSString *categoryString=[[results valueForKeyPath:#"picture.data"] objectForKey:#"url"];
NSString *userid=[results objectForKey:#"id"];
if (userid != nil)
{
self.gotUserDetails = YES;
}
NSString *username=[results objectForKey:#"name"];
NSString *email=[results objectForKey:#"email"];
NSUserDefaults *userId=[NSUserDefaults standardUserDefaults];
[userId setObject:userid forKey:#"userid"];
}
}
}
}
But to post the feed (https://graph.facebook.com/me/feed/access_token=) from this login user I need access token. If anyone know how to get the access token in iOS 6.0 please help me.
Thanks to all.
Rather than worrying about getting the token and passing that with you call, Apple have provided SLRequest which you can use. You specify the target URL and parameters and SLRequest deals (transparently) with the authentication, transmission and collection of the response data.
You may not actually get the token, but you still need to get authorisation and that authorisation is linked to the list of things you want to do. Your code currently just shows that you want to get the e-mail address, but you can add other permissions:
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:
#{
ACFacebookAppIdKey : ...,
ACFacebookPermissionsKey : #[ #"email", #"read_stream", #"user_groups", #"user_videos" ]),
}
completion:^(BOOL granted, NSError *error) { ...
You need to check the Facebook documentation to find out what permissions you need to request from the user and fill them in for ACFacebookPermissionsKey.
//Try This
-(void)fetchuserinfo
{
NSString *accessToken = [FBSession activeSession].accessToken;
NSLog(#"%#",accessToken);
}
or
-(void)fetchuserinfo
{
NSLog(#"%#",FBSession.activeSession.accessToken);
}
facebook SDK 3.2 in iOS 7 & iOS 8 , it works fine for me.
You should import FacebookSDK/FacebookSDK.h
#import <FacebookSDK/FacebookSDK.h>
....
[self checkFBIDWithToken:[FBSession activeSession].accessTokenData.accessToken];
PS:"checkFBIDWithToken:(NSString *)tempToken" is a method.
facebook doc: accessToken

How to fetch Facebook friends in ios 6?

I want to send invite facebook friends from my app same as doing like in Instagram app.
But i can't find any good tutorial for that.
I able to get the name & id of the friend but I can't able to get the url for the profile image,name,etc. for the friends.
My code is as follow:
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error) {
if(!error)
{
list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains data: %#", list );
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
nameLabel.text = [list objectForKey:#"username"];
});
}
else{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
So, how can i achieve this?
This is code for it for fetching friends list
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
__block ACAccount *facebookAccount = nil;
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{
ACFacebookAppIdKey: #"add_here_your_project_FB_ID",
ACFacebookPermissionsKey: #[#"publish_stream", #"publish_actions",#"read_friendlists"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:options completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
}
else {
NSLog(#"error.localizedDescription======= %#", error.localizedDescription);
}
}];
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
//NSString *acessToken = [NSString stringWithFormat:#"%#",facebookAccount.credential.oauthToken];
//NSDictionary *parameters = #{#"access_token": acessToken};
NSDictionary *param=[NSDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,link,gender,last_name,first_name,username",#"fields", nil];
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/friends"];
SLRequest *feedRequest = [SLRequest
requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:feedURL
parameters:param];
feedRequest.account = facebookAccount;
[feedRequest performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse, NSError *error)
{
if(!error)
{
id json =[NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"Dictionary contains data: %#", json );
if([json objectForKey:#"error"]!=nil)
{
//[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
//nameLabel.text = [json objectForKey:#"username"];
});
}
else{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
I hope it helps you. Thanks
you should include this in param
[ NSMutableDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,link,gender,last_name,first_name",#"fields",nil]

upload Video to Facebook using iOS6 Social Framework

I want to publish a video file to facebook. Previously I used the Facebook iOS SDK3.0 and it works. However, for iOS6 Social Framework, there is problem.
__block ACAccount * facebookAccount;
ACAccountStore* accountStore = [[ACAccountStore alloc] init];
NSDictionary *options = #{
ACFacebookAppIdKey: #"MY APP ID",
ACFacebookPermissionsKey: #[#"publish_actions", ],
#"ACFacebookAudienceKey": ACFacebookAudienceFriends
};
ACAccountType *facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSLog(#"access to facebook account ok %#", facebookAccount.username);
NSData *videoData = [NSData dataWithContentsOfFile:[self videoFileFullPath]];
NSLog(#"video size = %d", [videoData length]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType" ,
#"Video title", #"title",
#"Video description", #"description",nil];
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:requestURL
parameters:params];
request.account = facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response,NSError * error){
NSLog(#"response = %#", response);
NSLog(#"error = %#", [error localizedDescription]);
}];
} else {
NSLog(#"access to facebook is not granted");
// extra handling here if necesary
}
}];
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSConcreteData
_fastCharacterContents]: unrecognized selector sent to instance 0x2097ead0'
Here is my research:
First, the video data cannot be part of the parameter list, since it will render the SLRequest invalid and that is the crash you are experiencing.
The video data must go in the multi part section of the request.
Now,there is a need to associate the parameters with the multipart data and that is the tricky part. So it is necessary to use the source attribute to make that link.
Source requires a URL in a string format set it in the parameters and set the same value in the filename field in the multipart request.
That should do it.
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
NSURL *videoPathURL = [[NSURL alloc]initFileURLWithPath:videoPath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:videoPath];
NSString *status = #"One step closer.";
NSDictionary *params = #{#"title":status, #"description":status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
[request addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[videoPathURL absoluteString]];
I'm working the same issue. I think your error is from ARC and NSData *videoData gets deleted before the return from performRequestWithHandler.

How to get the most updated tweet?

I am trying to post a tweet and then getting the latest tweets from the timeline and get the url of the image i just posted.
But somehow its not showing me the recent one. This is the code i am using:
-(void)shareButtonClicked:(id)sender
{
if ([TWTweetComposeViewController canSendTweet])
{
// Create account store, followed by a twitter account identifier
// At this point, twitter is the only account type available
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(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)
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
// Build a twitter request
UIImage * image = [UIImage imageNamed:#"welcomescreen-header.png"];
NSString * status = #"This is welcome screen.";
NSString * completeHandle = [NSString stringWithFormat:#"%##%#",status,twitterHandle.text];
NSData * data=[completeHandle dataUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Text:%#",completeHandle);
NSData * imageData = (UIImageJPEGRepresentation(photo.image, 90));
TWRequest *postRequest = [[TWRequest alloc] initWithURL:
[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"]
parameters:nil requestMethod:TWRequestMethodPOST];
[postRequest addMultiPartData:imageData withName:#"media" type:#"image/jpeg"];
[postRequest addMultiPartData:data withName:#"status" type:#"text"];
// Post the request
[postRequest setAccount:acct];
// Block handler to manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
NSLog(#"Twitter Response, HTTP response: %i", [urlResponse statusCode]);
if ([urlResponse statusCode] == 200) {
[self getTheUserTimeLine];
}
}];
}
}
}];
}
}
-(void)getTheUserTimeLine
{
TWRequest *postRequest = [[TWRequest alloc] initWithURL:
[NSURL URLWithString:#"https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=ashu1702&count=1"]
parameters:nil requestMethod:TWRequestMethodGET];
// Block handler to manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(#"Twitter response: %#", [dict description]);
}
else
NSLog(#"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];
}
Try using http://twitter.com/statuses/user_timeline/ashu1702.json?count=1 in your browser and see what happens. I misread your code earlier but trying this now it seems okay to me.