iOS Facebook SDK - Check Permissions - iphone

I have a Facebook SSO working perfectly on my app, using last release of Facebook Objective-C SDK.
I need to ask an extra permission inside the app if user do "something". I don't need to ask that permission if user gave it to me before, so, I guess, in Facebook SDK there should be a method
-(BOOL) checkPermission:(NSString*) permission;
so I can use it like this:
if( [facebook checkPermission:#"email"] ) {
Is there a way to do this?

This question is a bit old but you can now check what permissions the active session has without making a graph request. Here is how it's done in the HelloFacebookSample :
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// permission does not exist
} else {
// permission exists
}
Just replace "publish_actions" with "email".

SDK not providing direct method for checking specific permissions but you can check if user granted permission to your application by checking permissions connection of user object in Graph API
GET https://graph.facebook.com/me/permissions
Same can be achieved with FQL query on permissions table
SELECT email FROM permissions WHERE uid = me()

IMPORTANT: This seems to be true for an older version of the Facebook SDK (for example 3.9.0). In 3.15.0 it doesn't work this way anymore. You should use [session.permissions] as Raphaƫl Agneau says in his answer.
You have to use the following method, because [FBSession activeSession].permissions seems to return the permissions you requested, not the real ones.
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *c, id result, NSError *error) {
if (!error) {
NSDictionary *permissions= [(NSArray *)[result data] objectAtIndex:0];
if (![permissions objectForKey:#"publish_actions"]) {
// Ok, continue with your logic
} else {
// Permission not found, maybe request it (see below)
}
} else {
// Treat error
}
}];
See here for more info:
https://developers.facebook.com/docs/facebook-login/ios/v2.0#permissions-checking
If the permission is not found you may want to request it this way:
[session requestNewPublishPermissions:PERMISSIONS_YOU_WANT
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession* session, NSError* error) {
// Try again the /me/permissions above
}];

Here's my code for FBSDK 4.2.0 for checking permissions. The string that's passed in is the name of the permission, e.g. "publish_actions"
- (void) checkForPermission:(NSString *)permission granted:(void (^)(void))sBlock denied:(void (^)(void))fBlock {
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/permissions" parameters:nil] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
BOOL hasPermission = NO;
if (!error) {
NSArray *permissions = [result objectForKey:#"data"];
for (NSDictionary *dict in permissions) {
if ([[dict objectForKey:#"permission"] isEqualToString:permission]) {
if ([[dict objectForKey:#"status"] isEqualToString:#"granted"]) {
hasPermission = YES;
}
}
}
}
if (hasPermission) {
(sBlock) ? sBlock() : sBlock;
} else {
(fBlock) ? fBlock() : fBlock;
}
}];
} else {
(fBlock) ? fBlock() : fBlock;
}
}

For the SDK 4+ you have these 2 ways of getting the permissions:
[[FBSDKAccessToken currentAccessToken] hasGranted:#"user_photos"]
or
[[[FBSDKAccessToken currentAccessToken] permissions] containsObject:#"user_photos"]

Related

How to Fetch Google Plus circles in IOS Sdk

I am using Google Plus integration where I have to fetch circles of user.
I am passing the Url:https://www.googleapis.com/plus/v1/people/Your_User_Id/people/visible?key=APP_Key.
I am getting the response as:
{ error = { code = 403; errors = ( { domain = global; message = Forbidden; reason = forbidden; } ); message = Forbidden; }; }
What kind of permission do I need for This request?
You can only do this for the signed in user - so the "Your_User_Id" should always be "me". It's fine to pass the app key as well, but you must be making the call with an oAuth 2.0 token from a user who has signed in to your app. You can see all the details here: https://developers.google.com/+/mobile/ios/people#retrieve_a_collection_of_people
Basically you'd need to implement sign-in, if you haven't already, then you can use the plusService in the GPPSignIn sharedInstance:
GTLQueryPlus *query =
[GTLQueryPlus queryForPeopleListWithUserId:#"me"
collection:kGTLPlusCollectionVisible];
[[[GPPSignIn sharedInstance] plusService] executeQuery:query
completionHandler:^(GTLServiceTicket *ticket,
GTLPlusPeopleFeed *peopleFeed,
NSError *error) {
if (error) {
GTMLoggerError(#"Error: %#", error);
} else {
// Get an array of people from GTLPlusPeopleFeed
NSArray* peopleList = [peopleFeed.items retain];
}
}];
That is calling the URL that you're giving there.

How to check if Facebook is loggedIN in device ? objective C

I am implementing the Facebook SDK into my app . I am using FBLoginView to login with Facebook. I have a UIButton, which I'm using to share on a user's Facebook wall. Now I don't want to login using FBLoginView , i want to check if there is a Facebook app, and if the user has logged in.
- (IBAction)pickFriendsList:(UIButton *)sender
{
FBFriendPickerViewController *friendPickerController = [[FBFriendPickerViewController alloc] init];
friendPickerController.title = #"Pick Friends";
[friendPickerController loadData];
// Use the modal wrapper method to display the picker.
[friendPickerController presentModallyFromViewController:self animated:YES handler:
^(FBViewController *sender, BOOL donePressed) {
if (!donePressed) {
return;
}
NSString* fid;
NSString* fbUserName;
for (id<FBGraphUser> user in friendPickerController.selection)
{
NSLog(#"\nuser=%#\n", user);
fid = user.id;
fbUserName = user.name;
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:#"test", #"message", #"http://webecoist.momtastic.com/wp-content/uploads/2009/01/nature-wonders.jpg", #"picture", #"Sample App", #"name",fid,#"tags",fid,#"to",#"106377336067638",#"place", nil];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed",fid] parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection,id result,NSError *error)
{
[FBWebDialogs presentFeedDialogModallyWithSession:nil parameters:params handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error)
{
// Error launching the dialog or publishing a story.
NSLog(#"Error publishing story.");
}
else
{
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled story publishing.");
}
else
{
// Handle the publish feed callback
//Tell the user that it worked.
}
}
}];
}];
}
}];
}
I am assuming that you are using iOS 6 sdk. In which case, Use below code (workable for device) :
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
{
//user is already logged in using iOS integrated FB a/c
}
else
{
//user is not logged in
}
Note: FBSession can't check this criteria. So session check with FBSession has a different meaning from above code.
Regards,
Check for the URL Scheme fb://
[[UIApplication sharedApplication] canOpenURL:#"fb://"] returns YES if Facebook App is installed. This post lists, de available URL schemes for Facebook: https://stackoverflow.com/a/5707825/1511668
Maybe fb://online is what you are looking for.

iOS Facebook SDK 3.2 Check Permissions via Graph Path Request

I am trying to check if user has already granted publish permission or not. if he has not granted permissions before then i navigate him to permissions screen via: requestNewPublishPermissions
-(void)checkPermissions
{
// Get the most recent status
[FBRequestConnection
startWithGraphPath:#"me/permissions"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
//This Condition Never Executed
if([[result objectForKey:#"data"] objectForKey:#"publish_actions"])
{
//permissions exist
}
else
{
[self openSessionForPublishPermissions];
}
NSString *permission = [[result objectForKey:#"data"] objectForKey:#"publish_actions"];
NSLog(#"permissions data = %#",data);
}
else
{
NSLog(#"error"); //Control goes to this block
}
}];
}
In code above if(!error) block is never executed and it always returns Error
Where i'm going wrong? Am i missing something?
You can see permissions in the active session. Here is how it's done in the HelloFacebookSample :
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// permission does not exist
} else {
// permission exists
}
Instead of manually checking the permissions, you could check if the session is active and request publish permissions: if the user has already granted the permissions, an additional confirmation dialog will not be posted. See the code sample below:
- (void)requestWritePermission:(UIViewController *)viewController channel:(NSString *)channel callback:(void(^)(BOOL success))callback
{
if ([FBSession.activeSession isOpen])
{
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
callback(error == nil);
}];
}
else
{
// Attempt to request publish permission without read permission.
}
}
The code is not complete, but should get you started.

Facebook Login ask to install (iPhone)

I need help in the facebook login from Facebook-SDK-3.1 for iOS 6.I have used all the code of the Facebook sdksample code sessionLoginSample,I have used the WebView opening code in this and whenever i login from the new id ...it takes me to the below image link to install in my project .dont know what exactly it is...and if i do so and after that logout from the code ..and when I again press button to login , it automatically log-in without asking for the id and pssword``login page. and again again it automatically logs-in , even after logout./.can anyone help me why after being logout it ask stores the previous access token and password.
and code is
- (IBAction)buttonClickHandler:(id)sender {
AppDelegate* appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObjects:#"email", nil]];
}
[appDelegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
FBSession.activeSession = session;
[self updateView];
NSLog(#" state=%d",state);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
userInfo = #"";
userInfo = user.username;
NSLog(#"string %#", userInfo);
[self checkfacebook];
}];
}]; }
}
FB grants access to your app once the user logs in . If the user wants to modify the privileges he can do it by loggin into fb and changing permissions. You might want to look into oAuth for further details.
As u login through new emailid it has to install your app for them...so,its asking for different login..but again u login with the same it will not ask...the answer for ur 2nd question is....is u doing something to the server side...bcoz there might be a provision on the server which remember user for few hour or few days...so,check with server side..if not working with server...reply me back i will try to answer further...

How to login just in time to facebook in iOS app

Have reviewed the facbook pages on how to integrate facebook with iOS, but what i had been looking for is a bit different.
I would like to prompt for Facbook login only when a user decides to share stuff, the flow explained in FB docs walk thru how to login (handle asyc response from FB login) and show publish button, but what we need is to show "Post to FB" button, when the user clicks, i would like the user to login and then go to the preview of what is going to be posted and then post to FB.
I am using FB SDK and iOS 5, the difficulty is how to wire FB login flow directly to Post flow.
Thanks
Elango
Below is some code that I wrote that does this. If the user has not signed in to Facebook from the device settings, it is a better user experience to just call openActiveSessionWithPublishPermissions:, which does both the read and publish permissions in one step. Otherwise, you just do the two permissions serially. As soon as the read permission succeeds, you do the publish permission.
I tested this code on an iOS6 and iOS5 device, using Facebook SDK 3.2.1
- (BOOL)hasFacebookInDeviceSettings
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:#"com.apple.facebook"];
BOOL hasFacebookBuiltinAccount = (accountTypeFB != nil);
return hasFacebookBuiltinAccount;
}
- (BOOL)hasLoggedInToFacebookInDeviceSettings
{
if (![self hasFacebookInDeviceSettings]) {
return NO;
}
BOOL result = [SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook];
return result;
}
- (void)openFacebookSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
if (![self hasLoggedInToFacebookInDeviceSettings]) {
// Simpler if we don't have the built in account
[FBSession openActiveSessionWithPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self facebookSessionStateChanged:session
state:state
error:error];
}];
}
else if (!FBSession.activeSession.isOpen) {
__block BOOL recursion = NO;
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (recursion) {
return;
}
recursion = YES;
if (error || !FBSession.activeSession.isOpen) {
[self facebookSessionStateChanged:session
state:state
error:error];
}
else {
assert(FBSession.activeSession.isOpen);
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,
NSError *error) {
[self facebookSessionStateChanged:session
state:FBSession.activeSession.state
error:error];
}];
}
}
}];
}
}
hasFacebookInDeviceSettings tells you if this device even supports Facebook from the settings (i.e. this is iOS6+).
hasLoggedInToFacebookInDeviceSettings tells you if the user has signed into to Facebook from the iOS6 Facebook device settings.
You'll need to create your own facebookSessionStateChanged: and other code, as described in the login tutorial