Upload multiple photos on Facebook using Batch Request - iphone

I had done following code with reference to following link to create batch request for uploading multiple photos in Facebook.
I had got some solution for uploading multiple photos on Facebook through this Facebook graph API.
CODE:
NSString *jsonRequest1 = #"{ \"method\": \"POST\", \"relative_url\": \"me/photos\" , \"body\": \"Hello 1\", \"attached_files\": \"file1\" }";
NSString *jsonRequest2 = #"{ \"method\": \"POST\", \"relative_url\": \"me/photos\" , \"body\": \"Hello 2\", \"attached_files\": \"file2\" }";
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[ %#, %# ]", jsonRequest1, jsonRequest2];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonRequestsArray,#"batch",nil];
[params setObject:UIImagePNGRepresentation(self.image1) forKey:#"file1"];
[params setObject:UIImagePNGRepresentation(self.image2) forKey:#"file2"];
[objFacebook requestWithGraphPath:#"me" andParams:params andHttpMethod:#"POST" andDelegate:self];
Now when I am running this code I got the following output.
Result Dictionary in - (void)request:(FBRequest *)request didLoad:(id)result
(
{
body = "{\"error\":0,\"error_description\":\"File file1 has not been attached\"}";
code = 400;
headers = (
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
},
{
body = "{\"error\":0,\"error_description\":\"File file2 has not been attached\"}";
code = 400;
headers = (
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
}
)
I don't know how this files attached.. Can anyone help me to figure out this problem.
Is there any change in my code then please let me know.
Thanks in advance...

I recommend you use the new integrated Facebook API's in iOS 6 to do this instead of Facebook's API: https://developer.apple.com/videos/wwdc/2012/?id=306 there's a golden WWDC video for all social tasks. Plus using the new API's in iOS 6 is MUCH faster then using Facebooks.

For your NSDictionary of parameters ,use the NSData representation, instead of directly using the UIImage object.
Depending on the compression format of the images you are trying to upload, you'll need to use a different method to convert the UIImage to NSData. Here are two techniques, one for PNG and one for JPEG
//...cut...
[params setObject:UIImageJPEGRepresentation(self.jpegImage, 0.8) forKey:#"file1"];
[params setObject:UIImagePNGRepresentation(self.pngImage) forKey:#"file2"];
//...cut...
This is a tutorial from the Facebook Developer blog that shows something similar (although it is for a video, and not the batch API), and one significant difference from your code is that the parameter passed is in NSData representation, not UIImage.
http://developers.facebook.com/blog/post/532/

[params setObject:UIImagePNGRepresentation(self.image1) forKey:#"file1"];
This should not be the data, it should be the path for that images. It will work fine if you provide a path instead of NSData.

I got the solution for multiple file upload using FBgraph.
here is my code.
-(void) fbGraphCallback
{
FbGraphFile *graph_file = [[FbGraphFile alloc]initWithImage:imgView1.image];
FbGraphFile *graph_file1 = [[FbGraphFile alloc]initWithImage:imgView2.image];
NSString *jsonRequest1 = #"{ \"method\": \"POST\", \"relative_url\": \"me/photos\" , \"body\": \"First Image\", \"attached_files\": \"file1\" }";
NSString *jsonRequest2 = #"{ \"method\": \"POST\", \"relative_url\": \"me/photos\" , \"body\": \"Second Image\", \"attached_files\": \"file2\" }";
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[ %#, %# ]", jsonRequest1, jsonRequest2];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonRequestsArray,#"batch",nil];
[params setObject:graph_file forKey:#"file1"];
[params setObject:graph_file1 forKey:#"file2"];
[fbgraph doGraphPost:#"" withPostVars:params];
}
Thanks mehul.

You are adding the binary to the Dictionary incorrectly. Take a look at the file upload method in Facebook's sample app. You should be able to easily adopt Facebook's sample code to your app.
/**
* Upload a photo.
*/
-(IBAction)uploadPhoto:(id)sender
{
NSString *path = #"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, #"picture",
nil];
[_facebook requestWithMethodName:#"photos.upload"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
}

Related

How to tag photo to friends using graph api in ios

I got this error-
ostPictureButtonPressed: {"error":{"message":"(#100) param tags must be non-empty.","type":"OAuthException","code":100}}
My code is
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:6];
UIImage *picture = [UIImage imageNamed:#"Default.png"];
//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"];
NSArray *arr=[[NSArray alloc]initWithObjects:#"100001912715296", nil ];
SBJsonWriter *writer = [[SBJsonWriter alloc] init];
NSString *jsonString = [writer stringWithObject:arr];
NSLog(#"The jason string is %#",jsonString);
[variables setObject:jsonString forKey:#"tags"];
[variables setObject:#"110506962309835" forKey:#"place"];
[variables setObject:#"Hello friends I am using MySafety App.\n This is a must have app for all peoples whether you are a working lady, a house wife or a school going girl.This app lets you save 6 emergency contacts whom you want to alert in case of emergency.Whenever you feel you are in danger, just press the SOS button and it will send sms to your contacts with your current location and a alarm will go on with flashing lights" 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];
NSLog(#"fb_graph_response %#",fb_graph_response);
NSLog(#"postPictureButtonPressed: %#", fb_graph_response.htmlResponse);

Not receiving Facebook picture via Graph API

I can't seem to properly retrieve a user's profile picture using the current iOS graph method.
My call: self.pictureRequest = [facebook requestWithGraphPath:#"me/picture" andDelegate:self];
What I do with the result:
-(void)request:(FBRequest *)request didLoad:(id)result{
if(request == self.pictureRequest){
UIImageView *image = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 500, 500)];
image.image = [UIImage imageWithData:result];
[self.view addSubview:image];
NSLog("result is %#", result);
}
So I'm just trying to get the profile picture right now. Result shows up as null in the console. I guess this means I'm not actually getting a result? (I tried if(result) NSLog(#"got a result") but it doesn't return, so I'm guessing a result isn't being sent back by fb?)
Any ideas? I also looked up a similar problem here but not sure what they do differently:
Problem getting Facebook pictures via iOS
well I can retrieve the user pic and other info like this .. try it
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic, email FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}//Call this function after the facebook didlogin
and in request didLoad:
- (void)request:(FBRequest *)request didLoad:(id)result
{
if([request.url rangeOfString:#"fql.query"].location !=NSNotFound)
{
if ([result isKindOfClass:[NSArray class]] && [result count]>0) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"name"]) {
self.fbUserName = [result objectForKey:#"name"];
// Get the profile image
UIImage *fbimage = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[result objectForKey:#"pic"]]]];
}
If you want to get the picture URL using requestWithGraph path (instead of requestWithMethodName like #Malek_Jundi provides) then see my answer here:
iOS Facebook Graph API Profile picture link
You can also get fb profile picture url by,
NSString *userFbId;
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture", userFbId]];
NSData *imageData = [[NSData alloc] initWithContentsOfURL:url];
self.userProfileImage.image = [UIImage imageWithData:imageData];

error on uploading Video to Youtube failedWithStatus:400 [duplicate]

I want to upload video from my app to the youtube. I am using the example YoutubeTest for this purpose. I have set the developer key and client Id for my app. Now when trying to upload the video using example source code, it shows an error which is:
2012-03-19 10:51:07.947 YouTubeTest[539:f803] serviceBase: objectFetcher: failedWithStatus:400 data:
2012-03-19 10:51:07.985 YouTubeTest[539:f803] Error: Error Domain=com.google.GDataServiceDomain Code=400 "The operation couldn’t be completed. (com.google.GDataServiceDomain error 400.)" UserInfo=0x6c49e50 {}
Has anyone successfully implemented the GData to upload videos to youtube from the iphone app. Can anyone give me the example source code.
Yes ofcourse many had successfully implemented it ... hmmm try this link http://urinieto.com/category/google/ follow instructions line by line.
Not Sure y you are getting this error. Follow above instructions if problem still persists i will help you out .
Cheers
I am having the same issue with YouTubeTest app. here is the code for request:
(IBAction)uploadPressed:(id)sender {
NSString *devKey = [mDeveloperKeyField text];
GDataServiceGoogleYouTube *service = [self youTubeService];
[service setYouTubeDeveloperKey:devKey];
NSString *username = [mUsernameField text];
NSString *clientID = [mClientIDField text];
NSURL *url = [GDataServiceGoogleYouTube youTubeUploadURLForUserID:username
clientID:clientID];
// load the file data
NSString *path = [[NSBundle mainBundle] pathForResource:#"YouTubeTest" ofType:#"m4v"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSString *filename = [path lastPathComponent];
// gather all the metadata needed for the mediaGroup
NSString *titleStr = [mTitleField text];
GDataMediaTitle *title = [GDataMediaTitle textConstructWithString:titleStr];
NSString *categoryStr = [mCategoryField text];
GDataMediaCategory *category = [GDataMediaCategory mediaCategoryWithString:categoryStr];
[category setScheme:kGDataSchemeYouTubeCategory];
NSString *descStr = [mDescriptionField text];
GDataMediaDescription *desc = [GDataMediaDescription textConstructWithString:descStr];
NSString *keywordsStr = [mKeywordsField text];
GDataMediaKeywords *keywords = [GDataMediaKeywords keywordsWithString:keywordsStr];
BOOL isPrivate = mIsPrivate;
GDataYouTubeMediaGroup *mediaGroup = [GDataYouTubeMediaGroup mediaGroup];
[mediaGroup setMediaTitle:title];
[mediaGroup setMediaDescription:desc];
[mediaGroup addMediaCategory:category];
[mediaGroup setMediaKeywords:keywords];
[mediaGroup setIsPrivate:isPrivate];
NSString *mimeType = [GDataUtilities MIMETypeForFileAtPath:path
defaultMIMEType:#"video/mp4"];
// create the upload entry with the mediaGroup and the file data
GDataEntryYouTubeUpload *entry;
entry = [GDataEntryYouTubeUpload uploadEntryWithMediaGroup:mediaGroup
data:data
MIMEType:mimeType
slug:filename];
SEL progressSel = #selector(ticket:hasDeliveredByteCount:ofTotalByteCount:);
[service setServiceUploadProgressSelector:progressSel];
GDataServiceTicket *ticket;
ticket = [service fetchEntryByInsertingEntry:entry
forFeedURL:url
delegate:self
didFinishSelector:#selector(uploadTicket:finishedWithEntry:error:)];
[self setUploadTicket:ticket];
}
Solved my problem. The error info in your case is not enough. But if you print out the HTTPURLResponse from the server , it will help to spot the error. In my case keywords length was too long.
I faced the same error. But I did find a solution through trial and error :)
Actually as Youtube itself states
You don't need to provide Client_Id anymore. Please remove it.
But the actual problem was with the login credentials. API was returning error response when i login as "xyz#gmail.com". It started working when i provided just the username without domain "xyz".
Hope this helps!

batch request graph api iPhone xcode?

I am going to fetch four or multiple records of from facebook through graph api with batch request like this
NSString *jsonRequest1 = #"{ \"method\": \"GET\", \"relative_url\": \"133028623426021\" }";
NSString *jsonRequest2 = #"{ \"method\": \"GET\", \"relative_url\": \"152881298125928\" }";
NSString *jsonRequest3 = #"{ \"method\": \"GET\", \"relative_url\": \"20870926514\" }";
NSString *jsonRequest4 = #"{ \"method\": \"GET\", \"relative_url\": \"124551187593106\" }";
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[ %#, %#, %#, %# ]", jsonRequest1, jsonRequest2,jsonRequest4,jsonRequest3];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:jsonRequestsArray forKey:#"batch"];
FbGraphResponse *fb_graph_response1 = [fbGraph doGraphPost:jsonRequestsArray withPostVars:params];
NSLog(#"%#",fb_graph_response1.htmlResponse);
But my response is like this
response =
How can i get response through graph api with batch request?
For request_ids, you do not need to create a batch request. You can simply pass them as a comma separate list and avoid doing a batch request.
NSString *requestIds = #"123456789,987654321";
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObject:requestIds forKey:#"ids"];
[facebook requestWithGraphPath:#"" andParams:params andDelegate:self];
Your final graph URL wants to look like:
https://graph.facebook.com/?ids=REQUEST_ID1,REQUEST_ID2,REQUEST_ID3&access_token=ACCESS_TOKEN

Share image on facebook using FBConnect

After searching 2 days on it m finally posting my code.
Application Description: I am choosing an image through imagePicker and after editing it I want to share it on Facebook.
Problem: I can post the text on my wall but not the image, as i dont have any URL i cant find another way to post image on my wall.
here is the code ( which i stole from another application) of my PostToWall
FBStreamDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
dialog.userMessagePrompt = #"Enter your message:";
dialog.actionLinks = #"[{\"Get DowntownLA!\",\"href\":\"http://www.facebook.com/DowntownLA.com/\"}]";
dialog.attachment = [NSString stringWithFormat:
#"{ \"name\":\"%#\","
"\"href\":\"%#\","
"\"caption\":\"%#\",\"description\":\"%#\","
"\"media\":[{\"type\":\"image\","
"\"src\":\"%#\","
"\"href\":\"%#\"}],"
"\"properties\":{\"%#\":{\"text\":\"%#\",\"href\":\"%#\"}}}", #"name: priya",#"href nothing",#"cation nothing",#"description nothin", #"imageSource nothing ", #"imageHref nothing", #"linkTitle nothing", #"linkText nothing", #"linkHref nothing"];
[dialog show];
Please tel me wher m going wrong !!!!!
The error m getting on simulator is : Application Response Error - The post action links must be valid URls. You can see this because you are one of the developers of the app.
i have upload image in this way
- (void) postOnFBWall
{
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:2];
//create a UIImage (you could use the picture album or camera too)
UIImage *picture = imgUploadPhoto.image;
//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"];
NSString * messageValue = [NSString stringWithFormat:#"Menu Name: %#, Restaurant: %#, Category: %#, Comment: %#",txtNameofMenu.text,txtRestaurant.text,categoryLbl.text,txtViewComment.text];
[variables setObject:[NSString stringWithFormat:#"%#",messageValue] 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 = [[FBRequestWrapper defaultManager] doGraphPost:#"me/photos" withPostVars:variables];
NSLog(#"postPictureButtonPressed: %#", fb_graph_response.htmlResponse);
}