I have implement a script to get list friends in my facebook include image, username....
But when it load to viewcontroller ( uitableview ) list friends has return but the tableview be block scrolling, please help
'- (void)getFriendsListWithCompleteBlock:(void (^)(NSArray *, NSString *))completed{
if (!FBSession.activeSession.isOpen)
{
NSLog(#"permissions::%#",FBSession.activeSession.permissions);
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info", #"user_friends"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
else if (session.isOpen)
{
[self showWithStatus:#""];
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,gender"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSArray *data = [result objectForKey:#"data"];
NSMutableArray *friendsList = [[NSMutableArray alloc] init];
for (FBGraphObject<FBGraphUser> *friend in data)
{
//NSLog(#"friend:%#", friend);
NSDictionary *picture = [friend objectForKey:#"picture"];
NSDictionary *pictureData = [picture objectForKey:#"data"];
//NSLog(#"picture:%#", picture);
FBData *fb = [[FBData alloc]
initWithData:(NSString*)[friend objectForKey:#"name"]
userID:(NSInteger)[[friend objectForKey:#"id"] integerValue]
gender:(NSString*)[friend objectForKey:#"gender"]
photoURL:(NSString*)[pictureData objectForKey:#"url"]
photo:(UIImage*)nil
isPhotoDownloaded:(BOOL)NO];
[friendsList addObject:fb];
}
NSString *message;
if (friendsList.count <1) {
message = #"Not Founds";
}
[self dismissStatus];
dispatch_async(dispatch_get_main_queue(), ^{
if (completed) {
completed(friendsList,message);
}
});
}];
}
}];
}
}
'
Related
I am new in iOS Development, I am trying to do get Details of User from Facebook. Here is my code which i am used but when it called my app is hang. In below code it can not worked when i can not Login with device in Facebook in Setting>Facebook. Please help me for this.
-(Void)LoginWithFB {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
SLComposeViewController *vc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
id options = #{
ACFacebookAppIdKey: #"1501842240102594",
ACFacebookPermissionsKey: #[ #"email"],
};
[accountStore requestAccessToAccountsWithType:facebookAccountType
options:options
completion:^(BOOL granted, NSError *error) {
if (granted)
{
// Return back logined facebook Account
ACAccount *fbAccount = [[accountStore accountsWithAccountType:facebookAccountType] lastObject];
// Do What you want...
// Request friend list
//http://graph.facebook.com/000000000/picture
SLRequest *friendsListRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL: [[NSURL alloc] initWithString:#"https://graph.facebook.com/me"]parameters:nil];
friendsListRequest.account = fbAccount;
[friendsListRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
// Parse response JSON
NSError *jsonError = nil;
NSDictionary *dictionaryForFacebookData = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments
error:&jsonError];
// NSString *proficePicture = [NSString stringWithFormat:#"http://graph.facebook.com/415790901901979/picture"];
NSMutableDictionary *dictionaryParameter = [[NSMutableDictionary alloc]init];
[dictionaryParameter setObject:#"facebook" forKey:#"registrationsource"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"first_name"] forKey:#"firstname"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"last_name"] forKey:#"lastname"];
[dictionaryParameter setObject:[dictionaryForFacebookData objectForKey:#"email"] forKey:#"email"];
[dictionaryParameter setObject:#"yes" forKey:#"status"];
WebServiceClass *objectToCallApi = [[WebServiceClass alloc]init];
NSDictionary *dictionaryReturnValue = [objectToCallApi callAPIWebservice:dictionaryParameter stringURL:[[Singelton sharedInstance] passMethodName:#"login"]];
if (![[dictionaryReturnValue objectForKey:#"success"] isEqualToString:#"1"])
{
[UIAlertView showWithTitle:ALERT_TITLE message:[dictionaryReturnValue objectForKey:#"message"] handler:^(UIAlertView *alertview, NSInteger buttonindex){
}];
}
if ([[dictionaryReturnValue objectForKey:#"success"] isEqualToString:#"1"])
{
APP_DELEGATE.intTabbarNumber = 0;
NSMutableDictionary *data =[[NSMutableDictionary alloc]init];
[data setObject:[NSString stringWithFormat:#"%# %#",[dictionaryReturnValue objectForKey:#"firstname"], [dictionaryReturnValue objectForKey:#"lastname"]] forKey:#"fullname"];
[data setObject:dictionaryReturnValue[#"username"] forKey:#"username"];
[data setObject:dictionaryReturnValue[#"email"] forKey:#"email"];
[data setObject:dictionaryReturnValue[#"userid"] forKey:#"userid"];
NSMutableArray *arrayOfExistingUser;
if([[NSUserDefaults standardUserDefaults] valueForKey:#"Users"] != nil)
{
arrayOfExistingUser = [[[NSUserDefaults standardUserDefaults] valueForKey:#"Users"] mutableCopy];
for (int i=0; i<arrayOfExistingUser.count; i++)
{
if ([[[arrayOfExistingUser objectAtIndex:i]objectForKey:#"userid"] isEqualToString:[data objectForKey:#"userid"]])
{
[arrayOfExistingUser removeObjectAtIndex:i];
}
}
}
else
{
arrayOfExistingUser = [[NSMutableArray alloc]init];
}
[arrayOfExistingUser addObject:data];
[[NSUserDefaults standardUserDefaults] setObject:arrayOfExistingUser forKey:#"Users"];
[[NSUserDefaults standardUserDefaults] synchronize];
[[NSUserDefaults standardUserDefaults]setObject:dictionaryReturnValue forKey:#"dictionaryForLoginData"];
if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"teacher"])
{
[APP_DELEGATE createTabbarInstanceForTeacher];
}
else if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"student"])
{
[APP_DELEGATE createTabbarInstanceForstudent];
}
else if ([[dictionaryReturnValue objectForKey:#"role"] isEqualToString:#"parent"])
{
[APP_DELEGATE createTabbarInstanceForParent];
}
}
}];
}
else
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller.view resignFirstResponder];
controller.view.hidden = YES;
[self presentViewController:controller animated:NO completion:nil];
}
}];
}
in .h file
#import <Accounts/Accounts.h>
#import <Social/Social.h>
#property (nonatomic, strong) ACAccountStore *accountStore;
#property (nonatomic, strong) ACAccount *facebookAccount;
in .m file
- (void) getuserdetails
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= nil;
//[self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
if (! FBaccountType) {
FBaccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSString *key =kFBAppId;
NSDictionary *dictFB = [NSDictionary dictionaryWithObjectsAndKeys:key,ACFacebookAppIdKey,#[#"email"],ACFacebookPermissionsKey, nil];
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:dictFB completion:
^(BOOL granted, NSError *e)
{
if (granted)
{
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
self.facebookAccount = [accounts lastObject];
NSLog(#"facebook account =%#",self.facebookAccount);
[self get];
}
else
{
NSLog(#"fb error %#",e.description);
dispatch_async(dispatch_get_main_queue(), ^
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"%#",e.description);
if([e code]== ACErrorAccountNotFound)
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Account not found"
message:msgSetUpFBAccount delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
else
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:msgFBAccessDenied
message:#"" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
});
NSLog(#"error getting permission %#",e);
}
}];
}
-(void)get
{
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.facebookAccount;
[request performRequestWithHandler:^(NSData *data,
NSHTTPURLResponse *response,
NSError *error)
{
if(!error)
{
list =[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"Dictionary contains: %#", list );
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else
{
[self performSelectorOnMainThread:#selector(hideLoader) withObject:nil waitUntilDone:YES];
NSLog(#"error from get%#",error);
}
}];
}
-(void)attemptRenewCredentials{
[self.accountStore renewCredentialsForAccount:(ACAccount *)self.facebookAccount completion:^(ACAccountCredentialRenewResult renewResult, NSError *error){
if(!error)
{
switch (renewResult) {
case ACAccountCredentialRenewResultRenewed:
NSLog(#"Good to go");
[self get];
break;
case ACAccountCredentialRenewResultRejected:
{
NSLog(#"User declined permission");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"You declined permission" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
case ACAccountCredentialRenewResultFailed:
{
NSLog(#"non-user-initiated cancel, you may attempt to retry");
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
message:#"non-user-initiated cancel, you may attempt to retry" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
break;
}
default:
break;
}
}
else{
//handle error gracefully
NSLog(#"error from renew credentials%#",error);
}
}];
}
In your method signature - (Void)LoginWithFB; Void is not a type but void is. So that might be the problem.
I want to get Facebook friends in my project. I have tried the FBFriendPicker Method, but I can't get the friends. It shows empty list to me.
Here is my code.
- (IBAction)pickFriendsButtonClick:(id)sender {
if (!FBSession.activeSession.isOpen) {
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"user_friends"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
} else if (session.isOpen) {
[self pickFriendsButtonClick:sender];
}
}];
return;
}
if (self.friendPickerController == nil) {
// Create friend picker, and get data loaded into it.
self.friendPickerController = [[FBFriendPickerViewController alloc] init];
self.friendPickerController.title = #"Pick Friends";
self.friendPickerController.delegate = self;
}
[self.friendPickerController loadData];
[self.friendPickerController clearSelection];
[self presentModalViewController:self.friendPickerController animated:YES];
}
Try This...
-(IBAction)btnFacebookClick:(id)sender
{
NSArray *permissions = [[NSArray alloc] initWithObjects: #"user_about_me,user_birthday,user_hometown,user_location,email",#"read_mailbox",#"read_stream",nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState status,NSError *error)
{
if(error)
{
NSLog(#"session error %#",error);
}
else if(FB_ISSESSIONOPENWITHSTATE(status))
{
[self getFriendList];
}
}];
}
-(void)getFriendList
{
FBRequest *friendsRequest=[FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler:^(FBRequestConnection *connection,NSDictionary* result,NSError *error)
{
friendsArr = [result objectForKey:#"data"];
NSLog(#"friends description :%#",[friendsArr description]);
}];
}
Try this code for get facebook friends....
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
friendsRequest.session = FBSession.activeSession;
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %lu friends", (unsigned long)friends.count);
for (NSDictionary<FBGraphUser>* friend in friends)
{
NSLog(#"I have a friend named %# ", friend.name);
}
}];
Please try below code :
[FBSession openActiveSessionWithReadPermissions:#[#"email"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (error) {
// Handle errors
[self handleAuthError:error];
}
else
{
// Check for publish permissions
FBRequest *req = [FBRequest requestForMyFriends];
[req startWithCompletionHandler:^(FBRequestConnection *connection,NSDictionary *result,NSError *error){
NSLog(#"Result:- %#",[result objectForKey:#"data"]);
}];
}
}];
With the new API version v2.0, you cannot get the complete list of friends just with user_friends. Your picker must be using /me/friends which will give you the list of friends using that app. So in your case none of your friends be using this app and that's why you are getting a blank response.
To get the complete list of friends you should use /me/taggable_friends API. But note that this permission needs to be reviewed first by facebook before you go live. See this answer for more info for using this permission.
I'm trying to get FaceBook Friend list , and display it in custom view like "foresqure App"
what I mean "foursquare" ask for the permission and to post on your wall inside the app without leaving the app to the browser or to the app Facebook ? after that the app get all friends and display it in custom tableView.
here what I tried :
if (!FBSession.activeSession.isOpen) {
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"user_friends"]
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
} else if (session.isOpen) {
//[self pickFriendsButtonClick:sender];
NSLog(#"aaaa");
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
}
}];
}
In this case it will open the safari to ask for permision not inside the app and friend array allows nill or count = 0.
Try this code ..
Firstly call this method like this ..
[self FBFriendList];
And add this two methods.
-(void)FBFriendList
{
if (!FBSession.activeSession.isOpen)
{
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else if(session.isOpen)
{
[self FBFriendList];
[self fb_frnd_use_this_app];
}
}];
return;
}
}
-(void)fb_frnd_use_this_app
{
FBRequest *request = [FBRequest requestWithGraphPath:#"me/friends"
parameters:#{#"fields":#"name,installed,first_name,picture"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
NSLog(#"%#",result);
int count = 0;
NSMutableArray *frnd_arr = [result objectForKey:#"data"];
for (int i = 0; i < [frnd_arr count]; i++)
{
NSLog(#"%#",frnd_arr);
count++;
}
NSLog(#"%#",app.Arr_Facebook_Frnd);
app.fbfriendCount =[NSString stringWithFormat:#"%d",count];
}];
}
Hope this code is useful for you.
Hi I am using facebook SDK 3.8 in my project. and using HelloFaceBookSample Code in my app but in my app i have no login button of facebook. I have implemented login flow of facebook and after login i have post on facebook. Now Post Status working fine but when i post image on facebook it give me error of
an attempt was made reauthorize permissions on an unopened session in ios
Code :
-(void) clickButtonFacebookUsingSDK
{
if (!appdelegate.session.isOpen)
{
appdelegate.session = [[FBSession alloc] init];
[appdelegate.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if(appdelegate.session.isOpen)
{
NSLog(#"calling postdata when session is not open******");
[self postData];
}
}];
}
else
{
NSLog(#"calling postdata when session is open******");
[self postData];
}
}
-(void) postData
{
[self showingActivityIndicator];
UIImage *img = [UIImage imageNamed:#"abc.jpg"];
[self performPublishAction:^{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
connection.errorBehavior = FBRequestConnectionErrorBehaviorReconnectSession
| FBRequestConnectionErrorBehaviorAlertUser
| FBRequestConnectionErrorBehaviorRetry;
FBRequest *req = [FBRequest requestForUploadPhoto:img];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:message3, #"message", nil]];
[connection addRequest:req
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [self showAlert:#"Photo Post" result:result error:error];
[self showAlert:#"Photo Post" result:result resulterror:error];
if (FBSession.activeSession.isOpen) {
}
}];
[connection start];
}];
}
- (void) performPublishAction:(void (^)(void)) action {
// we defer request for permission to post to the moment of post, then we check for the permission
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// if we don't already have the permission, then we request it now
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
// UIAlertView helper for post buttons
- (void)showAlert:(NSString *)message result:(id)result resulterror:(NSError *)error
{
NSString *alertMsg;
NSString *alertTitle;
if (error)
{
alertTitle = #"Error";
// Since we use FBRequestConnectionErrorBehaviorAlertUser,
// we do not need to surface our own alert view if there is an
// an fberrorUserMessage unless the session is closed.
if (FBSession.activeSession.isOpen) {
alertTitle = #"Error";
} else {
// Otherwise, use a general "connection problem" message.
alertMsg = #"Operation failed due to a connection problem, retry later.";
}
}
else
{
NSDictionary *resultDict = (NSDictionary *)result;
alertMsg = [NSString stringWithFormat:#"Successfully posted '%#'.", message];
NSString *postId = [resultDict valueForKey:#"id"];
if (!postId) {
postId = [resultDict valueForKey:#"postId"];
}
if (postId) {
alertMsg = [NSString stringWithFormat:#"%#\nPost ID: %#", alertMsg, postId];
}
alertTitle = #"Success";
}
if (alertTitle) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:alertTitle
message:alertMsg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[self dismissActivityIndicator];
}
}
it gives me error in performPublishAction method.
can anyone tell me what is the problem . i have a lot of search and also found many solution but no one work. Please help. Thanks in advance.
I think that you have to set to FBSession what is its active session :
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
HI Im trying to enable a IBAction to post on an user's timeline while they have an active section. I am getting an error message stating; Implicit declaration of function "x" is invalid C99. I been reading posts about the issue but no luck and honestly I am not sure if I am doing this right at all. I updated the permissions on my fb app and got the object code from the Graph API Explorer but I dont know if Im implementing it right on my code.
Here is my post method:
-(void) aPost
{
NSMutableDictionary<FBGraphObject> *object =
[FBGraphObject openGraphObjectForPostWithType:#"website"
title:#"CR Taxi APP"
image:#"http://a4.mzstatic.com/us/r1000/047/Purple4/v4/05/cc/f2/05ccf23f-a409-1e73-a649-a5e6afc4e6eb/mzl.llffzfbp.175x175-75.jpg"
url:#"https://itunes.apple.com/cr/app/cr-taxi/id674226640?mt=8"
description:#"La nueva aplicaciĆ³n para llamar taxis!"];;
[FBRequestConnection startForPostWithGraphPath:#"{id_from_create_call}"
graphObject:object
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
// handle the result
}];
}
and this is my action method
- (IBAction)publishAction:(id)sender {
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *writepermissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
#"publish_actions",
nil];
[[FBSession activeSession]requestNewPublishPermissions:writepermissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *aSession, NSError *error){
if (error) {
NSLog(#"Error on public permissions: %#", error);
}
else {
**not on the code //( error on this one) aPost(aSession, error);
}
}];
}
else {
// If permissions present, publish the story
**not on the code //(not an error on this one) aPost(FBSession.activeSession, nil);
}
}
Please help!
Thank you!
I'd guess the compiler error is actually "Implicit declaration of function 'aPost' is invalid C99", although the formatting of your action method code is wonky as written. The compiler is only going to produce that error message the first time it encounters the function call to aPost.
aPost is written as a method that has no return and takes no arguments. You are trying to call it as a C function, passing it two arguments, which the compiler interprets as an entirely new function. As aPost is written with all the hard-coded strings, you probably just want to change the calls to aPost(arg1, arg2); to [self aPost]; (provided aPost and publishAction are in the same class).
Try this: might helps you
//Write This Line in your ViewController.h File
#property (strong, nonatomic) NSMutableDictionary *postParams;
//in View Controller.m File
- (void)viewDidLoad
{
self.postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
[UIImage imageNamed:#"Default.png"], #"picture",
#"Facebook SDK for iOS", #"name",
#"build apps.", #"caption",
#"testing for my app.", #"description",
nil];
[self.postParams setObject:#"hgshsghhgsls" forKey:#"message"];
}
- (IBAction)SharePressed:(id)sender {
#try {
[self openSession];
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists",#"read_stream", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
if (![session isOpen]) {
[self openSession];
}
}];
[FBRequestConnection startWithGraphPath:#"me/feed" parameters:self.postParams HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,id result,NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:#"error: domain = %#, code = %d, des = %#",error.domain, error.code,error.description];
}
else
{
alertText=#"Uploaded Successfully";
[self ResetAllcontent];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result" message:alertText delegate:self cancelButtonTitle:#"OK!"
otherButtonTitles:nil]show];
}];
}
#catch (NSException *exception) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"Please Login" message:#"For Sharing on facbook please login with facbook" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:nil, nil];
[alert show];
}
#finally {
}
}
- (void)openSession
{
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication]delegate];
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[appDelegate sessionStateChanged:session state:state error:error];
}];
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) &&
(accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (fbAccounts && [fbAccounts count] > 0 &&
(account = [fbAccounts objectAtIndex:0])){
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
}
}
//=====in your plist file do
URLTypes=>Item 0=> URL Schemes =>Item 0=>fbyourfacebookId
FacebookAppID-your facebookID
And yes dont forget to create facebook id at developer.facebook.com
and also give permissions as your need
- (IBAction)shareViaFacebook:(id)sender {
if (FBSession.activeSession.isOpen) {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"%#. Join on Linute.",self.userNameLabel.text], #"name",
//#"Build great social apps and get more installs.", #"caption",
locationString, #"description",
//#"http://www.linute.com/", #"link",
eventPicString, #"picture",//imageURL
nil];
// Make the request
[FBRequestConnection startWithGraphPath:#"/me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Link posted successfully to Facebook
NSLog(#"result: %#", result);
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"%#", error.description);
}
}];
}else{
FBSession *session = [[FBSession alloc] initWithPermissions:#[#"public_profile", #"email",#"user_friends",#"publish_actions"]];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (FBSession.activeSession.isOpen) {
[self shareViaFacebook:nil];
}else{
[self shareViaFacebook:nil];
}
}];
}