I am having some trouble trying to get the Facebook iOS SDK to batch upload photos. Currently I can upload them one by one, but I would like to batch the requests if possible. I have read this post over and over along with the fb batch docs. Here is what I have thus far.
Facebook *facebook = [(AppDelegate*)[[UIApplication sharedApplication] delegate] facebook];
NSData *imageData = UIImagePNGRepresentation([imgs objectAtIndex:0]);
NSString *jsonRequest1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\", \"attached_files\": \"file1\" }"];
NSString *jsonRequest2 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\", \"attached_files\": \"file2\" }"];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[ %#, %# ]", jsonRequest1, jsonRequest2];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonRequestsArray,#"batch",imageData,#"file1",imageData,#"file2" nil];
I am mapping the imageData to the key it is looking for, but I get this response every time.
{
body = "{\"error\":{\"message\":\"File batch has not been attached\",\"type\":\"GraphBatchException\"}}";
code = 400;
headers = (
{
name = "WWW-Authenticate";
value = "OAuth \"Facebook Platform\" \"invalid_request\" \"File batch has not been attached\"";
},
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Cache-Control";
value = "no-store";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
},
{
body = "{\"error\":{\"message\":\"File file2 has not been attached\",\"type\":\"GraphBatchException\"}}";
code = 400;
headers = (
{
name = "WWW-Authenticate";
value = "OAuth \"Facebook Platform\" \"invalid_request\" \"File file2 has not been attached\"";
},
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Cache-Control";
value = "no-store";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
}
)
Any help is very much appreciated.
Have you tried using the Social framework for iOS 6 to share photos? It allows you to add all the photos and share them.
- (IBAction)postToFacebook:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"First post from my iPhone app"];
[controller addURL:[NSURL URLWithString:#"http://www.jinibot.com"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
//add as many images as you want
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[self presentViewController:controller animated:YES completion:Nil];
}
}
Try with this.
Please notice that Facebook limit the number of requests which can be in a batch to 50.
-(void)uploadBulkPhotosToAlbum:(NSArray *)photoArray albumId:(NSString *)albumId
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
NSString *graphPath = [NSString stringWithFormat:#"%#/photos",albumId];
NSMutableString *jsonFormat = [[NSMutableString alloc] init];
[jsonFormat setString:#"["];
for (int i = 0; i < photoArray.count; i++)
{
if (i != 0)
{
[jsonFormat appendString:#","];
}
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSString *jsonRequest = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"attached_files\": \"%#\" }",graphPath,fileName];
[jsonFormat appendString:[NSString stringWithFormat:#" %#",jsonRequest]];
}
[jsonFormat appendString:#" ]"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonFormat,#"batch",nil];
for (int i = 0; i < photoArray.count; i++)
{
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSData *data = UIImagePNGRepresentation([photoArray objectAtIndex:i]);
[params setObject:data forKey:fileName];
}
FBRequest *request = [FBRequest requestWithGraphPath:#"me" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
{
[self resetViewAfterUpload:result];
}
else
{
[MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
NSLog(#"Photo uploaded failed :( %#",error.userInfo);
[[[UIAlertView alloc] initWithTitle:#"Error occurred!!" message:#"Some error occured while uploading." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil] show];
}
}];
[connection start];
}
With the new Facebook SDK (3.0) try something like this:
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
FBRequest *request1 = [FBRequest requestForUploadPhoto:image1];
[connection addRequest:request1
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
//handle error/success
}
];
FBRequest *request2 = [FBRequest requestForUploadPhoto:image2];
[connection addRequest:request2
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
//handle error/success
}
];
[connection start];
How about using an NSOperationQueue to queue up all the upload requests?
Here is function I have used in one of our project by Facebook SDK 3.x
-(void)postOnFacebookWall : (id )response{
NSString *strPost = [NSString stringWithFormat:#"Group Name:%#",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_name"]];
NSString *strUrl = [NSString stringWithFormat:#"%#",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_picture_path"]];
NSURL *urlToShare = [NSURL URLWithString:strUrl];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:urlToShare]];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Heook"
caption:#"string"
description:#"The 'Has."
picture:urlToShare
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
if (!appCall) {
// Next try to post using Facebook's iOS6 integration
BOOL displayedNativeDialog = [FBDialogs presentOSIntegratedShareDialogModallyFrom:self
initialText:strPost
image:image
url:nil
handler:nil];
if (!displayedNativeDialog) {
[self performPublishAction:^{
// NSString *message = [NSString stringWithFormat:#"Group Name:%#\nGroup Image:%#\n",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_name"],[[response valueForKey:#"GroupDetail"] valueForKey:#"group_picture_path"]];
[FBRequestConnection startForPostStatusUpdate:strPost
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"Group shared on facebook" result:result error:error];
}];
}];
}
}
}
Related
I am trying to get Facebook friend list with name, id, etc in my app.
- (IBAction)onFBLogin:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"email", #"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"%#", result);
[self getFBEmailAddress];
}
}];
}
-(void)getFBEmailAddress{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email, friends"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *pictureURL = [NSString stringWithFormat:#"%#",[result objectForKey:#"picture"]];
mFBId = [NSString stringWithFormat:#"%#",[result objectForKey:#"id"]];
NSLog(#"My Profile : %#", result);
NSLog(#"email is %#", [result objectForKey:#"email"]);
[self getFBFriendList];
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
-(void)getFBFriendList{
NSString* graphPat = [[NSString alloc] initWithFormat:#"%#/friends", mFBId];
FBSDKGraphRequest *requestFriends = [[FBSDKGraphRequest alloc]
initWithGraphPath:graphPat
parameters:#{#"fields": #"id, name"}
HTTPMethod:#"GET"];
[requestFriends startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error && result)
{
NSArray *allFriendsResultData = [result objectForKey:#"data"];
if ([allFriendsResultData count] > 0)
{
for (NSDictionary *friendObject in allFriendsResultData)
{
NSString *friendName = [friendObject objectForKey:#"name"];
NSString *friendID = [friendObject objectForKey:#"id"];
NSLog(#"%# : %#", friendID, friendName);
}
}
}
}];}
I've succeed to login via Facebook and get my profile. After that, I've tried to get friend list via the friends graph api. But at that time, it only said count of friends following as below.
friends = {
data = (
);
summary = {
"total_count" = 2;
};
};
id = 60XXXXXX1295X;
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/hprofile-xfa1/v/t1.0-1/p50x50/1..._501957533...";
};
};
How Can I get full information of friends list such as id, name, etc? Please help me if any one already implemented. Thank you.
This work for me.
NSMutableArray *completeList = [[NSMutableArray alloc] init];
[self fetchFacebookEachFriend:completeList withGrapPath:#"/me/friends" withCallback:^(BOOL success, NSMutableArray * fbList) {
//Finish get All Friends
fbListFinal(success, fbList);
}];
- (void)fetchFacebookEachFriend:(NSMutableArray *)completeList withGrapPath:(NSString *)graphPath withCallback:(returnFbList)fbList
{
NSDictionary *limitDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_name, last_name, middle_name, name, email", #"fields", nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:graphPath parameters:limitDictionary HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Alert!" message:#"Please connect to Facebook to find your friends" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
fbList(NO, completeList);
return;
}
//Add each friend to list
for (NSDictionary *friend in [result valueForKey:#"data"]) {
[completeList addObject:friend];
}
if ([result valueForKey:#"paging"] != nil && [[result valueForKey:#"paging"] valueForKey:#"next"] != nil) {
NSString *nextPage = [[result valueForKey:#"paging"] valueForKey:#"next"];
nextPage = [[nextPage componentsSeparatedByString:#"?"] objectAtIndex:1];
[self fetchFacebookEachFriend:completeList withGrapPath:[NSString stringWithFormat:#"me/friends?%#",nextPage] withCallback:fbList];
} else
fbList(YES, completeList);
}];
}
result.paging.next contains the complete URL, with access token and all. I find the simplest thing is just to pass it on to an NSURLSession data task:
NSString *nextPage = result[#"paging"][#"next"];
if (!nextPage) return;
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:nextPage] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [self decodeJSONResult:data response:response error:error];
// use json
}] resume];
I wrote this as an FBSDKGraphRequest extension: FBSDKGraphRequest+Paging.h
I tried the below code for getting email of the person who logged in iOS Settings Facebook.
Please help me how to get email from SLRequest.
- (void) getMyDetails {
if (! _accountStore) {
_accountStore = [[ACAccountStore alloc] init];
}
if (! _facebookAccountType) {
_facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSDictionary *options = #{ ACFacebookAppIdKey: FB_APP_ID };
[_accountStore requestAccessToAccountsWithType: _facebookAccountType
options: options
completion: ^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [_accountStore accountsWithAccountType:_facebookAccountType];
_facebookAccount = [accounts lastObject];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:url
parameters:nil];
request.account = _facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"id: %#", responseDictionary[#"id"]);
}];
}
}];
}
Here is the code tested on iOS 8 that returns email. The solution doesn't require Facebook SDK, although the system grants access to Facebook account only if a user logged in with Facebook in Settings app.
// Required includes
#import Accounts;
#import Social;
// Getting email
ACAccountStore *theStore = [ACAccountStore new];
ACAccountType *theFBAccountType = [theStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *theOptions = #{
ACFacebookAppIdKey : #"YOUR_APP_ID",
ACFacebookPermissionsKey : #[#"email"]
};
[theStore requestAccessToAccountsWithType:theFBAccountType options:theOptions completion:^(BOOL granted, NSError *error) {
if (granted) {
ACAccount *theFBAccount = [theStore accountsWithAccountType:theFBAccountType].lastObject;
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://graph.facebook.com/me"]
parameters:#{#"fields" : #[#"email"]}];
request.account = theFBAccount;
[request performRequestWithHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil && ((NSHTTPURLResponse *)response).statusCode == 200) {
NSError *deserializationError;
NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&deserializationError];
if (userData != nil && deserializationError == nil) {
NSString *email = userData[#"email"];
NSLog(#"%#", email);
}
}
}];
}
}];
You can get email id by below mentioned way.
Call Facebook graph API by the help of access token that you got from Account store
And yes, to get email id from Facebook, you need to provide "email" permission while requesting access token, without the permission you won't be able to get email parameter
Here is my code
NSString *FB_EncodedToken = [APP_CONSTANT.facebookToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *opearation = [AFHTTPRequestOperationManager manager];
opearation.requestSerializer = [AFHTTPRequestSerializer serializer];
opearation.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *strUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me?"];
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:FB_EncodedToken,#"access_token", nil];
[opearation GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLogs(#"Description %#",responseObject);
//Lets pasre the JSON data fetched from facebook
[self parseUserDetail:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLogs(#"Error description %#",error.description);
self.completionHandler(error);
}];
Then parse the data
-(void)parseUserDetail:(NSDictionary *)dict
{
FBProfileBO *profile = [[FBProfileBO alloc] init];
profile.userFirstName = [dict objectForKey:#"first_name"];
profile.userLastName = [dict objectForKey:#"last_name"];
profile.userEmail = [dict objectForKey:#"email"];
profile.userName = [dict objectForKey:#"name"];
profile.userDOB = [dict objectForKey:#""];
profile.facebookId = [dict objectForKey:#"id"];
//Call back methods
self.completionHandler(profile);
profile = nil;
}
I am making a test app through that I want to post a video on facebook. I am using latest sdk of facebook. But I am not able to post it on facebook. The video is coming from web service.
How to convert video url in nsdata and mu code is below
NSString *astrUserid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"user_id"];
NSString *astrImageid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"image_id"];
NSString *astrExt=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"ext"];
NSString *aStrDisplyimage=[NSString stringWithFormat:#"http://followme.pmcommu.com/audio/user/%#-%#.%#",astrUserid, astrImageid,astrExt ];
NSURL *aimageurl=[NSURL URLWithString:aStrDisplyimage];
NSString *filePathOfVideo = [aimageurl path];
NSLog(#"Path Of Video is %#", filePathOfVideo);
NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
//you can use dataWithContentsOfURL if you have a Url of video file
//NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
//NSLog(#"data is :%#",videoData);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video name ", #"name",
#"description of Video", #"description",
nil];
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"RESULT: %#", result);
//[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
//[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
}
}];
}
else
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Login fail :%#",error);
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
//[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
NSLog(#"RESULT: %#", result);
}
else
{
//[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}
}];
}
I am new for that can any one help me please
or this will help you for upload and streaming video, i think
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ACFacebookAppIdKey: FACEBOOK_ID,
ACFacebookPermissionsKey: #[#"publish_stream", #"video_upload"],
ACFacebookAudienceKey: ACFacebookAudienceFriends}; // basic read permissions
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:facebookAccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSDictionary *parameters = #{#"description": aMessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/videos"]
parameters:parameters];
[facebookRequest addMultipartData: aVideo
withName:#"source"
type:#"video/mp4"
filename:#"video.mov"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}];
}
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[e localizedDescription]);
}
}];
Get the publish permission
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
Try this
- (void)fbDidLogin {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/videos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
try this
[NSData dataWithContentsOfURL:[NSURL URLWithString:#"Your URL"]]
-(void)facbookSharng {
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self]
// write the deleate methdo for post ID..
}
I am trying to create a new album on a user's Facebook account, and upload images to that album. I have succeeded to create an album, but when I start uploading images to it only the last image selected gets uploaded the number of times the images I have selected.
This is my piece of code to create a Facebook album and upload images to it
- (void)createFacebookAlbum {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setObject:albumNAME forKey:#"name"];
[parameters setObject:#"Test message" forKey:#"message"];
FBRequest* request = [FBRequest requestWithGraphPath:#"me/albums" parameters:parameters HTTPMethod:#"POST"];
NSLog(#"creating facebook album");
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
albumId = [result objectForKey:#"id"];
NSLog(#"OK %#", albumId);
[self publishContentToAlbum:[result objectForKey:#"id"]];
}
else {
NSLog(#"Error: %#",error.userInfo);
}
}];
[connection start];
}
-(void)uploadBulkPhotosToAlbum:(NSMutableArray *)photoArray albumId:(NSMutableArray *)albumId{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
NSString *graphPath = [NSString stringWithFormat:#"%#/photos",albumId];
NSMutableString *jsonFormat = [[NSMutableString alloc] init];
[jsonFormat setString:#"["];
for (int i = 0; i < (NSUInteger *)countere; i++)
{
if (i != 0)
{
[jsonFormat appendString:#","];
}
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSString *jsonRequest = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"attached_files\": \"%#\" }",graphPath,fileName];
[jsonFormat appendString:[NSString stringWithFormat:#" %#",jsonRequest]];
}
[jsonFormat appendString:#" ]"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonFormat,#"batch",nil];
for (int i = 0; i <(NSUInteger *)countere; i++)
{
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSData *data = UIImagePNGRepresentation([photoArray objectAtIndex:i]);
[params setObject:data forKey:fileName];
}
FBRequest *request1 = [FBRequest requestWithGraphPath:graphPath
parameters:params
HTTPMethod:#"POST"];
[connection addRequest:request1
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Photo uploaded successfuly! %#",result);
} else {
NSLog(#"Photo uploaded failed :( %#",error.userInfo);
}
}];
[connection start];
}
Can anyone help me to solve my problem?
Thanks for the reply.
I'm uploading a photo as an open graph object, then tying it into my open graph action once it returns the URL.
Everything is working great so far, but I'm not able to get the custom user message "TEST TEST TEST TEST!" to show up. I've been hitting this issue from all angles and can't seem to get it nailed down. Any ideas?
- (void)postPhotoThenOpenGraphAction {
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
// First request uploads the photo.
FBRequest *request1 = [FBRequest requestForUploadPhoto:[UIImage imageWithData:[NSData dataWithContentsOfFile:picture.pathSmall]]];
[connection addRequest:request1 completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
} else {
[self showFacebookFailedError];
}
}
batchEntryName:#"photopost"];
// Second request retrieves photo information for just-created
// photo so we can grab its source.
FBRequest *request2 = [FBRequest requestForGraphPath:#"{result=photopost:$.id}"];
[connection addRequest:request2 completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error && result) {
NSString *source = [result objectForKey:#"source"];
[self postOpenGraphActionWithPhotoURL:source];
} else {
[self showFacebookFailedError];
}
}
];
[connection start];
}
- (void)postOpenGraphActionWithPhotoURL:(NSString*)photoURL {
id<PTOGPicture> photoGraphObject = [self pictureObjectForPicture:self.picture];
id<PTOGSharePicture> action = (id<PTOGSharePicture>)[FBGraphObject graphObject];
action.photo = photoGraphObject;
if (self.selectedPlace) {
action.place = self.selectedPlace;
}
if (self.selectedFriends.count > 0) {
action.tags = self.selectedFriends;
}
action.message = #"TEST TEST TEST TEST!";
if (photoURL) {
NSMutableDictionary *image = [[NSMutableDictionary alloc] init];
[image setObject:photoURL forKey:#"url"];
NSMutableArray *images = [[NSMutableArray alloc] init];
[images addObject:image];
action.image = images;
}
// Create the request and post the action to the.
[FBRequestConnection startForPostWithGraphPath:#"me/myappapp:share"
graphObject:action
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
//... code taken out for brevity
}];
}
I have a simpler version that works for what you want:
First you create your action object as you wish:
- (void)shareOnFacebook {
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
action[#"<OPEN_GRAPH_OBJ>"] = obj;
action[#"image[0][url]"] = url;
action[#"image[0][user_generated]"] = #"true";
action[#"message"] = #"some message here";
[FBRequestConnection startForPostWithGraphPath:#"me/<app_namespace>:<action>" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
}];
}
However, the requirement for this to work, is that you must have these two permissions set on the action setup page:
I hope it helps.