Unable to Like a post from ios sdk - ios

i am using Facebook SDK 3.0 to login user and i am successfully getting its FB id and FB session token.
`NSDictionary<FBGraphUser> *user.id` (FB ID)
and
[FBSession.activeSession accessToken] (FB session token)
Now i want to like a post inside my app. SO i am creating a POST request and passing the parameters like this
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/og.likes",#"34856345..."]] cachePolicy:NO timeoutInterval:5.0];
[urlRequest addValue:#"BAAGjjgD8bhUBAM73jzkpy23zlHo7e8ZAqPaOGvbxU..." forHTTPHeaderField:#"access_token"];
[urlRequest addValue:myshareLink forHTTPHeaderField:#"object"];
[urlRequest setHTTPMethod:#"POST"];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
[theConnection autorelease];
but i am getting this error
result:{"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104}}
but if i use the same access token and user id from CURL command it posts successfully.
curl -X POST -F 'access_token=BAAGjjgD8bhUBAE8XmogjJZAZAPyJ8SUyxkllJQ...' -F 'object=http://xyz.com/abc/gallery.php#pic/pic2/' https://graph.facebook.com/732../og.likes
Please some help me figure it out what i am missing.
Thanks

I would recommend using the FBRequestConnection and FBRequest class found in the iOS Facebook SDK rather than using NSURLConnection and NSMutableURLRequest. I believe Facebook requires some extra header values at the iOS level that the Facebook SDK automatically generates for you.
For a like action, I used the FBRequest class method requestForGraphPath to create the request. Don't forget to set the httpMethod and session fields on your FBRequest before passing it to a FBRequestConnection.

Related

oAuth2 authentication of server API using NSURLSessions in ios

Kindly bear with me if you find this question similar or not clear to the complete context, posting my first question, so I'll improve over as I get used to it.
I have tried to search for similar problem statements to find close solution.
I have client id, secret, redirect URL given by my web server so that it can authenticate its API for usage using oauth2 authentication. So before using any of its web services, in the beginning client has to do an authorize-token handshake to receive a token to be supplied to API call.
In my IOS client application creating a NSURL with that like:
NSString* urlString = [NSString stringWithFormat:#"%#/oauth/authorize/?client_id=%#&response_type=code&redirect_uri=%#",myServerHostName, myAppClientId,myServerRedirectHostname];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"utf-8" forHTTPHeaderField:#"charset"];
[request setHTTPMethod:#"POST"];
Creating a NSURLSession and NSURLSessionDataTask with appropriate parameters with above NSURLRequest:
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request];
[postDataTask resume];
And have created a delegate redirect handler so I could grab the new redirect URL like:
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionDataTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)newRequest completionHandler:(void (^)(NSURLRequest *))completionHandler {
//Doing stuff : Grab the new redirected URL to get the oauth2 code. from the URL.
}
Can this be a legitimate way of performing the oauth2 for authenticating API before their access/usage ?
Currently my server fails with throwing 500 as it gets the above request.
Completed 500 Internal Server Error in 14ms
NameError (undefined local variable or method `login_path' for #<Doorkeeper::AuthorizationsController:0x000001078c1560>)
But when I try this through the web : example using 'Advanced REST client', the client receives the redirect URL( with status code 302) successfully.
Figured it out later that the sending out request was absolutely correct, the server side was using the door-keeper gem implementation which intern redirected to signup link for authentication, as the redirection was failing hence the error 500 was being received. Such oauth2 authentication of any API cannot be done without the ideal user accounts.

Authentication Issue with REST call for iOS

I am currently trying to make a REST call from an iOS device. My code is below
NSString *restCallString = [NSString stringWithFormat:#"MyURL"];
NSURL *url = [NSURL URLWithString:restCallString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:#"GET"];
[request addValue:Value1 forHTTPHeaderField:#"Header1"];
[request addValue:Value2 forHTTPHeaderField:#"Header2"];
[request setURL:[NSURL URLWithString:restCallString]];
#try{
_currentConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
#catch(NSError *e){
NSLog(#"%#", e.description);
}
Whenever this is called, I get the following error: Authentication credentials were not provided. However, what confuses me is that if I send an identical GET request via a HTTP web console, it works perfectly. In other words, using the same URL and the same 2 header-value pairs, I get a valid response on a web console, and see no authentication errors. What could be causing this?
You are setting the HTTP headers. This won't work, because the HTTP header is not contained in $_GET or $_POST because they're are not content, but description of the content expected.
Try this instead:
NSURL *url = [NSURL URLWithString:[restCallString stringByAppendingFormat:#"?Header1=%#&Header2=%#", Value1, Value2]];
Of cause you have to be aware that the URL is RFC 1738 compliant.
if I send an identical GET request via a HTTP web console, it works perfectly
I suspect your web console is leveraging SessionAuthentication — i.e. If you're already logged in to your site in your browser the API will authenticate you based on your session cookie.
Django Rest Framework provides various authentication methods and there are third-party options too. The simplest to get going is probably the provided Token Auth method.
Make sure this is enabled. Create a token in the admin (or via the provided view) and make sure you've set the Authorization header. It needs to look like this:
Authorization: Token 9944b09199c62bcf9418ad846dd0e4bbdfc6ee4b
So your Objective-C will go something like:
[request addValue:[NSString stringWithFormat:#"Token %#", yourToken]
forHTTPHeaderField:#"Authorization"];
Hopefully that gets you started.

Disqus Password Credentials OAuth

I'm trying to authenticate a user in my iOS app but all I get is a 400 error.
According to the documentation, "this type of flow is restricted to approved applications only, so you must request access first".
So how do I approve my application to be able to accomplish this flow?
Part of my request:
NSURL *url = [NSURL URLWithString:#"https://disqus.com/api/oauth/2.0/access_token/"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:WS_TIMEOUT];
NSString *strAuth = [NSString stringWithFormat:#"%#:%#", username, password];
NSString *strAuthBase64 = [[strAuth dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *postString = [NSString stringWithFormat#"grant_type=password&client_secret=%#&client_id=%#&scope=read,write", DISQUS_SECRET, DISQUS_KEY];
[request addValue:[NSString stringWithFormat:#"Basic %#", strAuthBase64] forHTTPHeaderField:#"Authorization"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
Thanks in advance.
This is something we'd have to enable for your application from our end. However, I'd instead recommend hosting a page to handle the authentication with the standard server-side flow. You can then pull the access token and other variables from the page into your application after the user has authorized.
The reason is so you don't have to deal with form validation, error messaging, and can take advantage of our updates to the form without touching your code.
Some server-side OAuth examples in PHP and Python can be found on this page: https://github.com/disqus/DISQUS-API-Recipes/tree/master/oauth
Try this library which solves Disqus authorization issue in a slick manner. Really nice solution https://github.com/moqod/disqus-ios

Fetching Facebook Open Graph Data via NSURLRequest

How can I retrieve data from the Graph API using NSMutableURLRequest?
I already have a valid access token and I need to fetch basic user information such as birthday, ID, picture or first/last name.
In the accounts framework you can create a request with parameters using + requestForServiceType:requestMethod:URL:parameters: so I just tried - setValue:forHTTPHeaderField: but it doesn't seem to work...
As long as I write all the necessary attributes in the request URL it works fine. Maybe there is a request URL scheme I can use or any other way to submit the attributes needed to perform the request.
Thanks in advance
You can create a simple GET request and include the access_token like this. You can insert the ACCESS_TOKEN using [NSString stringWithFormat:]
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me?access_token=ACCESS_TOKEN&fields=id,name,birthday"]]];

Posting picture on Facebook 'feed' from an iPhone app

I am using ASIHTTPRequest to work on Facebook graph API.
This is the nearest I have gone to posting a picture on the feed. So if I have a
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
The url is https://graph.facebook.com/me/feed
Now to post a picture I do the following:
[request setPostValue:#"My Message" forKey:#"message"];
[request setPostValue:#"somepic.png" forKey:#"picture"];
[request setPostValue:#"Some Name" forKey:#"name"];
[request setPostValue:#"Some description" forKey:#"description];
[request startAsynchronous];
If you try this then everything works fine other than the picture being posted. A blank placeholder for the picture is though show on the feed.
Just use this small snippet to upload a image on your disk as raw data
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setData:UIImageJPEGRepresentation(img.image, 0.1) withFileName:filename andContentType:#"image/jpeg" forKey:#"photo"];
I found out this documentation on facebook: http://developers.facebook.com/docs/reference/api/post
According to this documentation we can not post an image residing on our machine using the api. Instead we have to upload the pic and then provide the link for posting to the feed.
But uploading an image on to the wall is allowed if you logon to facebook.com. I believe this functionality is not provided in the graph api.
It might be worth taking a look at ShareKit - http://www.getsharekit.com/
Their demo app publishes a photo on the Facebook wall successfully. I believe they wrap the upload-then-publish process in their code.
HTH,
Oded

Resources