How to Upload Photos on facebook using Graph API in iPhone? - iphone

I have made one application, In my application I have integrate Facebook for sharing information.
for Facebook integration I have use Graph API in application.
now In my application, I want to upload photo on user's wall.
I have use this code for upload photo on user's wall.
// for upload photo
- (void)uploadPhoto:(id)sender {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Image1" ofType:#"jpg"];
NSString *message = [NSString stringWithFormat:#"I think this is a Great Image!"];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request {
// Use when fetching text data
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:
#"https://graph.facebook.com/%#?access_token=%#", photoId,
[_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
But, here I get
responseString is {"error":{"message":"Error validating application.","type":"OAuthException"}} and
Photo id is: (null)
and Image is not upload on user's wall.
so, please tell me how to solve it.

First have you authorized your application to upload pictures by doing this (using the FBConnect SDK), you can checkout all permissions here
NSArray* permissions = [NSArray arrayWithObjects:#"publish_stream", #"user_photos", nil];
[facebook authorize:permissions];
The next problem is that facebook does not allow posts sent in this way to link to pictures hosted on their domains (I know it's REALLY annoying, maybe it would be worth checking if things have changed since april). I spent quite a bit of time working this one out. The way I cracked it was to create a redirect URL using bitly (you can access their services programatically using their API, there's an obj-c wrapper for it here, although I changed it to be asynchronous) and send that URL in the post.

may help u
//facebook post a image on wall
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
userImgView.image, #"picture",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];

another way is bellow for post image on Facebook ...
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:2];
//create a UIImage (you could use the picture album or camera too)
UIImage *picture = [UIImage imageNamed:"yourImageName"];
//create a FbGraphFile object insance and set the picture we wish to publish on it
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
//finally, set the FbGraphFileobject onto our variables dictionary....
[variables setObject:graph_file forKey:#"file"];
[variables setObject:#"write your Message Here" forKey:#"message"];
//the fbGraph object is smart enough to recognize the binary image data inside the FbGraphFile
//object and treat that is such.....
//FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"117795728310/photos" withPostVars:variables];
FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"me/photos" withPostVars:variables];
hope , this help you...
:)

The facebook API uses OAuth to authenticate requests. You will need to use a library that can request the appropriate temporary/client tokens, and generate the appropriate HTTP headers for requests. This is quite a complicated procedure which involves hashing and normalizing of request arguments.
You cannot do this crafting your own manual HTTP requests .

You can use facebook's native function
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: UIImageJPEGRepresentation(postImage, 1.0), #"source", self.postTextView.text, #"message", nil];
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me/photos" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error == nil) {
NSLog("Success");
}
else {
NSLog("Failed");
}
}];
Using this code you can post image with message.
Best regards

Related

How to get facebook friend_list using Graph API in Social Framework?

i am able to login in Facebook using my native application.i have used Social Framework and wanna get facebook friends location using Graph Api.
but i am not getting any solution what should i do in next step.
can anybody tell me what to do next ?? Thanks in Advance
You can request facebook friends using:
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error)
{
if (!error)
{
NSString *urlString = [NSString
stringWithFormat:#"https://graph.facebook.com/me?fields=id,name,friends.fields(id,name,picture),picture&access_token=%#",
[[FBSession.activeSession accessToken] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
NSLog(#"%#",url);
ASIFormDataRequest *request1 = [ASIFormDataRequest requestWithURL:url];
[request1 setRequestMethod:#"GET"];
[request1 setTag:101];
[request1 setDelegate:self];
[request1 startAsynchronous];
}
}];
and you will get the responce in:
- (void)requestFinished:(ASIHTTPRequest *)request
{
if (request.tag == 101){
NSDictionary *response = [[request responseString] JSONValue];
}
}

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 check that user has allowed my app to post on facebook wall or not after login with facebook?

I am facing a problem regarding facebook sdk in ios . I made an app that uses facebook login and at the time of login it ask me to allow permission that my app can post on my facebook wall or not. I want to check that permission is allowed by the user or not. How can I check that. Do you have any idea?
Thank you!
Try it :
NSString *theWholeUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me/permissions?access_token=%#",[[FBSession activeSession] accessToken]];
NSLog(#"TheWholeUrl: %#", theWholeUrl);
NSURL *facebookUrl = [NSURL URLWithString:theWholeUrl];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:facebookUrl];
[req setHTTPMethod:#"GET"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:req returningResponse:&response error:&err];
NSString *content = [NSString stringWithUTF8String:[responseData bytes]];
//NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
SBJSON *json = [SBJSON new];
NSError *error = nil;
NSDictionary * dictionary =[json objectWithString:content error:&error];
The accepted answer uses the Graph API but I presume you are using the native iOS Facebook SDK to make things easier?
If so you can find your issue fully documented by Facebook here. They cover all the different scenarios, including how to handle declined permissions and how to re-ask for permission when you need it.
The right way to do this with the Graph API is to use User.permissions.
https://developers.facebook.com/tools/explorer/?method=GET&path=me%2Fpermissions

How to post on Facebook a photo with tags using ASIHTTPRequest

I am posting a photo on Facebook from my iPhone app using the Graph API and ASIFormDataRequest.
Everything works fine (photo is uploaded with the right caption). When I try to add tags, photo is still uploaded but with no tag.
Here is how I prepare the data
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/photos",userID]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
[request setPostValue:caption forKey:#"message"];
[request setPostValue:fbManager._facebook.accessToken forKey:#"access_token"];
[request setAllowCompressedResponse:NO];
[request setTimeOutSeconds:60];
//Add tags
NSMutableArray *tagArray=[[NSMutableArray alloc] init];
for(FacebookTag *aTag in aJob.tags) {
NSNumber *_cordX=[NSNumber numberWithFloat:((aTag.x/aJob.image.size.width)*100.0)];
NSNumber *_cordY=[NSNumber numberWithFloat:((aTag.y/aJob.image.size.height)*100.0)];
NSString *cordX=[_cordX stringValue];
NSString *cordY=[_cordY stringValue];
NSMutableDictionary* tag = [NSMutableDictionary dictionaryWithObjectsAndKeys:
aTag.userId, #"to",
cordX, #"x",
cordY, #"y",
nil];
[tagArray addObject:tag];
}
NSData *tagData = [NSKeyedArchiver archivedDataWithRootObject:tagArray];
NSString* tagString = [[NSString alloc] initWithData:tagData encoding:NSUTF8StringEncoding];
[request setPostValue:tagString forKey:#"tags"];
Try this code
// Upload photo
...
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
newPhoto, #"picture", nil];
[self.facebook requestWithGraphPath:#"me/photos" andParams:params
andHttpMethod:#"POST" andDelegate:self];
...
// Response received. Photo upload successful, so add tags
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([request.params objectForKey:#"picture"]) {
// Get photo ID from result
NSString* photoId = (NSString*)[result objectForKey:#"id"];
NSMutableDictionary* params = nil;
for (int i = 0; i < [tagsList count]; i++) {
// tagsList contains user IDs to tag
NSString* uid = (NSString*)[tagsList objectAtIndex:i];
params = [NSMutableDictionary dictionaryWithObjectsAndKeys:uid, #"to",
nil];
NSString* graphUrl = [NSString stringWithFormat:#"%#/tags", [photoId stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]];
[self.facebook requestWithGraphPath:graphUrl
andParams:params andHttpMethod:#"POST" andDelegate:self];
}
}
...
}
It is using FBGraph API

Using Twitter API's upload_with_media with iOS SDK?

I've been looking for a Objective-C version of this PHP code sample on how to use Twitter's upload_with_media for an iPhone application.
I have been able to find one. Could you point me to ane example or explain how I could translate this code to Objective-C?
Thanks
You can Do like this for upload_with_media,
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"] parameters:nil requestMethod:TWRequestMethodPOST];
UIImage * image = [UIImage imageNamed:#"myImage.png"];
//add text
[postRequest addMultiPartData:[#"I just found the secret level!" dataUsingEncoding:NSUTF8StringEncoding] withName:#"status" type:#"multipart/form-data"];
//add image
[postRequest addMultiPartData:UIImagePNGRepresentation(image) withName:#"media" type:#"multipart/form-data"];
// Set the account used to post the tweet.
[postRequest setAccount:twitterAccount];
// Perform the request created above and create a handler block to handle the response.
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
[self performSelectorOnMainThread:#selector(displayText:) withObject:output waitUntilDone:NO];
}];