I need to make a post on a my own fanpage as the admin.
I created this code hopping that passing the id of the page "fbPageID" would leave the post on that page, but it actually leaves the post on my profile.
NSArray *publishPerms = #[#"manage_pages",#"publish_actions", #"publish_stream"];
[FBSession openActiveSessionWithPublishPermissions:publishPerms defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:NO completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (session.isOpen) {
[FBRequestConnection startForPostStatusUpdate:self.textBox.text place:fbPageID tags:nil completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error){
NSLog(#"error %#",error);
}
else{
NSLog(#"POSTED %#",result);
}
}];
}
else{
NSLog(#"session not open");
}
This is helpfull for Post on user Facebook..
Step 1 - Import FBSDK in your project
Step 2 - Login Authentication
NSDictionary *params = #{
#"message": #"This is a test message",
};
/* make the API call */
FBSDKGraphRequest *request_ = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"];
[request_ startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
// Handle the result
}];
Related
I am using Facebook SDK in my iPhone app. I want to find the user's Facebook profile photos, for that I am using the below code:
-(IBAction)FacebookLogin:(id)sender{
if (FBSession.activeSession.isOpen) {
[self findAlbums];
} else {
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_photos",
nil];
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
[self findAlbums];
}
}];
}
}];
}
}
-(void)findAlbums {
[FBRequestConnection startWithGraphPath:#"/me/albums"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
NSLog(#"result::%#",result);
}];
}
Out put ---- data = ( );
This does not give any albums in data. The Facebook user logged in have many albums and photos in his profile. Why this happens?
just change the code in find albums to :
[FBRequestConnection startWithGraphPath:#"me/albums"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Success! Include your code to handle the results here
NSLog(#"user events: %#", result);
NSArray *feed =[result objectForKey:#"data"];
for (NSDictionary *dict in feed) {
NSLog(#"first %#",dict);
}
} else {
// An error occurred, we need to handle the error
// Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
NSLog(#"error %#", error.description);
}
}];
you have to add the Facebook credentials(i.e facebook account) you're using to the Facebook developer account settings(i.e as admin or developer) , only then you can access the album's photos through your code
I am trying to develop a simple app, which, retrieves data from Facebook, when the user connects to it.
I tried this code for it.
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_birthday",#"user_hometown",#"user_location",#"email",#"basic_info", nil];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", [result objectForKey:#"gender"]);
NSLog(#"%#", [result objectForKey:#"hometown"]);
NSLog(#"%#", [result objectForKey:#"birthday"]);
NSLog(#"%#", [result objectForKey:#"email"]);
}];
But when I run this code, it gives an error "FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint."
Thanks in advance, really appreciate your help.
The error is very appropriate, what it is trying to say is that request connection method should be called once the session is open.
Now your
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
method returns BOOL value true or false to specify you wether session is open or not(it tries to open synchronously). So first check the result of this call and the put it inside the code for fetching info. For eg.
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"%#", [result objectForKey:#"gender"]);
NSLog(#"%#", [result objectForKey:#"hometown"]);
NSLog(#"%#", [result objectForKey:#"birthday"]);
NSLog(#"%#", [result objectForKey:#"email"]);
}];
}
This should remove your error, but you still may not get the results.You may or may not get result on the very first call to this code but whenever the code for completion handler will be called, this method FBRequestConnection will also get called and at that time you'll get the results as it is an asynchronous call.
If it still doesn't work try this
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error)
{
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSLog(#"FB user first name:%#",user.first_name);
NSLog(#"FB user last name:%#",user.last_name);
NSLog(#"FB user birthday:%#",user.birthday);
}
}];
`(void)fbAccountConfigureWithBlock:(void (^)(id, NSString *))block
{
_block_data=block;
if(![SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"Please go to settings and add at least one facebook account."];
_block_data(nil,nil);
});
return;
}
ACAccountStore *store = [[ACAccountStore alloc]init];
ACAccountType *accountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[store requestAccessToAccountsWithType:accountType
options:#{ACFacebookAppIdKey : FacebookAppId,
ACFacebookAudienceKey : ACFacebookAudienceFriends,
ACFacebookPermissionsKey : #[#"email"]}
completion:^(BOOL granted, NSError *error)
{
if(granted){
NSArray *array = [store accountsWithAccountType:accountType];
if(!array.count){
dispatch_sync(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"Please go to settings and add at least one facebook account."];
_block_data(nil,nil);
});
}
else{
ACAccount *account = array[0];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://graph.facebook.com/me"]
parameters: #{#"fields":#"id,first_name,last_name,name,email,picture.height(180).width(180)"}];
[request setAccount:account];
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if(!error){
NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSLog(#"Facebook user data ----> %#",userData);
dispatch_async(dispatch_get_main_queue(), ^{
if(userData[#"error"] != nil)
[self attemptRenewCredentials:store account:account];
else
_block_data(userData,nil);
});
}
else{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:error.localizedDescription];
_block_data(nil,nil);
});
}
}];
}
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlertMessage:#"" message:#"We need permission to access your facebook account in order make registration."];
_block_data(nil,nil);
});
}
}];
}`
This is the most easy and simple code I have used to upload images to Facebook it works perfectly on my simulator and on my device in testing phase. But when I published my app to iTunes it 80% got crash and 20% made success to upload image to facebook. Why this is happening ?
Xcode shows warning that "openActiveSessionWithPermissions is deprecated"
if (FBSession.activeSession.isOpen)
{
[self UploadToFb];
}
else // Take permissions
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
[self controlStatusUsable:NO];
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason
if (error) {
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
[self UploadToFb];
}
}];
}
}];
}
After taking Permissions from user Upload image to Facebook
-(void)UploadToFb
{
[FBRequestConnection startForUploadPhoto:myImg.image
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
{
[FBRequestConnection startForUploadPhoto:myImg.image
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"Uploaded");
}
else
{
NSLog(#"Error");
}
}];
}
else
{
NSLog(#"Error");
}
}];
}
I wrote following code for uploading video to facebook from iOS device.
-(void)uploadVideo {
NSLog(#"UPload Videio ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSLog(#"Path is %#", filePath);
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];
if (FBSession.activeSession.isOpen) {
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error) {
NSLog(#"OK: %#", result);
} else
NSLog(#"Error: %#", error.localizedDescription);
}];
} else {
// We don't have an active session in this app, so lets open a new
// facebook session with the appropriate permissions!
// Firstly, construct a permission array.
// you can find more "permissions strings" at http://developers.facebook.com/docs/authentication/permissions/
// In this example, we will just request a publish_stream which is required to publish status or photos.
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
//[self controlStatusUsable:NO];
// OPEN Session!
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"VEEERRRRRRR: %#", result);
} else
NSLog(#"VVEEERRRRREEEERRR: %#", error.localizedDescription);
}];
//[self promptUserWithAccountNameForUploadPhoto];
}
// [self controlStatusUsable:YES];
}];
}
}
This gives me error
The operation couldn’t be completed. (com.facebook.sdk error 5.)
I don't know what is wrong with facebook. It uploads image, text, but in video it gives this error.
NOTE:
It is not due to send again and again, as I also tested by making new account and resetting iOS Device.
sample.mov also exists and works with graph api, but issue is with this SDK.
Thanks.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.
more here... ?
Having read this solution. I was able solve this problem.
[FBRequestConnection startWithGraphPath:#"me/videos"
completionHandler:^(FBRequestConnection *connection,
id result, NSError *error)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"SUCCESS RESULT: %#", result);
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}];
I was having this problem all day when I noticed that my app does not appear in:
Settings App->Facebook->"ALLOW THESE APPS TO USE YOUR ACCOUNT"
This made me realize that posting to Facebook is not permitted by default, you must prompt the user for their permission:
[[FBSession activeSession] requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error)
{
// UPLOAD VIDEO HERE AND THAT ERROR 5 SHOULD GO AWAY
}
}];
I currently have a problem with my iOS application because I don't seem to be able to send requests to people...
Here is the code that I have:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
if([FBSession activeSession].isOpen) {
[FBWebDialogs presentRequestsDialogModallyWithSession:[FBSession activeSession] message:#"Join me." title:#"Invite" parameters:params handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
NSLog(#"%#", [FBSession activeSession]);
if (error)
NSLog(#"Error sending request.");
else {
if (result == FBWebDialogResultDialogNotCompleted)
NSLog(#"User canceled request.");
else if(result == FBWebDialogResultDialogCompleted)
NSLog(#"Request: %#", resultURL);
else
NSLog(#"Error unknown.");
}
}];
}
else {
[FBSession openActiveSessionWithReadPermissions:#[#"email"] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if(session.isOpen) {
[FBSession openActiveSessionWithPublishPermissions:#[#"publish_actions"] defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if(session.isOpen) {
[self showRequestForFacebook];
}
}];
}
}];
}
Every time I get a Request: (null). I get a request ID but nothing on the account. I looked at the sample in the Facebook SDK and I seem to have exactly the same. However, it works with the sample and not with my code.
Is there anything to change somewhere? Is it something on developers.facebook.com?
Edit: I forgot to say that in the same application I use a SLComposeViewController to share on Facebook and it works perfectly.
Thanks a lot! :)
NSString *query2 = [NSString stringWithFormat:#"SELECT uid, name, pic_square,is_app_user FROM user WHERE is_app_user = 1 AND uid IN " #"(SELECT uid2 FROM friend WHERE uid1 = me())"];
// Set up the query parameter
NSDictionary *queryParam2 = #{ #"q": query2 };
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql" parameters:queryParam2 HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error) {
} else {
// NSLog(#"Result: %#", result);
// Get the friend data to display
NSArray *friendInfo = (NSArray *) result[#"data"];
NSLog(#"%#",friendInfo);
self.data=friendInfo;
[self constructDictionaryOfNumbers];
// Show the friend details display
}
}];
}