I am trying the facebook integration for the first time. I am confused of many codes i am able to get from different tutorial sites.
I have used the following code to fetch user information from facebook data but i am not able to get the data using storyboard. Can someone suggest what is wrong with this code??
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL wasHandled = [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
return wasHandled;
}
The following code paragraph under here is not getting excecuted. So is there some other way to get the control into this code??
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
regisrationdetails.fbid = user.id;
regisrationdetails.firstname = user.first_name;
}
Rest everything i tried different types to call it but its not happening.
- (void)loginView:(FBLoginView *)loginView
handleError:(NSError *)error {
NSString *alertMessage, *alertTitle;
if (error.fberrorShouldNotifyUser) {
alertTitle = #"Facebook Error";
alertMessage = error.fberrorUserMessage;
} else if (error.fberrorCategory == FBErrorCategoryAuthenticationReopenSession) {
alertTitle = #"Session Error";
alertMessage = #"Your current session is no longer valid. Please log in again.";
} else if (error.fberrorCategory == FBErrorCategoryUserCancelled) {
NSLog(#"user cancelled login");
} else {
alertTitle = #"Unknown Error";
alertMessage = #"Error. Please try again later.";
NSLog(#"Unexpected error:%#", error);
}
if (alertMessage) {
[[[UIAlertView alloc] initWithTitle:alertTitle
message:alertMessage
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
}
}
- (void)viewDidLoad
{
[FBLoginView class];
FBLoginView *loginView = [[FBLoginView alloc] init];
loginView.readPermissions= #[#"email", #"user_likes"];
loginView.publishPermissions = #[#"publish_actions"];
loginView.defaultAudience = FBSessionDefaultAudienceFriends;
FBSession *session = [[FBSession alloc] init];
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
[FBRequestConnection startForMeWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
regisrationdetails.firstname = [result objectForKey:#"name"];
}
}];
NSLog(#"%#", regisrationdetails.firstname);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
if (!error) {
regisrationdetails.firstname = user.name;
regisrationdetails.address1 = user.location[#"name"];
regisrationdetails.city = user[#"city"];
}
}];
- (IBAction)CreateAccount:(id)sender
{
regisrationdetails.firstname=_FirstName.text;
regisrationdetails.lastname=_LastName.text;
regisrationdetails.email=_EmailAddress.text;
regisrationdetails.address1=_Address1.text;
regisrationdetails.address2=_Address2.text;
regisrationdetails.city=_City.text;
regisrationdetails.state=_State.text;
regisrationdetails.zip=_Zip.text;
NSURL *url = [[NSURL alloc]initWithString:[NSString stringWithFormat:#"%#first_name=%#&last_name=%#&email=%#&address_1=%#&address_2=%#&city=%#&state=%#&zip=%#&&fb_id=%#&action=fbsignin",MainURL, regisrationdetails.firstname,regisrationdetails.lastname,regisrationdetails.email,regisrationdetails.address1,regisrationdetails.address2,regisrationdetails.city,regisrationdetails.state,regisrationdetails.zip,regisrationdetails.fbid ]];
NSError *errors;
NSData *data = [NSData dataWithContentsOfURL:url];
NSDictionary *json = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&errors];
status = json[#"status"];
error = json[#"error"];
user = json[#"user"];
if ([status isEqualToString:#"success"])
{
UIAlertView *success=[[UIAlertView alloc]initWithTitle:#"Success" message:nil delegate:self cancelButtonTitle:#"Close" otherButtonTitles:nil];
[success show];
}
else if ([status isEqualToString:#"failure"])
{
messages=[[NSString alloc]init];
for (int i=0; i<[error count]; i++)
{
messages=[messages stringByAppendingString:[error objectAtIndex:i]];
messages=[messages stringByAppendingString:#"\n"];
}
UIAlertView *failure=[[UIAlertView alloc]initWithTitle:#"Failure" message:messages delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[failure show];
}
}
Is there a simple sample code available to fetch the facebook user information using storyboard??
Make sure you have implement facebook delegate methods,
fbLoginview.delegate = self;
And implement this method to get user information
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user {
// here we use helper properties of FBGraphUser to dot-through to first_name and
// id properties of the json response from the server; alternatively we could use
NSLog(#"user :%#",user);
}
Related
I am trying to login a user through facebook in my parse.com app. I have all the ids and appdelegate methods in place.
I have created a view in the storyboard and made that a facebook login button and then i have connected it to my .h file as a IBAction.
my code:
- (IBAction)fblogin:(FBSDKLoginButton *)sender {
[PFFacebookUtils logInInBackgroundWithReadPermissions:#[#"public_profile", #"email"] block:^(PFUser *user, NSError *error) {
if (error) {
// NSLog(#"Uh oh. The user cancelled the Facebook login.");
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
} else if (!user) {
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:#"You cancelled Login, try again!" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
}else {
// NSLog(#"User logged in through Facebook!");
// [self dismissViewControllerAnimated:YES completion:NULL];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"first_name, last_name, email, public_profile"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
} else if ([[error userInfo][#"error"][#"type"] isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
// NSLog(#"The facebook session was invalidated");
[PFFacebookUtils unlinkUserInBackground:[PFUser currentUser]];
}
else {
NSDictionary *userData = (NSDictionary *)result;
// [self requestFacebookUser:user];
NSString *name = userData[#"name"];
NSString *email = userData[#"email"];
user.username = name;
user.email = email;
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertVeiw show];
}
else {
// [self dismissViewControllerAnimated:NO completion:nil];
//[self.navigationController popToRootViewControllerAnimated:NO];
[self performSegueWithIdentifier:#"inbox" sender:self];
}
}];
}
}];
}
}];
}
The faccebook web page opens when i press login facebook button then we sign in and then nothing happens.
Please help me implement facebook login step by step correctly.
EDIT:
app delegate:
[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions];
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
applicationWillEnterForeGround:
[FBSDKAppEvents activateApp];
then:
along with your(SanitLee) answer i have these methods:
- (void)loginViewFetchedUserInfo:(FBSDKLoginManager *)loginView
user:(FBSDKProfile*)user {
}
-(void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error{
// [self performSegueWithIdentifier:#"inbox" sender:self];
}
-(void)loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
}
-(void)loginButtonClicked{
}
i also get this error on whose view is not in the window hierarchy!
Here's how I did it and it works for me.
Firstly, import this in your m file:
#import <ParseFacebookUtils/PFFacebookUtils.h>//fb login for parse
Then the following codes should do what you want:
- (IBAction)loginButtonTouchHandler:(id)sender {
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[MBProgressHUD showHUDAddedTo:self.view animated:YES];
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = NSLocalizedString(#"Uh oh. The user cancelled the Facebook login.", nil);
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Log In Error", nil) message:errorMessage delegate:nil cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(#"Dismiss", nil), nil];
[MBProgressHUD hideHUDForView:self.view animated:YES];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
[self _loadData];
} else {
NSLog(#"User with facebook logged in!");
}
[MBProgressHUD hideHUDForView:self.view animated:YES];
[self _presentNextViewControllerAnimated:YES];
}
}];
}
- (void)_presentNextViewControllerAnimated:(BOOL)animated {
PAWWallViewController *wallViewController = [[PAWWallViewController alloc] initWithNibName:nil bundle:nil];
[(UINavigationController *)self.presentingViewController pushViewController:wallViewController animated:NO];
[self.presentingViewController dismissModalViewControllerAnimated:YES];
}
- (void)_loadData {
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
PFUser *user = [PFUser currentUser];
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSString *name = userData[#"name"];
NSString *email = userData[#"email"];
NSString *location = userData[#"location"][#"name"];
NSString *gender = userData[#"gender"];
NSString *birthday = userData[#"birthday"];
NSString *relationship = userData[#"relationship_status"];
NSString *facebookLink = [NSString stringWithFormat:#"Facebook.com/%#", facebookID];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
NSLog(#"facebookID --> %#", facebookID);
NSLog(#"name --> %#", name);
NSLog(#"email --> %#", email);
//for profile image
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
PFFile *userImageFile = [PFFile fileWithName:#"userImage.jpg" data:data];
if (userImageFile) [user setObject:userImageFile forKey:kPAWParseUserImageKey];
}
[user setObject:facebookID forKey:kPAWParseUsernameKey]; //initially use fb id as username to avoid duplication
[user setObject:name forKey:kPAWParseRealnameKey];
[user setObject:facebookLink forKey:kPAWParseFacebookKey];
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
if (succeeded) {
NSLog(#"fb user saved successfully");
}
} else {
NSLog(#"fb user saved unsuccessfully");
}
}];
}];
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) {
NSLog(#"The facebook session was invalidated");
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Log out of Spotpost?", nil) message:nil delegate:self cancelButtonTitle:NSLocalizedString(#"Log out", nil) otherButtonTitles:NSLocalizedString(#"Cancel", nil), nil];
[alertView show];
} else {
NSLog(#"Some other error: %#", error);
}
}];
}
And here is how I did config in app delegate:
#import <ParseFacebookUtils/PFFacebookUtils.h> //fb login for parse
....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
...
[PFFacebookUtils initializeFacebook]; //fb login for parse
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
....
[FBAppCall handleDidBecomeActiveWithSession:[PFFacebookUtils session]]; //fb login for parse
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
withSession:[PFFacebookUtils session]];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[PFFacebookUtils session] close];
}
I am trying to follow the Parse tutorial for Logging in With Facebook. However, the sample code does not match up with the guide, so the code there is useless. I have followed the guide completely, but after I login, it directs me to Facebook app, I give permission, it goes back to the app I am building, but I get the following error
FBSDKLog: Error for request to endpoint 'me': An open FBSession must be specified for calls to this endpoint.
What is going on? In Login controller:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
- (IBAction)loginButtonTouchHandler:(id)sender {
// Set permissions required from the facebook user account
NSArray *permissionsArray = #[ #"user_about_me", #"user_relationships", #"user_birthday", #"user_location"];
[PFFacebookUtils initializeFacebook];
// Login PFUser using Facebook
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
[_activityIndicator stopAnimating]; // Hide loading indicator
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = #"Uh oh. The user cancelled the Facebook login.";
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error"
message:errorMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Dismiss", nil];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
} else {
NSLog(#"User with facebook logged in!");
}
[self _presentUserDetailsViewControllerAnimated:YES];
}
}];
[_activityIndicator startAnimating]; // Show loading indicator until login is finished
}
- (void)_presentUserDetailsViewControllerAnimated:(BOOL)animated {
UserDetailsViewController *detailsViewController = [[UserDetailsViewController alloc] init];
[self.navigationController pushViewController:detailsViewController animated:YES];
}
In my UserDetailsViewController:
- (void)viewDidLoad {
// ...
[self _loadData];
}
- (void)_loadData {
// ...
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSString *name = userData[#"name"];
NSString *location = userData[#"location"][#"name"];
NSString *gender = userData[#"gender"];
NSString *birthday = userData[#"birthday"];
NSString *relationship = userData[#"relationship_status"];
NSURL *pictureURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookID]];
// URL should point to https://graph.facebook.com/{facebookId}/picture?type=large&return_ssl_resources=1
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:pictureURL];
// Run network request asynchronously
[NSURLConnection sendAsynchronousRequest:urlRequest
queue:[NSOperationQueue mainQueue]
completionHandler:
^(NSURLResponse *response, NSData *data, NSError *connectionError) {
if (connectionError == nil && data != nil) {
// Set the image in the header imageView
self.headerImageView.image = [UIImage imageWithData:data];
}
}];
// Now add the data to the UI elements
// ...
}
}];
}
We figured it out, when trying to create an auto-login feature with this function:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([[[[error userInfo] objectForKey:#"error"] objectForKey:#"type"]
isEqualToString: #"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonAction:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
if ([PFUser currentUser] && // Check if user is cached
[PFFacebookUtils isLinkedWithUser:[PFUser currentUser]]) { // Check if user is linked to Facebook
// Present the next view controller without animation
[self _presentUserDetailsViewControllerAnimated:NO];
}
}
We actually end up skipping the [PFFacebookUtils initializeFacebook] call, since it only happens when you push the login button. The solution is to put this call in the appDelegate in the method application:didFinishLaunchingWithOptions:
I want to send the messages and want to post on facebook and twitter in background is there any possible framework is there to do this.Can any one share the idea please.Thanks in advance .
To post on Twitter in background use this library https://github.com/nst/STTwitter
You will need to register your app on Twitter to receive consumer key and consumer secret. After you have it just use the code represented here Accessing Twitter Direct Messages using SLRequest iOS. This code uses system Twitter credentials, user have to set these credentials in iPhone / iPad settings.
Regarding to post on Facebook: I found no wrapper for iOS which can provide possibility to post in background. I use official Facebook iOS SDK is here https://github.com/facebook/facebook-ios-sdk. But post functionality works only with user's participation.
For facebook make sure you have the user permission or sdk setup properly. I would recommend to go through this tutorial for details.
http://m-farhan.com/2014/03/ios-facebook-sdk-tutorial/
- (void)requestPermissionAndPost {
[FBSession.activeSession requestNewPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", #"publish_checkins",nil]
defaultAudience:FBSessionDefaultAudienceEveryone
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Now have the permission
[self postOpenGraphAction];
} else {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self presentAlertForError:error];
}
}
}];
}
- (void)postOpenGraphAction
{
FBRequestConnection *newConnection = [[FBRequestConnection alloc] init];
FBRequestHandler handler =
^(FBRequestConnection *connection, id result, NSError *error) {
// output the results of the request
[self requestCompleted:connection forFbID:#"me" result:result error:error];
};
UIImage *img = imageView.image;
NSString *message = #"Your Message";
FBRequest *request=[[FBRequest alloc] initWithSession:FBSession.activeSession graphPath:#"me/photos" parameters:[NSDictionary dictionaryWithObjectsAndKeys:UIImageJPEGRepresentation(img, 0.7),#"source",message,#"message",#"{'value':'EVERYONE'}",#"privacy", nil] HTTPMethod:#"POST"];
[newConnection addRequest:request completionHandler:handler];
[self.requestConnection cancel];
self.requestConnection = newConnection;
[newConnection start];
}
// FBSample logic
// Report any results. Invoked once for each request we make.
- (void)requestCompleted:(FBRequestConnection *)connection
forFbID:fbID
result:(id)result
error:(NSError *)error
{
NSLog(#"request completed");
// not the completion we were looking for...
if (self.requestConnection &&
connection != self.requestConnection)
{
NSLog(#" not the completion we are looking for");
return;
}
// clean this up, for posterity
self.requestConnection = nil;
if (error)
{
NSLog(#" error");
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles: nil];
// error contains details about why the request failed
[alert show];
}
else
{
NSLog(#" ok");
NSLog(#"%#",result);
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"Posted Open Graph action, id: %#",
[result objectForKey:#"id"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
[self doCheckIn];
};
}
fro Twitter its simple and easy
#import <Twitter/Twitter.h>
- (void)TWPostImage:(UIImage *)image withStatus:(NSString *)status
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
//ACAccountStore *accountStore = [[ACAccountStore alloc] init];
// Create an account type that ensures Twitter accounts are retrieved.
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
ACAccount *ac;
if(granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
int i=0;
for (ACAccount *account in accountsArray ) {
i++;
NSLog(#"Account name: %#", account.username);
ac=account;
}
if (i==0) {
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please setup Twitter Account Settigns > Twitter > Sign In "
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
return ;
}
ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];;
//SLRequestHandler requestHandler;
SLRequestHandler requestHandler =
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (responseData) {
NSInteger statusCode = urlResponse.statusCode;
if (statusCode >= 200 && statusCode < 300) {
NSDictionary *postResponseData =
[NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:NULL];
NSLog(#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]);
ESAppDelegate* d =[[UIApplication sharedApplication] delegate];
NSString* link = [NSString stringWithFormat:#"Your Message",twitterAccStore,hashtagFromStore];
[d linkSelected:link PointerToSelf:self];
/*[[[UIAlertView alloc] initWithTitle:#"Result"
message:[NSString stringWithFormat:#"[SUCCESS!] Created Tweet with ID: %#", postResponseData[#"id_str"]]
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];*/
}
else {
NSLog(#"[ERROR] Server responded: status code %d %#", statusCode,
[NSHTTPURLResponse localizedStringForStatusCode:statusCode]);
}
}
else {
NSLog(#"[ERROR] An error occurred while posting: %#", [error localizedDescription]);
}
});
};
//});
ACAccountStoreRequestAccessCompletionHandler accountStoreHandler =
^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com"
#"/1.1/statuses/update_with_media.json"];
NSDictionary *params = #{#"status" : status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
NSData *imageData = UIImageJPEGRepresentation(image, 1.f);
[request addMultipartData:imageData
withName:#"media[]"
type:#"image/jpeg"
filename:#"image.jpg"];
[request setAccount:[accounts lastObject]];
[request performRequestWithHandler:requestHandler];
//});
}
else {
NSLog(#"[ERROR] An error occurred while asking for user authorization: %#",
[error localizedDescription]);
}
};
[accountStore requestAccessToAccountsWithType:twitterType
options:NULL
completion:accountStoreHandler];
}else
{
[[[UIAlertView alloc] initWithTitle:#"Wait"
message:#"Please Settigns > Twitter > In bottom Enable DealsHype to post"
delegate:nil
cancelButtonTitle:#"Thanks!"
otherButtonTitles:nil]
show];
}
}];
}
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];
}
}];
}