Facebook Graph Object/Event post in new 4.0 SDK - ios

I'm attempting to post a graph event like so with the new SDK:
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
action[#"event"] = #"http://samples.ogp.me/680289198752391";
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/friendlish:add" parameters:action tokenString:token.tokenString version:#"v2.3" HTTPMethod:#"POST"];
//
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"%#", error);
else
NSLog(#"%#", result);
}];
[connection start];
All works fine, and it posts -- but when I try actually changing up the example to something custom like this:
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
NSMutableDictionary<FBGraphObject> *event = [FBGraphObject openGraphObjectForPost];
event[#"og:title"] = #"My Event";
event[#"og:type"] = #"friendlish:event";
event[#"og:url"] = #"http://www.facebook.com";
event[#"og:description"] = #"Yaba daba doo";
event[#"og:image"] = #"https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png";
action[#"event"] = event;
I get a first error in console before the connection NSLogs are called:
Unsupported FBSDKGraphRequest attachment:{
data = {
};
"fbsdk:create_object" = 1;
"og:description" = "Yaba daba doo";
"og:image" = "https://fbstatic-a.akamaihd.net/images/devsite/attachment_blank.png";
"og:title" = "My Event";
"og:type" = "friendlish:event";
"og:url" = "http://www.facebook.com"; }, skipping.
Then the error from the connection method NSLog:
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL"
UserInfo=0x174077080 {NSLocalizedDescription=unsupported URL,
NSUnderlyingError=0x17445f920 "unsupported URL"}

Related

FBSDKGraphRequest gives error "unsupported URL" while Fetching Event Attending list Facebook iOS

I am getting attending list of Event by this code.
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[[[FBSession activeSession] accessTokenData] accessToken], #"access token",
#"100000000000",#"limit",
nil];
FBSDKGraphRequest *requestA = [[FBSDKGraphRequest alloc] initWithGraphPath:[NSString stringWithFormat:#"%#/attending",[self.dictData objectForKey:#"FBEventId"]] parameters:params HTTPMethod:#"GET"];
FBSDKGraphRequestConnection *connectionA = [[FBSDKGraphRequestConnection alloc] init];
[connectionA addRequest:requestA completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(!error)
{
attending = [[result objectForKey:#"data"] count];
[tblDetail reloadData];
}
else
{
attending = 0;
NSLog(#"error description : %#",error.description);
}
}];
[connectionA start];
This is working fine. But if i call it again, It gives me error,
It seems like, It work only once.
Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo=0x7fe846142280 {NSLocalizedDescription=unsupported URL, NSUnderlyingError=0x7fe843ddcb90 "unsupported URL"}
I have access of these Permissions,
Permission : (
"user_events",
"user_friends",
"rsvp_event",
email,
"publish_actions",
"public_profile"
)
Is it enough to do this action ?
Why this is happening ??
Finally I got solution. Actual problem is in my graph request.
Here is a correct one.
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"100000000000",#"limit",
nil];
FBSDKGraphRequest *requestA = [[FBSDKGraphRequest alloc] initWithGraphPath:[NSString stringWithFormat:#"%#/attending",[self.dictData objectForKey:#"FBEventId"]] parameters:params tokenString:[[[FBSession activeSession] accessTokenData] accessToken] version:#"v2.3" HTTPMethod:self.HTTPGet];
FBSDKGraphRequestConnection *connectionA = [[FBSDKGraphRequestConnection alloc] init];
[connectionA addRequest:requestA completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(!error)
{
attending = [[result objectForKey:#"data"] count];
}
else
{
attending = 0;
NSLog(#"error description : %#",error.description);
}
[tblDetail reloadRowsAtIndexPaths:[NSArray arrayWithObjects:[NSIndexPath indexPathForRow:3 inSection:0], nil] withRowAnimation:UITableViewRowAnimationAutomatic];
}];
[connectionA start];

Post image on facebook using FBSDK 4.x for iOS

For the new Facebook SDK 4.x (4.1) for iOS had new changes with the frameworks . It includes 3 different framework as like
Core
Sharing
Login.
To share any image I used FBSDKSharePhoto Class. But it has method
[FBSDKSharePhoto photoWithImage:(*UIImage) userGenerated:(BOOL)]
I want to add caption with the image as string and text. can Anyone help me for this so I can post caption with the image using FB's new sdk.
Thanks in Advance.
As #NANNAV posted it will work, but if you want to share silently with out any FB Dialog screen then use "shareWithContent" as below, but you need to submit your Facebook app for review.
Code in Obj-c
FBSDKSharePhoto *sharePhoto = [[FBSDKSharePhoto alloc] init];
sharePhoto.caption = #"Test Caption";
sharePhoto.image = [UIImage imageNamed:#"BGI.jpg"];
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = #[sharePhoto];
[FBSDKShareAPI shareWithContent:content delegate:self];
Code in Swift
var sharePhoto = FBSDKSharePhoto()
sharePhoto.caption = "Test"
sharePhoto.image = UIImage(named: "BGI.jpg")
var content = FBSDKSharePhotoContent()
content.photos = [sharePhoto]
FBSDKShareAPI.shareWithContent(content, delegate: self)
Assign your Caption String to caption Key value
#property (nonatomic, copy) NSString *caption;
Try This :
FBSDKSharePhoto *photo = [[FBSDKSharePhoto alloc] init];
photo.image = image;
photo.userGenerated = YES;
photo.caption = #"Add Your caption";
FBSDKSharePhotoContent *content = [[FBSDKSharePhotoContent alloc] init];
content.photos = #[photo];
[FBSDKShareDialog showFromViewController:self
withContent:content
delegate:nil];
Add the below code to share text to facebook using Facebook SDK 4.x
FBSDKGraphRequestConnection *connection =[[FBSDKGraphRequestConnection alloc]init];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"Your_message_here_to_share_FB", #"message",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error){
NSLog(#"Failed to share");
}
else{
NSLog(#"Updated successfully");
}
}];
*Add below code to share photo.
FBSDKGraphRequestConnection *connection =[[FBSDKGraphRequestConnection alloc]init];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys: image, #"picture",
#"Your_text_here",#"message",
nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/photos" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
NSLog(#"Posting the image is success, the result is%#",result);
}
else if(error)
{
NSLog(#"Error occured while posting image %#",error);
}
}];
[connection start];

Publishing Facebook custom story using API calls from IOS app

I need to publish Open Graph story to Facebook wall from my app. I followed current tutorial on Facebook developers.
I've created object,action and story on Facebook dashboard. Then in my app do the following code:
create an object:
NSMutableDictionary<FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object.provisionedForPost = YES;
object[#"title"] = #"test title";
object[#"type"] = #"myapp:my_object_type";
object[#"description"] = #"test discription";
object[#"url"] = #"http://example.com";
object[#"image"] = #[#{#"url": [result objectForKey:#"uri"], #"user_generated" : #"false" }];
and post it:
[FBRequestConnection startForPostOpenGraphObject:object completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSString *objectId = [result objectForKey:#"id"];
NSLog(#"object id %#",objectId);
} else {
NSLog(#"Error posting the Open Graph object to the Object API: %#", error);
}
}];
} else {
NSLog(#"Error staging an image: %#", error);
}
}];
Got object id as result.
Then create an action and link it with object:
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:objectId forKey:#"my_object_type"];
FBOpenGraphActionParams *params = [[FBOpenGraphActionParams alloc] init];
params.action = action;
params.actionType = #"myapp:my_app_action";
And post it to Facebook:
[FBRequestConnection startForPostWithGraphPath:#"/me/myapp:my_app_action" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"OG story posted, story id: %#", [result objectForKey:#"id"]);
[[[UIAlertView alloc] initWithTitle:#"OG story posted"
message:#"Check your Facebook profile or activity log to see the story."
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil] show];
} else {
NSLog(#"Encountered an error posting to Open Graph: %#", error);
}
}];
As a result i got the message that OG story was successfully posted, but when going to Facebook, there is nothing in feed or timeline, just an image added to users photo album.
Well, dunno what was the problem, but now it works with the following code:
FBRequestConnection *connection = [[FBRequestConnection alloc]init];
NSMutableDictionary <FBOpenGraphObject> *object = [FBGraphObject openGraphObjectForPost];
object[#"type"] = #"myapp:my_object_type";
object[#"title"] = #"title";
object[#"url"] = #"http://example.com";
object[#"image"] = #"http://image.png";
object[#"description"] = #"description";
FBRequest *objectRequest = [FBRequest requestForPostOpenGraphObject:object];
[connection addRequest:objectRequest completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(#"Error: %#",error.description);
}
} batchEntryName:#"objectCreate"];
NSMutableDictionary <FBOpenGraphAction> *action = [FBGraphObject openGraphActionForPost];
action[#"buy"] = #"{result=objectCreate:$.id}";
action[#"fb:explicitly_shared"] = #"true";
FBRequest *actionRequest = [FBRequest requestForPostWithGraphPath:#"me/myapp:my_app_action" graphObject:action];
[connection addRequest:actionRequest completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(#"error: %#",error.description);
} else {
NSLog(#"posted with id %#", result[#"id"]);
}
}];
[connection start];

Facebook API: Unknown fields: name?

My request:
<FBRequestConnection: 0x93a8ba0, 1 request(s):(
<FBRequest: 0x9395c90, session: 0xa8aeb80, graphPath: https://graph.facebook.com/me, HTTPMethod: GET, parameters:
{
"access_token" = BAAG4P63ZBHK0BAObimWrMZCGOzn3s6qOtqynyzkJmIN0fKiKGlCkmlqlKMcpbvrrhN9QJsIxrTc7PZCFoceuCwAC2ygCph27WV72iwxkbi2svKCDemDo8BBqOwc6bp6DQH7U9tjp4gZBofb4brYg;
fields = name;
format = json;
"migration_bundle" = "fbsdk:20120913";
sdk = ios;
})>
My response:
result (null)
error Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x93b1ad0 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) Unknown fields: name.";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
What is the reason behind?
If I send without fields = name; then I get back some default user data.
Invoking:
FBRequest *graphRequest = [[FBRequest alloc] initWithSession:[FBSession activeSession]
graphPath:request.graphPath
parameters:request.parameters
HTTPMethod:request.httpMethod];
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:graphRequest
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
[self requestCompleted:connection result:result error:error];
}];
[connection start];
Request object:
-(NSString*)graphPath
{ return #"https://graph.facebook.com/me"; }
-(NSDictionary*)parameters
{
return [NSDictionary dictionaryWithObjectsAndKeys:
#"name", #"fields",
nil];
}
-(NSString*)HTTPMethod
{
return #"GET";
}
Have tried with fixed parametes as well, no effect:
graphRequest = [[FBRequest alloc] initWithSession:[FBSession activeSession]
graphPath:#"https://graph.facebook.com/me"
parameters:[NSDictionary dictionaryWithObjectsAndKeys:#"name", #"fields", nil]
HTTPMethod:#"GET"];
Graph path must be relative.
Now I use only #"me" instead of #"https://graph.facebook.com/me", and works like a charm.

Facebook Batch Photo Upload iOS

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

Resources