Fetching Facebook Open Graph Data via NSURLRequest - ios

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"]]];

Related

iOS sending a POST and GET in the same request

I am successfully posting data as follows:
NSMutableURLRequest *scriptrequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"myurl.com"]];
[scriptrequest setHTTPMethod:#"POST"];
NSString *sendData =[NSString stringWithFormat:#"ID=%#&action=List", ID, nil];
NSData *scriptdata = [sendData dataUsingEncoding:NSUTF8StringEncoding];
[scriptrequest setHTTPBody:scriptdata];
NSError *scripterr;
NSURLResponse *scriptresponse;
NSData *scriptResponseData = [NSURLConnection sendSynchronousRequest:scriptrequest returningResponse:&scriptresponse error:&scripterr];
My question is, is it possible to also attach GET data to the same call?
GET and POST are different types of HTTP Request.
GET Request is majorly used for fetching the web content while POST is for insert/update some content.
So eventually A single HTTP request can only be of one of the following.
Http types include:
GET
HEAD
POST
PUT
DELETE
TRACE
OPTIONS
CONNECT
PATCH
More technical details at Wikipedia:
http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol
It looks to me like you are trying to retrieve data from your server, not update. A more typical way to form the request would be to GET http://myurl.com?ID=123&action=List. However, this really depends on how the server code is written.

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

Unable to Like a post from ios sdk

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.

Any alternative to NSURL?

A client is pondering development of an iPhone and iPad app and has asked an odd question: Is there any way to send data from an iOS device to a server other than using NSURL?
I think you could try using a POST request
responseData = [[NSMutableData data] retain];
NSMutableURLRequest *request = [NSMutableURLRequest
requestWithURL:[NSURL URLWithString:#"http://www.domain.com/your/servlet"]];
NSString *params = [[NSString alloc] initWithFormat:#"foo=bar&key=value"];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
That way the data would go inside the body of the request and not on the URL itself
The NSURL API isn't a way of getting data from a server. It's just a class for storing a URL. I suppose if you really want to avoid NSURL as much as possible, you could store URLs in an NSString, and then use appropriate APIs to convert it into an NSURL right before you use it.
To get data from a server, you would use either the NSURLSession API (modern) or NSURLConnection API (kind of crufty). Either is a fairly straightforward way to fetch data from an HTTP or HTTPS URL.
If you don't want to use either of those URL fetching APIs for some reason, you can write your own code using sockets or grab libcurl (MIT license) and link it into your app. Be aware that if you write your own socket code or use libcurl, assuming you're writing code for iOS, you'll need to occasionally use high-level APIs such as NSURL or CFHost to wake up the cellular radio.

Resources