Issue with Log in to Parse.com using Facebook credentials - ios

I created a Facebook account, set up Parse.com app and developed iOS application as suggested by Parse.com website. I followed all the steps to make changes in info.plist file and in app delegate class.
Below is my code and I tried to debug it line by line. I noticed that FB asks for user permission and even after accepting it, no further action takes place.
- (IBAction)fblogin:(FBSDKLoginButton *)sender {
NSArray *permissions = #[#"public_profile", #"email"];
[PFFacebookUtils logInInBackgroundWithReadPermissions:permissions block:^(PFUser *user, 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 loadData];
[self.navigationController popToRootViewControllerAnimated:NO];
}
}];
}
-(void)loadData{
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"email, public_profile"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
// NSDictionary *userData = (NSDictionary *)result;
// NSString *first = [result objectForKey:#"first_name"];
// NSString *last = [result objectForKey:#"last_name"];
// NSString *username = [NSString stringWithFormat:#"%#.%#", first, last];
NSString *name = [result objectForKey:#"name"];
NSString *email = [result objectForKey:#"email"];
PFUser *userFb = [PFUser currentUser];
[userFb setObject:name forKey:#"username"];
[userFb setObject:email forKey:#"email"];
[userFb saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error)
{
UIAlertView *alertVeiw = [[UIAlertView alloc] initWithTitle:#"Sorry" message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
[alertVeiw show];
} else {
[[PFInstallation currentInstallation] setObject:[PFUser currentUser].objectId forKey:#"userId"];
[[PFInstallation currentInstallation] saveInBackground];
// [self.navigationController popToRootViewControllerAnimated:NO];
}
}];
}
}];
}
I couldn't understand why is it not working.
Imported frameworks into .m
#import "LoginViewController.h"
#import <Parse/Parse.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
#import <TwitterKit/TwitterKit.h>
#import <ParseFacebookUtilsV4/PFFacebookUtils.h>
#import "InboxViewController.h"
#import "MBProgressHUD.h"
above is the only login code i have and im not sure why its not working. When i first added and changed the code it would log in and provide a random username. Then when i kept trying different methods and finally ended up with method above it stopped logging in

Related

Parse - Facebook users being recreated everytime

I'm using Parse.com + Facebook user and I'm noticing something unusual that has not been happening previously. A user creates an account via Facebook, logs in, logs out, logs in, logs out, and then when they try logging in, that user gets deleted and another user gets created. Why could that be?
Here is my signup/signin code:
-(IBAction)facebookSignIn:(id)sender{
CLGeocoder *geo = [[CLGeocoder alloc] init];
if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied ){
UIAlertView *locationAlert = [[UIAlertView alloc]initWithTitle:#"Oops!" message:#"You must have location services enabled for this app to work properly" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Okay", nil];
[locationAlert show];
}else{
[PFFacebookUtils logInWithPermissions:_permissions block:^(PFUser *aUser, NSError *suError) {
if(!aUser){
NSLog(#"not fbook user because %#",[suError description]);
if([[[suError userInfo] objectForKey:#"com.facebook.sdk:ErrorLoginFailedReason"] isEqualToString:#"com.facebook.sdk:SystemLoginDisallowedWithoutError"]){
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error" message:#"Looks like you have Facebook authentication disabled! Go to Settings > Facebook > mySwapp and turn the switch ON"delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Okay", nil];
[alert show];
}
else{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Error Signing In/Logging In" message:[suError localizedDescription] delegate:nil cancelButtonTitle:nil otherButtonTitles:#"Okay", nil];
[alert show];
}
}
else if(aUser.isNew){
NSLog(#"User is NEW");
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *fbError) {
if (!fbError) {
NSLog(#"Facebook Request succeeded");
NSString *email = [user objectForKey:#"email"];
[aUser setEmail:email];
PFQuery *g = [PFQuery queryWithClassName:#"Counter"];
PFObject *cool = [g getObjectWithId:#"gpKDgNhwhw"];
[cool incrementKey:#"users"];
[cool saveEventually];
NSString *username = [NSString stringWithFormat:#"blahblah%d",[[cool objectForKey:#"users"] intValue]];
[aUser setUsername:username];
PFInstallation *installation = [PFInstallation currentInstallation];
[installation setObject:aUser forKey:#"user"];
[aUser setObject:#NO forKey:#"text"];
[aUser setObject:#YES forKey:#"snew"];
[aUser setObject:#"All" forKey:#"prefState"];
[aUser setObject:#"All" forKey:#"prefCat"];
[aUser setObject:#YES forKey:#"fnew"];
_type = #"facebook";
NSLog(#"Right before geopoint search....");
[PFGeoPoint geoPointForCurrentLocationInBackground:^(PFGeoPoint *geoPoint, NSError *error) {
if(!error){
NSLog(#"Got current geopoint!");
CLLocation *myLocation = [[CLLocation alloc]initWithLatitude:geoPoint.latitude longitude:geoPoint.longitude];
[geo reverseGeocodeLocation:myLocation completionHandler:^(NSArray *placemarks, NSError *error) {
if(!error){
CLPlacemark *pl = placemarks[0];
NSString *zip = [pl.addressDictionary objectForKey:(NSString *)kABPersonAddressZIPKey];
NSString *city = [pl.addressDictionary objectForKey:(NSString *)kABPersonAddressCityKey];
NSString *state = [pl.addressDictionary objectForKey:(NSString *)kABPersonAddressStateKey];
if(city == nil ||state ==nil){
NSLog(#"city or state is nil");
if(city==nil){
NSLog(#"city is nil");
}
if(state==nil){
NSLog(#"state is nil");
}
}
[aUser setObject:city forKey:#"city"];
[aUser setObject:state forKey:#"state"];
[aUser setObject:zip forKey:#"zip"];
[aUser setObject:geoPoint forKey:#"geopoint"];
[aUser setObject:#NO forKey:#"pref"];
[aUser setObject:#20 forKey:#"radius"];
[aUser setObject:#0 forKey:#"postCount"];
[aUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *perror) {
if(!perror && succeeded){
[self performSegueWithIdentifier:#"registerMe" sender:self]; }
else{
CCAlertView *errorAlert = [[CCAlertView alloc]initWithTitle:#"Oops!" message:[NSString stringWithFormat:#"%#. If you have already registered, please login regularly and go to the settings tab and switch on \"Link to Facebook\".",[[perror userInfo] objectForKey:#"error"]]];
[errorAlert addButtonWithTitle:#"Okay" block:^{
[aUser deleteInBackground];
}];
[errorAlert show];
}
}];
}
else{
CCAlertView *errorAlert = [[CCAlertView alloc]initWithTitle:#"Error getting Facebook data" message:[[fbError userInfo] objectForKey:#"error"]];
[errorAlert addButtonWithTitle:#"Okay" block:^{
[aUser deleteInBackground];
}];
[errorAlert show];
}
}];
}
else{
CCAlertView *errorAlert = [[CCAlertView alloc]initWithTitle:#"Facebook Sign In/Sign Up" message:[[suError userInfo] objectForKey:#"error"]];
[errorAlert addButtonWithTitle:#"Okay" block:^{
[aUser deleteInBackground];
}];
[errorAlert show];
NSString *ciid = [[PFInstallation currentInstallation] objectId];
[PFCloud callFunctionInBackground:#"logError" withParameters:#{#"installation":ciid,#"message":[suError description],#"place":#"Facebook Sign In/Sign Up"} block:^(id object, NSError *error) {
if(error){
PFObject * errorObj = [PFObject objectWithClassName:#"Error"];
[errorObj setObject:ciid forKey:#"installation"];
[errorObj setObject:[suError description] forKey:#"message"];
[errorObj setObject:#"Facebook Sign In/Sign Up" forKey:#"place"];
[errorObj saveEventually];
}
}];
}
}];
}
}];
}
else{
NSLog(#"User is OLD");
[self performSegueWithIdentifier:#"showMain" sender:self]; }
}];
}
}
and here is my logout code:
- (IBAction)goBackNow:(id)sender {
NSLog(#"gobacknow called");
[PFUser logOut];
[self.navigationController popToRootViewControllerAnimated:YES];
}
You can try to add more stuff to logout method. e.g.
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
PFInstallation *installation = [PFInstallation currentInstallation];
installation[#"user"] = [NSNull null];
[installation saveInBackground];
Also remember to [installation saveInBackground]; in your example

Create a LogIn and Register using XMPP framework

I am trying to make an XMPP LogIn and a Registration Page Separate one from another, the server is open fire based. Also I am NOT using inbound registration. I would like to underline that this is my first attempt to do something like this, my previous experience involves only working with NSSession to make a registration/ login. I want to say that I bought and read the Mastering The XMPP Framework book witted by Peter van de Put, but he explains only how to do it for an inbound registration/ login.
Also other links that I come across:
1 - similar answers between them
XMPP Aklesh Rathaur answer
XMPP Diego answer
2 - tutorial
PS: The information that I need to send to the server when I sign up is: email, name and password when created
and when I sign in: email, password
Building a Jabber Client for iOS
in this tutorial I don't understand how does the login take place since it only saves the users credentials in the NSUserDefaults.
You can download what I have implemented here (using an stackoverflow suggestion):
my code so far and database structure picture
UPDATE, this is the code that I am trying to use for registration:
-> .h file:
#import <UIKit/UIKit.h>
#import <CoreData/CoreData.h>
#import "XMPP.h"
#import "XMPPRoster.h"
#interface SignUpViewController : UIViewController <UITextFieldDelegate, UIApplicationDelegate, XMPPRosterDelegate, XMPPStreamDelegate>
{
XMPPStream *xmppStream;
}
#property (nonatomic, strong, readonly) XMPPStream *xmppStream;
#end
-> .m file
- (void)signUpButtonFunction{
NSLog(#"SignUp function");
[[self xmppStream] setHostName:#"IP_ADDRESS"];
[[self xmppStream] setHostPort:5222];
XMPPJID *jid=[XMPPJID jidWithString:emailTextField.text];
[[self xmppStream] setMyJID:jid];
[[self xmppStream] connectWithTimeout:3.0 error:nil];
NSMutableArray *elements = [NSMutableArray array];
[elements addObject:[NSXMLElement elementWithName:#"username" stringValue:#"venkat"]];
[elements addObject:[NSXMLElement elementWithName:#"password" stringValue:#"dfds"]];
[elements addObject:[NSXMLElement elementWithName:#"name" stringValue:#"eref defg"]];
[elements addObject:[NSXMLElement elementWithName:#"email" stringValue:#"abc#bbc.com"]];
[ xmppStream registerWithElements:elements error:nil];
}
//server connect delegate methods are not working at least it doesn't enter in them
- (void)xmppStreamDidRegister:(XMPPStream *)sender{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration" message:#"Registration Successful!" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
- (void)xmppStream:(XMPPStream *)sender didNotRegister:(NSXMLElement *)error{
DDXMLElement *errorXML = [error elementForName:#"error"];
NSString *errorCode = [[errorXML attributeForName:#"code"] stringValue];
NSString *regError = [NSString stringWithFormat:#"ERROR :- %#",error.description];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Registration Failed!" message:regError delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
if([errorCode isEqualToString:#"409"]){
[alert setMessage:#"Username Already Exists!"];
}
[alert show];
}
So, after search on the matter I found out that on the openFire can be installed a plugin that allows normal registration, so I have implemented the next method for the registration:
NSString *urlToCall = #"http://MyIP:9090/plugins/userService/userservice?type=add&secret=BigSecretKey&username=testUser&password=testPass&name=testName&email=test#gmail.com";
NSURL *url = [NSURL URLWithString:urlToCall];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"GET"];
NSError *error = nil;
NSURLResponse *response;
NSData *result = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];
NSString *responseString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
if ([responseString isEqual: #"<result>ok</result>\r\n"]) {
NSLog(#"user created");
} else {
NSLog( #"user NOT created");
NSLog(#"%#",responseString);
}

Share app through facebook is not working

Hi in my Application i have option of sharing my application through Facebook. So I have added the Facebook framework to my project and I have added the bundle id into my Facebook and got the App id but the problem is I'm not Unable to share the App its showing like this.
An error occurred. Please try again later
In my Stimulator is showing like this i don't why it's showing like that. If my device have Facebook App its working fine but if it doesn't have the Facebook App its showing error like this. Please tell how to resolve this issue.
- (IBAction)share:(id)sender {
FBLinkShareParams *params = [[FBLinkShareParams alloc] init];
params.link = [NSURL URLWithString:#"url/"];
// If the Facebook app is installed and we can present the share dialog
if ([FBDialogs canPresentShareDialogWithParams:params]) {
// Present share dialog
[FBDialogs presentShareDialogWithLink:params.link
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
// Success
NSLog(#"result %#", results);
}
}];
// If the Facebook app is NOT installed and we can't present the share dialog
} else {
// FALLBACK: publish just a link using the Feed dialog
// Put together the dialog parameters
// Put together the dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My appname", #"name",
#"test share.", #"caption",
#"sample.", #"description",
#"myrul", #"link",
nil];
// Show the feed dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
NSLog(#"Error publishing story: %#", error.description);
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User canceled.
NSLog(#"User cancelled.");
} else {
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"post_id"]) {
// User canceled.
NSLog(#"User cancelled.");
} else {
// User clicked the Share button
NSString *result = [NSString stringWithFormat: #"Posted story, id: %#", [urlParams valueForKey:#"post_id"]];
NSLog(#"result %#", result);
}
}
}
}];
}
}
- (NSDictionary*)parseURLParams:(NSString *)query {
NSArray *pairs = [query componentsSeparatedByString:#"&"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] init];
for (NSString *pair in pairs) {
NSArray *kv = [pair componentsSeparatedByString:#"="];
NSString *val =
[kv[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
params[kv[0]] = val;
}
return params;
}
I have used the above code for its not working please help me how to resolve this issue.
Thanks.
Use this code for Share App.
-(void)facebook
{
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
SLComposeViewControllerCompletionHandler myBlock = ^(SLComposeViewControllerResult result){
if (result == SLComposeViewControllerResultCancelled) {
NSLog(#"Cancelled");
}
else
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Congratulations!" message:#"Successfully posted to facebook Wall." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
[Flurry logEvent:#"Share screen - Successfully posted on Facebook"];
}
[controller dismissViewControllerAnimated:YES completion:Nil];
};
controller.completionHandler =myBlock;
NSString *str=[NSString stringWithFormat:#" I am using App for my iPhone. You too can download it from here"];
[controller setInitialText:str];
[self presentViewController:controller animated:YES completion:Nil];
}
else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Sorry!"message:#"Please add Facebook account in settings menu" delegate:self cancelButtonTitle:Nil otherButtonTitles:#"Ok", nil];
alert.tag=100;
[alert show];
}
}
For use of SLComposeViewController,you have to add Social Framework. It fetch your facebook account from setting and you can share your app link through SLComposeViewController. and
if you want to add images or URL to in than :
[composeController addImage:[UIImage imageNamed:#"image.png"]];
[composeController addURL: [NSURL URLWithString:#"apple.com"]];

Fetch user data from Facebook on iOS

I am new to iOS
I just want to get info such as gender, city, e-mail, and date of birth
but from code which I posted below ,I just got an idea like how to post data on Facebook,
now I want to fetch user details form Facebook
.h
#import <UIKit/UIKit.h>
#import <Social/Social.h>
#interface ViewController : UIViewController
- (IBAction)PostFB:(id)sender;
- (IBAction)PostTW:(id)sender;
#end
.m
//
// ViewController.m
// FaceBookFirstApp3
//
// Created by hits1 on 27/01/14.
// Copyright (c) 2014 hits1. All rights reserved.
//
#import "ViewController.h"
#import <Social/Social.h>
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)PostFB:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"First post from my iPhone app"];
[self presentViewController:controller animated:YES completion:Nil];
}
}
- (IBAction)PostTW:(id)sender {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
SLComposeViewController *tweetSheet = [SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[tweetSheet setInitialText:#"Great fun to learn iOS programming at appcoda.com!"];
[tweetSheet addURL:[NSURL URLWithString:#"http://www.appcoda.com"]];
[tweetSheet addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[self presentViewController:tweetSheet animated:YES completion:nil];
}
}
#end
please, help me Out to Fetch at least one field(city (or) gender (or) phone-number) form Gmail or Facebook
You can use the below code to get user's gender, city, e-mail, and date of birth
In .h file add,
#import <Accounts/Accounts.h>
#property (nonatomic, retain) ACAccountStore *accountStore;
#property (nonatomic, retain) ACAccount *facebookAccount;
-(void)get;
-(void)attemptRenewCredentials;
- (void) getuserdetails;
in .m file
- (void) getuserdetails
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *key = #"your app id";
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 {
dispatch_async(dispatch_get_main_queue(), ^{
// NSLog(#"%#",e.description);
if([e code]== ACErrorAccountNotFound)
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Account not found"
message:#"Please setup your Facebook account in Settings App" delegate:self cancelButtonTitle:nil otherButtonTitles:#"Ok",nil];
[alt show];
}
else
{
UIAlertView* alt = [[UIAlertView alloc] initWithTitle:#"Access Denied"
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 );
NSLog(#"EmailID %#",[list objectForKey:#"email"]);
NSLog(#"Birthday %#",[list objectForKey:#"birthday"]);
NSLog(#"Gender %#",[list objectForKey:#"gender"]);
NSLog(#"City %#",[[list objectForKey:#"location"] objectForKey:#"name"]);
if([list objectForKey:#"error"]!=nil)
{
[self attemptRenewCredentials];
}
dispatch_async(dispatch_get_main_queue(),^{
});
}
else{
//handle error gracefully
NSLog(#"error from get%#",error);
//attempt to revalidate credentials
}
}];
}
-(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);
}
}];
}
-(void)accountChanged:(NSNotification *)notif//no user info associated with this notif
{
[self attemptRenewCredentials];
}
- (void)sessionStateChanged:(NSNotification*)notification
{
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
{
if (!error)
{
//for geting the user detail.
NSString *fbSelectDetails = [#"" stringByAppendingFormat:#"https://graph.facebook.com/me? fields=id,name,email,first_name,last_name,gender,picture,link,birthday,quotes,education&access_token=%#",FBSession.activeSession.accessToken];
NSMutableDictionary *userDetails = [NSMutableDictionary dictionaryWithDictionary:[DataLayer getJSONContentFromURL:fbSelectDetails]];
NSString *uid = [userDetails valueForKey:#"id"];
NSString *userName= user.name;
NSString *userEmail= [userDetails valueForKey:#"email"];
NSString *userFirstName= [userDetails valueForKey:#"first_name"];
NSString *userLastName= [userDetails valueForKey:#"last_name"];
NSString *userGender= [userDetails valueForKey:#"gender"];
NSString *userLink= [userDetails valueForKey:#"link"];
NSString *userDob= [userDetails valueForKey:#"birthday"];
NSMutableDictionary *imgUrl = [NSMutableDictionary dictionaryWithDictionary:[userDetails valueForKey:#"picture"]];
NSString *userImgUrl= [[imgUrl valueForKey:#"data"] valueForKey:#"url"];
}];
}
}

Facebook Share Dialog in iOS

I am trying to implement the native Share dialog from Facebook in a sample application.
Seem to have some problem in doing so.
Things I have done so far:
Included the latest Facebook SDK
Included the AdSupport, Social, Account, Security and libsqlite3.dylib.
Added the sample code from Facebook.
Added -lsqlite3.0 -ObjC to Other Linker Flags as well
Added the app id to the plist
Added the FBUserSettingsViewResources bundle and FacebookSDKResources.bundle to the project
But I can't seem to share the URL. The share dialog doesn't even appear.
My code looks like this:
Viewcontroller.h
#import <UIKit/UIKit.h>
#interface ViewController : UIViewController
{
IBOutlet UIButton *buttonShare;
}
- (IBAction)shareButtonClicked:(id)sender;
#end
ViewController.m
#import "ViewController.h"
#import <FacebookSDK/FacebookSDK.h>
#interface ViewController ()
#end
#implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)shareButtonClicked:(id)sender
{
FBShareDialogParams *params = [[FBShareDialogParams alloc] init];
params.link = [NSURL URLWithString:#"https://developers.facebook.com/ios"];
params.picture = [NSURL URLWithString:#"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"];
params.name = #"Facebook SDK for iOS";
params.caption = #"Build great apps";
[FBDialogs presentShareDialogWithParams:params clientState:nil handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
}
#end
Not able to share the URL. Need some guidance on this.
- (IBAction)shareButtonClicked:(id)sender
{
// 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];
}
else if(session.isOpen)
{
NSString *str_img = [NSString stringWithFormat:#"https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png"];
NSDictionary *params = #{
#"name" :[NSString stringWithFormat:#"Facebook SDK for iOS"],
#"caption" : #"Build great Apps",
#"description" :#"Welcome to iOS world",
#"picture" : str_img,
#"link" : #"",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
//NSLog(#"Error publishing story.");
[self.indicator stopAnimating];
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
//NSLog(#"User canceled story publishing.");
[self.indicator stopAnimating];
} else {
//NSLog(#"Story published.");
[self.indicator stopAnimating];
}
}}];
}
}];
return;
}
Do you have Facebook App installed on your device? The Share dialog only works if you have the Facebook app installed.
From the Share dialog documentation :
Tip 1: What if people don't have the Facebook app installed?
The Share dialog can't be displayed if people don't have the Facebook app installed. Apps can detect this by calling [FBDialogs canPresentShareDialogWithParams:nil]; and may disable or hide a sharing button or fall back to the Feed dialog to share on the web. See the HelloFacebookSample included with the iOS SDK for an example.
From what I saw, iOS 6 will return NO for + canPresentShareDialogWithParams:. It only responds to + canPresentOSIntegratedShareDialogWithSession:. But I could be wrong here.
Anyways, this is how I do it -
1. For sharing links :
if ([FBDialogs canPresentShareDialogWithParams:nil]) {
NSURL* url = [NSURL URLWithString:link.url];
[FBDialogs presentShareDialogWithLink:url
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success");
}
}];
}
2.For OpenGraph calls :
id<FBGraphObject> pictureObject =
[FBGraphObject openGraphObjectForPostWithType:#"your_namespace:picture"
title:image.title
image:image.thumbnailUrl
url:image.url
description:#""];
id<FBOpenGraphAction> action = (id<FBOpenGraphAction>)[FBGraphObject graphObject];
[action setObject:pictureObject forKey:#"picture"];
[FBDialogs presentShareDialogWithOpenGraphAction:action
actionType:#"your_namespace:action_name"
previewPropertyName:#"picture"
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success");
}
}];
Check out other ways to share on iOS here
Hope this helps.
This works for me:
NSString *url = #"myUrl";
FBLinkShareParams* params = [[FBLinkShareParams alloc]init];
params.link = [NSURL URLWithString:url];
if([FBDialogs canPresentShareDialogWithParams:params]){
[FBDialogs presentShareDialogWithLink: [NSURL URLWithString:url]
name: #"Name"
caption: #"Caption"
description: #"Description"
picture: nil
clientState: nil
handler: nil];
}
else{
[...]
}
- (IBAction)btn_facebook:(id)sender {
[self performSelector:#selector(fb_func) withObject:nil afterDelay:0.0];
}
-(void)fb_func
{
// 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];
}
else if(session.isOpen)
{
NSString *str_link = #"";
NSLog(#"%#",str_link);
NSDictionary *params = #{
#"name" :#"name",
#"caption" : #"Description",
#"description" :#"test",
#"picture" : PostimageToPintresrAndFacebook,
#"link" : #"url",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil
parameters:params
handler:
^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
NSLog(#"User canceled story publishing.");
} else {
NSLog(#"Story published.");
}
}}];
}
}];
return;
}

Resources