I've been running through this tutorial and everything has been going fine until I try to post to a users wall. I can get the user's info, first name, last name, education and such. But when I do the following:
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me/feed"]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Posted from Swangle for iPhone" forKey:#"message"];
[request setPostValue:#"Swangle for Iphone" forKey:#"name"];
[request setPostValue:#"Coming Soon..." forKey:#"caption"];
[request setPostValue:#"Description" forKey:#"description"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(postToWallFinished:)];
[request setDelegate:self];
[request startAsynchronous];
- (void)postToWallFinished:(ASIHTTPRequest *)request
{
// Use when fetching text data
NSString *responseString = [request responseString];
NSLog(#"Response String : %# and request : %#", responseString, request);
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *postId = [responseJSON objectForKey:#"id"];
NSLog(#"Post id is: %#", postId);
UIAlertView *av = [[[UIAlertView alloc] initWithTitle:#"Sucessfully posted to photos & wall!"
message:#"Check out your Facebook to see!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] autorelease];
[av show];
}
I am returned
Post id is : {"error":{"message":"Error validating application.","type":"OAuthException"}}
I know that the access_token is correct because I am allowed to login with it.
Also I created an application on developers.facebook, and am using the correct key to access their DB.
Can someone please advise me, or point me in the right direction to figure this out?
Thanks!
Have you asked for the authorization to post to the user wall?
From Facebook Graph API page:
Authorization
The Graph API as such allows you to easily access all public information about an object. For example, https://graph.facebook.com/btaylor (Bret Taylor) returns all the public information about Bret. For example a user's first name, last name and profile picture are publicly available.
To get additional information about a user, you must first get their permission. At a high level, you need to get an access token for the Facebook user. After you obtain the access token for the user, you can perform authorized requests on behalf of that user by including the access token in your Graph API requests
Take a look here:
https://developers.facebook.com/docs/reference/api/
Related
I followed this tutorial and was able to authenticate successfully and got the access token, now I am struggling to understand how can I get email associated with user profile before closing webview and join back my controller.
Any suggestions? I understand that Google has SDK for this, but I don't want to go that route if my requirement is possible with the tutorial I am using.
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
//Should I need to call another HTTP to retrieve email (or) email already available part of any other response?
If I need to call another HTTP, what URL should be invoked?
Make an authenticated request to the people.get API method with the userId set to me. The person resource has an emails array and the email with type set to account is their verified email.
I have a quick question.
I want the user to enter his username (email) and password and I want to get an access token from the bit.ly api.
I tried so far:
NSString *authStr = [NSString stringWithFormat:#"%#:%#", #"username", #"password"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64Encoding]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
However this does not work.
What I need is to get this command of curl to run in objective c:
curl -u "username:password" -X POST "https://api-ssl.bitly.com/oauth/access_token"
I know I can set the method to POST but I am not sure how to set username:password :|
I also tried using
curl -u "CLIENT_ID:CLIENT_SECRET" -d "grant_type=password" -d "username=USERNAME" \
-d "password=PASSWORD" https://api-ssl.bitly.com/oauth/access_token
however I still do not know how ti set the input of client id and client secret.
Any help on how I can set those information into the request would help me much!
Jack
Admittedly, things like AFNetworking do make working with NSURLConnection and the like a bit easier, but if you're doing this from scratch, you're close.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"https://api-ssl.bitly.com/oauth/access_token"]];
The endpoint for Resource Owner Credential Grants. That will get you the access_token you need to access the rest of our API.
The trickiest part of the flow is the "Authorization" header
NSString *authString = [NSString stringWithFormat:#"%#:%#", #"<YOUR CLIENT ID>", #"<YOUR CLIENT SECRET>"];
NSData *authData = [authString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64 = [authData base64EncodedStringWithOptions:0];
NSString *authHeader = [NSString stringWithFormat:#"Basic %#", base64];
[request setValue:authHeader forHTTPHeaderField:#"Authorization"];
This will set the Authorization field to: Basic clientID:clientSecret correctly base 64'ed
From there you need to set the body to the request
NSString *postBody = [NSString stringWithFormat:#"grant_type=password&username=%#&password=%#", #"<USERNAME>", #"<PASSWORD>"];
[request setHTTPBody:[postBody dataUsingEncoding:NSUTF8StringEncoding]];
Tell the request it's POST
[request setHTTPMethod:#"POST"];
Then open a NSURLConnection and observe the 3 important delegated methods
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
You will want to implement:
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
Source: I write the Bitly for iPhone app. Hope this helps. Let me know if you have any questions about the API, or the example above.
On 01.08.12 Bing modified their search api to a Azure, How can I authenticate in Objective-C to use the new bing search api from Azure?
My best guess is to learn from the provided PHP example in the migration word document!! http://go.microsoft.com/fwlink/?LinkID=248077 (Oh god, can't you setup a web page!) or this Java Question - Bing Search API Azure Marketplace Authentication in Java
I'm using ASIHTTPRequest to authenticate with following code.
NSString *queryString = [NSString stringWithFormat:#"'%#'", queryString];
queryString = [queryString urlEncodeUsingEncoding:NSUTF8StringEncoding]; //You'll have to implement url encoding method, preferably in a string category file
NSString *urlString = [NSString stringWithFormat:#"https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Image?Query=%#&Market='en-US'&$top=50&$format=json", queryString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlString] ];
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic];
[request setUsername:#"YOUR_KEY_HERE"];
[request setPassword:#"YOUR_KEY_HERE"];
[request setDelegate:self];
[request startAsynchronous];
Please note, no appID required. just instead pass your key as username and password. It is successfully getting the data.
However, can't really convert the data to NSString. tried every encoding but can't get the string from the data. Initial googling says it's UTF-8 encoded. But no success.
For above code to work, you must add ASIHTTP framework.
Another thing is, my guess is passing base64 encoded string with this format your_key:yourkey should also work with basic authentication.
I was able to get it to work using just NSUrlConnection. You must first base64encode
NSString *keyString = [NSString stringWithFormat:#"%#:%#", BING_SEARCH_API_KEY, BING_SEARCH_API_KEY];
NSData *plainTextData = [keyString dataUsingEncoding:NSUTF8StringEncoding];
NSString *base64String = [plainTextData base64EncodedString];
Setup your request
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] init];
[req setURL:[NSURL URLWithString:searchUrl]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", base64String];
[req setValue:authValue forHTTPHeaderField:#"Authorization"];
Make the request
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&error];
Look at the documentation about how to form searchUrl, and then process data according to the format you specified in $format= (I used json, so mine looks like):
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
I left out error handling, dont forget to add that by checking response as well as error.
I'm trying to add basic authorization to my request header. The code below compiles and I dont get any runtime errors. However, on the server side I do not see the "Authorization" in the header at all.
I was able to implement the didReceiveAuthenticationChallenge method and that works, but I dont understand why I have to do it this way. I simply want to always add basic auth to every request.
I'm not interested in using ASIHTTPRequest.
Thanks for the help!
This is my code below:
NSURL *url = [[NSURL alloc] initWithString:#"http://localhost:8000/MyWebService"];
self.userName = #"myusername";
self.password = #"mypassword";
NSMutableString *credentials = [[NSMutableString alloc] initWithFormat:#"%#:%#", userName, password];
NSString *encodedCredentials = [[credentials dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString *authHeader = [NSString stringWithFormat:#"Basic %#", encodedCredentials];
NSMutableURLRequest* req = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:5];
[req addValue:authHeader forHTTPHeaderField:#"Authorization"];
self.urlConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
if (self.urlConnection) {
self.receivedData = [NSMutableData data];
}
else {
errorLabel.text = #"Error connecting to the server";
}
The didReceiveAuthenticationChallenge is the way it works in iOS and the easiest way to do it. It will be submitted with every request (with the challenge). Guess that's not what you want to hear=)
I guess you have tried using different tutorials. I've used this one to authenticate before:
Basic access Auth, iOS
I used the asihttp library to connect to twitter.
The idea is to send a login request, get the response and extract the session ID/auth code from the response's cookie header. Then you can use that session ID/auth code for consecutive calls.
I don't obtain the auth_code because the authentication fails. how can I fix this?
the code is below:
- (void) login {
NSString *username = #"user";
NSString *password = #"pass";
NSURL *url = [NSURL URLWithString:#"https://twitter.com/sessions?phx=1"];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request addRequestHeader:#"User-Agent" value: #"ASIHTTPRequest"];
[request setPostValue:username forKey:#"session[username_or_email]"];
[request setPostValue:password forKey:#"session[password]"];
[request setDelegate: self];
[request setDidFailSelector: #selector(loginRequestFailed:)];
[request setDidFinishSelector: #selector(loginRequestFinished:)];
[request startAsynchronous];
}
- (void)loginRequestFailed:(ASIHTTPRequest *)request {
NSError *error = [request error];
NSLog(#"login request failed with error: %#", [error localizedDescription]);
}
- (void)loginRequestFinished:(ASIHTTPRequest *)request {
NSString *responseString = [[request responseHeaders] objectForKey:#"Set-Cookie"];
NSLog(#"%#",responseString);
}
I tried to connect from shell and it works.
curl -d 'session[user_or_emai]=user&session[password]=pass' https://twitter.com/sessions
Don't scrape twitter.com. It will end with you getting suspended. Instead use the approved API to integrate with Twitter. You can read about how authentication works with Twitter's API, how you can use xAuth to jumpstart authentication with a users password, and the open source code to help get you started.