How to get session login information to my UIWebView by FacebookSDK - iphone

After logging in to facebook with FacebookSDK, and I want to display a page using a UIWebView.
It is displayed correctly when I login for the first time.
But I close and restart the app, Even though the facebook session still open, I can't get login session to my UIWebView.
Do you have any suggestions for that, when I re-run the app, to get as it is the Facebook session information?
This is my code example.
#interface FBLogin2ViewController ()
#end
#implementation FBLogin2ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
NSString *appID = [FBSession defaultAppID];
NSLog(#"Session token exists %#", appID);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onLogin:(id)sender {
NSArray *permissions = nil;
if (![FBSession activeSession]) {
FBSession *session = [[FBSession alloc] initWithAppID:#"000000000000" permissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone urlSchemeSuffix:#"fb" tokenCacheStrategy:nil];
[FBSession setActiveSession:session];
}
else if( [FBSession activeSession].isOpen )
{
[[FBSession activeSession] closeAndClearTokenInformation];
FBSession.activeSession = nil;
}
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (IBAction)onLogout:(id)sender {
[FBSession.activeSession closeAndClearTokenInformation];
FBSession.activeSession = nil;
}
- (IBAction)onGoWeb:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://www.facebook.com/xxxxx?fref=xx"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
_webView.delegate = self;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
#end

1)call openFBSessionIfAvaliable in didFinishLaunchingWithOptions method
//in appdelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self openFBSessionIfAvaliable];
}
//in appdelegate
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
return [[FBSession activeSession] handleOpenURL:url];
}
//in appdelegate
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[FBSession activeSession] handleDidBecomeActive];
}
//in appdelegate
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[[FBSession activeSession] close];
}
-(void)openFBSessionIfAvaliable
{
[FBSession setActiveSession:[FBSession new]];
if ([FBSession activeSession].state == FBSessionStateCreatedTokenLoaded)
{
[self openFBSessionWithAllowLoginUI:NO];
}
}
- (BOOL)openFBSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error)
{
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
if (!error)
{
NSString *_facebookToken = [[FBSession activeSession] accessToken];
NSString *_facebookEmail = [user objectForKey:#"email"];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error)
{
[FBSession.activeSession closeAndClearTokenInformation];
/*UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Please try Again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];*/
}
}
2) On button Click of "Login via facebook" call below method
[self openFBSessionWithAllowLoginUI:YES];
3) Now every time when you launch the app, it will check the Facebook session, if found then proceed further otherwise show the button "Login via Facebook".session
I hope it will solve your problem.

Related

FB integration in ios app issues

I have integrated the facebook in my ios app and it is working nice.
But when i stored my FB credentials in setting it is not working.
It goes in following state
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
NSLog(#"case open session");
// if([sharePref returnFbName].length==0)
[self listFriendsFB];
break;
case FBSessionStateClosed:
NSLog(#"case FBSessionStateClosed session");
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
//[viewController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
NSLog(#"case close or fail session");
break;
default:
break;
}
It goes in FBSessionStateClosedLoginFailed , and error occurs.
And if I delete my account from phone setting it working fine i.e the session opens and it is logged in correctly.
Here is my code
- (void)openSession
{
//[self syncFacebookAccount];
NSArray *permissions=[[NSArray alloc]initWithObjects:#"email,publish_actions",nil];
dispatch_async(dispatch_get_main_queue(), ^{
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
NSLog(#"fb open session");
[self sessionStateChanged:session state:state error:error];
}];
});
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
NSLog(#"case open session");
// if([sharePref returnFbName].length==0)
[self fourthViewInitialization];
[self getFacebookInfo];
break;
case FBSessionStateClosed:
NSLog(#"case FBSessionStateClosed session");
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
//[viewController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
NSLog(#"case close or fail session");
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:AlertTitle
message:#"We are currently facing facebook connectivity issues. Please try again later!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
NSLog(#"error facebook : %#",error);
[alertView show];
[self hideActivityIndicator];
}
}
#pragma facebook methods
-(void)getFacebookInfo
{
// [NSThread detachNewThreadSelector:#selector(startLoader) toTarget:self withObject:nil];
NSString *query =[NSString stringWithFormat:#"Select name,uid,pic_square from user where uid=me()"];
// Set up the query parameter
my_info=[[NSMutableDictionary alloc]init];
my_info_array=[[NSMutableArray alloc ]init];
NSDictionary *queryParam =
[NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
[self hideActivityIndicator];
} else {
// NSLog(#"Result: %#", result);
// [self hideActivityIndicator];
my_info_array=(NSMutableArray *)[result objectForKey:#"data"];
my_info=[my_info_array objectAtIndex:0];
//NSLog(#"my info array %#",my_info_array);
NSLog(#"my info from fb %#",my_info);
//return my_info;
[firstView removeFromSuperview];
[self.view addSubview:fourthView];
displayNameLabel.text=[NSString stringWithFormat:#"%#%#",displayNameLabel.text,[my_info objectForKey:#"name"]];
[registerRequest setObject:[my_info objectForKey:#"name"] forKey:#"displayName"];
//[registerRequest setObject:[my_info objectForKey:#"email"] forKey:#"emailId"];
[registerRequest setObject:[my_info objectForKey:#"uid"] forKey:#"uid"];
[SharedPreferenceClass setFBUID:[my_info objectForKey:#"uid"]];// 30 sept
[registerRequest setObject:[my_info objectForKey:#"pic_square"] forKey:#"profilePic"];
NSString* picPath = [my_info objectForKey:#"pic_square"];
if (picPath.length>0) {
[SharedPreferenceClass setUserProfilePictureDefault:picPath];
}else{
[SharedPreferenceClass setUserProfilePictureDefault:#""];
}
//displayName.text=[my_info objectForKey:#"name"];
[self hideActivityIndicator];
}
}];
}
Thanks in advance.
I used this to open session when FB credentials are available in phone settings
// Initialize a session object
FBSession *session = [[FBSession alloc] init];
// Set the active session
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
NSLog(#"fb open session %#",error);
[self sessionStateChanged:session state:status error:error];
}];
And once session is opened I have used following code to get FB friends data.
NSArray *permissions=[[NSArray alloc]initWithObjects:#"email,publish_actions",nil];
dispatch_async(dispatch_get_main_queue(), ^{
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
NSLog(#"fb open session");
[self sessionStateChanged:session state:state error:error];
}];
});

Facebook SDK login issue on iPhone

I am trying to integrate the Facebook SDK into my application, and it works in my simulator perfectly. When I install it onto my iPhone and try running it, it shows me an alert, which states, "myapp needs to access your profile, friendlist, etc", and when I choose to allow it nothing happens - and it requires these permissions.
I have installed the Facebook application on my iPhone, tried logging out and back in many times, but without use.
But, when I go to settings and delete the Facebook details, it works perfectly:
How can I fix this?
I used following way its working for me :
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}
Remember to add your app to facebook developers/apps!!
If not, you can't interact with their servers...
Ok, I know what is going wrong. let me know that whatever you are doing is right but the result that you want will require something else.
Try this -
First of all implement all the facebook sdk delegate methods in your app delegate.
- (IBAction)loginWithFacebookButtonTapped:(id)sender
{
IntubeAppDelegate *delegat = (IntubeAppDelegate*)[[UIApplication sharedApplication] delegate];
[delegat doLoginAndSwitch];
}
Now, in your appDelegate -
-(void) doLoginAndSwitch
{
[self openSessionWithAllowLoginUI:YES];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"email", nil];
return [FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
-(BOOL)openSessionWithAllowPublishStreamPermission:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone completionHandler:^(FBSession *session, NSError *error){
}];
return YES;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if(!error)
{
// NSLog(#"FBSessionStateOpen :- logged in");
[self openSessionWithAllowPublishStreamPermission:YES];
// Your code
}
}
}
Also to switch back to your application -
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
I hope you would get what you desire now. :)

Facebook page like in iOS

I know how to like photos/comments in Facebook. But I want to like a Facebook page through my app. Is it possible? If yes, can anyone give me some suggestions?
This is a problem. If you were able to do this, you would be able to "like" a page programatically without the user necessarily being aware that this is what's happening. That would violate Facebook's TOS.
I think you'll be better off simply placing a regular "like button" in your application and letting your users decide if they want to click it.
Some related posts -
How to programmatically "press" a 'Like' button through a Facebook Application?
Like button in iOS application
Using 'Like' with the Facebook Graph API on iOS
Liking a page on behalf of a user?
I have written a method my calling which you can like your page by giving its url in the method.
For this method you have to use facebook sdk and need to add some deprecated facebook files as.
#import "Facebook.h"
#import "FBCustomLoginDialog.h"
#import "Accounts/Accounts.h"
It is up to you how you find that files and use it.Any way this is working code for page like.
-(void)like
{
NSString *likePage=#"http://in.yahoo.com/?p=us"; // here you page url
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
likePage, #"object",[[NSUserDefaults standardUserDefaults] valueForKey:#"token"],#"access_token",
nil];
[FBRequestConnection startWithGraphPath:#"/me/og.likes" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:nil message:[NSString stringWithFormat:#"liked with id %#",[result valueForKey:#"id"]] delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
NSLog(#"result is %#",result);
}];
}
- (IBAction)likepageonFB:(id)sender
{
if ([[FBSession activeSession] isOpen]) {
[self like];
}else
{
[appDelegate openSession];
}
}
Here is code used in app delegate file ....
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
// Override point for customization after application launch.
self.viewController = [[LikeAppViewController alloc] initWithNibName:#"LikeAppViewController" bundle:nil];
self.window.rootViewController = self.viewController;
[self.window makeKeyAndVisible];
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
// [self openSession];
} else {
// No, display the login page.
[self showLoginView];
}
return YES;
}
#pragma mark- Facebook Methods
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
{
[[NSUserDefaults standardUserDefaults] setValue:[[FBSession activeSession] accessToken] forKey:#"token"];
NSLog(#"token is %#",[[FBSession activeSession] accessToken]);
[self.viewController like];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[self showLoginView];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
- (void)openSession
{
NSLog(#"open session called ");
NSArray *permissions=[[NSArray alloc] initWithObjects:#"publish_stream",#"publish_actions",#"user_likes",#"user_about_me",nil];
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES completionHandler:^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)showLoginView
{
[self.viewController presentedViewController];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)fbDialogLogin:(NSString*)token expirationDate:(NSDate*)expirationDate
{
NSLog(#"expiry date is %#",expirationDate);
}
use this file FBCustomLoginDialog.h and FBCustomLoginDialog.m
Fb like Widget can be embedded in our application. You just have to add a webView and get the Fb Like Widget html code/URL here.
in ViewController.h where you want to add fb like button:
#import <UIKit/UIKit.h>
#interface TestViewController : UIViewController <UIWebViewDelegate>
#property (strong, nonatomic) UIWebView * fbLikeWebView;
-(void)embedFBLikeButton;
#end
in TestViewController.m
#import "AboutUsViewController.h"
#implementation AboutUsViewController
#synthesize fbLikeWebView = _fbLikeWebView;
- (void)viewDidLoad
{
[super viewDidLoad];
//Add this code for FbLike Webview
self.fbLikeWebView = [[UIWebView alloc] initWithFrame: CGRectMake(100.0, 50.0, 55.0, 70.0)];
_fbLikeWebView.opaque = NO;
_fbLikeWebView.backgroundColor = [UIColor clearColor];
_fbLikeWebView.delegate = self;
[self.view addSubview:_fbLikeWebView];
for (UIScrollView *subview in _fbLikeWebView.subviews)
{
if ([subview isKindOfClass:[UIScrollView class]]) {
subview.scrollEnabled = NO;
subview.bounces = NO;
}
}
}
then in ViewWillAppear method call the enbeddFBLikeButton Method to add the fbLike button wigdet on web view:
-(void)viewWillAppear:(BOOL)animated
{
[self embedFBLikeButton];
[_fbLikeWebView reload];
}
-(void)embedFBLikeButton
{
NSString *facebookUrl = //here paste the url you get from fb developer link above;
[self.fbLikeWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:facebookUrl]]];
}
You conform to UIWebViewDelegate now its turn to defining th edelegate method here:
#pragma mark - WebView Delgate Methods
- (BOOL)webView:(UIWebView *)webview shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if ([request.URL.lastPathComponent isEqualToString:#"login.php"])
{
[self login];
return NO;
}
return YES;
}
-(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
[_fbLikeWebView stopLoading];
}
This method for login the user to facebook Account:
- (void)login
{
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:#[#"publish_actions", #"publish_stream", #"user_photos"]]];
[[FBSession activeSession] openWithBehavior: FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
// call the legacy session delegate
//Now the session is open do corresponding UI changes
if (session.isOpen) {
FBRequest *me = [FBRequest requestForMe];
[me startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *my,
NSError *error) {
if (!my) {
NSLog(#"Facebook error:\n%#", error.description);
[[[UIAlertView alloc] initWithTitle: #"Error"
message: #"Facebook Login error."
delegate: self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil, nil] show];
return;
}
}];
[_fbLikeWebView reload];
[[[UIAlertView alloc] initWithTitle: #""
message: #"Successfully Login. Please click on like button"
delegate: self
cancelButtonTitle: #"Ok"
otherButtonTitles: nil, nil] show];
}
break;
case FBSessionStateClosedLoginFailed:
{
[_fbLikeWebView reload];
}
break;
default:
break; // so we do nothing in response to those state transitions
}
}];
}

how can i get friends list from facebook friendspickercontroller

In my Iphone app i'm using facebook sdk 3.1. I want to redirect facebook login page first. after login again redirect to my app.
And also i want to get facebook friends list from friendspickercontroller when i don't login facebook in settings in iphone.
i'm using this code
Facebook login:
-(IBAction)facebookButtonPressed:(id)sender
{
NSLog(#" hi im ");
NSArray *permissions =
[NSArray arrayWithObjects:#"user_photos", #"friends_photos",#"email", nil];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
if(!error)
{
NSLog(#" hi im sucessfully lloged in");
[self sessionStateChanged:session state:state error:error];
}
}];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
{
UIViewController *topViewController =
[appDelegate.naviCon topViewController];
if ([[topViewController modalViewController]
isKindOfClass:[ViewController class]]) {
[topViewController dismissModalViewControllerAnimated:YES];
}
NSLog(#"h im in state open 1111111");
{
NSLog(#"hi iam in open state9999999999999999999");
}
}
break;
case FBSessionStateClosed:
{
NSLog(#"iam in loginfailed 444444444444");
}
case FBSessionStateClosedLoginFailed:
NSLog(#"iam in loginfailed 555555555555");
NSLog(#"iam in statecloze 555555555555");
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error)
{
}
}
Getting frieds:
NSArray *permissions =
[NSArray arrayWithObjects:#"user_photos", #"friends_photos",#"email", nil];
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler: ^(FBSession *session, FBSessionState state, NSError *error)
{
if(!error)
{
if (self.friendPickerController == nil)
{
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];
}
}];
}
Thanks in advance
you also need read_friendlists permission for getting friend list.
then use
-(void)friendPickerViewControllerSelectionDidChange:(FBFriendPickerViewController *)friendPicker
{
NSArray *friends = friendPicker.selection;
}
Thanks
- (void)friendPickerViewControllerSelectionDidChange:(FBFriendPickerViewController *)friendPicker
{
NSArray *friends = friendPicker.selection;
}
I hope that's what you're looking for!

Getting user data from facebook login in xcode?

I have integrated facebook login in my app.But Im unable to get user data ie it is not entering the user details loop
In Appdelegate.m
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",
#"user_likes",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSLog(#"%#",user);
}}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[[FBSession activeSession] closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
}
But I dont find NSLog of user NSLog(#"%#",user) to be printed eventhough the session is opened bcoz NSLog(#"User session found") is printed
Y is it so ?
I had same issue where I was not able to enter in the block once came back after log in after an hour I figured out that I was returning mysession class instead of instance of mysession. This might fix your issue:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [mysession handleOpenURL:url];
}