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

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.

Related

Invite Facebook friends through iPhone App using FBWebDialogs

I am using Facebook sdk 3.10 to send a request to multiple friend at a time using FBWebDialogs. Following code I'm using and all thing is fine like selecting multiple friends , sending them request. But there is one problem, is this FBWebDialogs uses some limit of friends as I have more that 300 friends but this is showing only 12-15 friends always.
CODE
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:nil
parameters:nil
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
Using above I can see only max 12 friends in the dialog? Am I missing something?
Any help would be appreciated.
You should pass the NSDictionary type object to parameters argument.
You can create like this:
NSArray *suggestedFriends = [[NSArray alloc] initWithObjects:#"fb_id1", #"fb_id2", nil];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:[suggestedFriends componentsJoinedByString:#","], #"suggestions", nil];
Now
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
Here it will show all of the friends with the suggested Facebook ids.

How to post to a users wall using Facebook SDK

I want to post some text to a users wall using the facebook sdk in an iOS app.
Is posting an open graph story now the only way to do that?
I've found with open graph stories they are really strange, you can only post things in the format "user x a y" where you preset x and y directly on facebook, like user ata a pizza or user played a game. Setting up each one is pretty laborious too because you have to create a .php object on an external server for each one.
Am I missing something or is there a simpler way to go about this?
Figured it out by browsing the facebook tutorials a bit more.
-(void) postWithText: (NSString*) message
ImageName: (NSString*) image
URL: (NSString*) url
Caption: (NSString*) caption
Name: (NSString*) name
andDescription: (NSString*) description
{
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
url, #"link",
name, #"name",
caption, #"caption",
description, #"description",
message, #"message",
UIImagePNGRepresentation([UIImage imageNamed: image]), #"picture",
nil];
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// No permissions found in session, ask for it
[FBSession.activeSession requestNewPublishPermissions: [NSArray arrayWithObject:#"publish_actions"]
defaultAudience: FBSessionDefaultAudienceFriends
completionHandler: ^(FBSession *session, NSError *error)
{
if (!error)
{
// If permissions granted and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}];
}
else
{
// If permissions present and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}
-(void) postToWall: (NSMutableDictionary*) params
{
m_postingInProgress = YES; //for not allowing multiple hits
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post Failed"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
m_postingInProgress = NO;
}];
}
the easiest way of sharing something from your iOS app is using the UIActivityViewController class, here you can find the documentation of the class and here a good example of use. It is as simple as:
NSString *textToShare = #”I just shared this from my App”;
UIImage *imageToShare = [UIImage imageNamed:#"Image.png"];
NSURL *urlToShare = [NSURL URLWithString:#"http://www.bronron.com"];
NSArray *activityItems = #[textToShare, imageToShare, urlToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];
This will only work on iOS 6 and it makes use of the Facebook account configured in the user settings, and the Facebook SDK is not needed.
You can use Graph API as well.
After all the basic steps to create facebook app with iOS, you can start to enjoy the functionality of Graph API. The code below will post "hello world!" on your wall:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
...
//to get the permission
//https://developers.facebook.com/docs/facebook-login/ios/permissions
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
NSLog(#"publish_actions is already granted.");
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result.
}];
}
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/feed"
parameters: #{ #"message" : #"hello world!"}
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Post id:%#", result[#"id"]);
}
}];
}
...
The basic staff is presented here: https://developers.facebook.com/docs/ios/graph
The explorer to play around is here:
https://developers.facebook.com/tools/explorer
A good intro about it: https://www.youtube.com/watch?v=WteK95AppF4

Get publish permission for Facebook app for iOS with -openWithBehavior:completionHandler:

In my application I need user to sign in to Facebook, get friend list in my table view and Post on feeds, but I don't want to redirect the user anywhere. so I used -openWithBehavior:completionHandler: ... Here is my code.
-(IBAction)loginAction:(id)sender {
[self deleteCookies];
// get the app delegate so that we can access the session property
DLAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
// this button's job is to flip-flop the session from open to closed
if (appDelegate.session.isOpen) {
// if a user logs out explicitly, we delete any cached token information, and next
// time they run the applicaiton they will be presented with log in UX again; most
// users will simply close the app or switch away, without logging out; this will
// cause the implicit cached-token login to occur on next launch of the application
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
[self updateView];
}
// if the session isn't open, let's open it now and present the login UX to the user
[appDelegate.session 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
{
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
[FBSession openActiveSessionWithAllowLoginUI:NO];
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_stream",#"publish_actions", nil] defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:NO completionHandler:nil];
}
break;
case FBSessionStateClosedLoginFailed:
{ // prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
// call the legacy session delegate if needed
//[[delegate facebook] fbDialogNotLogin:userDidCancel];
}
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
}
[self updateView];
}];
}
}
The user is successfully signed in and I can retrieve the friend list by using FQL. The problem is while posting to feeds. I know I need to get publish permissions to do it. But when I uses the following code to post...
- (IBAction)postAction:(id)sender {
DLAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[FBSession openActiveSessionWithAllowLoginUI:NO];
NSMutableDictionary *postParams = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
#"https://developers.facebook.com/attachment/iossdk_logo.png", #"picture",
#"Facebook SDK for iOS", #"name",
#"Build great social apps and get more installs.", #"caption",
#"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps.", #"description",
nil];
if ([_postText.text length]>0) {
[postParams setObject:[_postText text] forKey:#"message"];
}
if (([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) ||
([FBSession.activeSession.permissions
indexOfObject:#"publish_stream"] == NSNotFound)) {
// No permissions found in session, ask for it
[FBSession.activeSession
reauthorizeWithPublishPermissions:
[NSArray arrayWithObjects:#"publish_stream",#"publish_actions",nil]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
[self publishStory:postParams];
}
}];
} else {
// If permissions present, publish the story
[self publishStory:postParams];
}
}
}
-(void)publishStory:(NSDictionary *)postParams {
[FBRequestConnection startWithGraphPath:
#"me/feed" parameters:postParams HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (!error) {
//Tell the user that it worked.
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared:"
message:[NSString stringWithFormat:#"Sucessfully posted to your wall."]
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
alertView.tag = 101;
[alertView show];
}
else {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error:"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
NSLog(#"%#",error);
}
}
];
}
This code redirects the user to Safari or Facebook App. Which I don't want to happen.
Definitely I need to get publish permissions while logging in. the question is HOW?
You have to set FBSessionLoginBehavior, to change it the only way is to use:
[session openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
// ex: updating the view
}];
I see you use FBSessionLoginBehaviorForcingWebView, so to get what you want you have to choose from this enum:
typedef enum {
/*! Attempt Facebook Login, ask user for credentials if necessary */
FBSessionLoginBehaviorWithFallbackToWebView = 0,
/*! Attempt Facebook Login, no direct request for credentials will be made */
FBSessionLoginBehaviorWithNoFallbackToWebView = 1,
/*! Only attempt WebView Login; ask user for credentials */
FBSessionLoginBehaviorForcingWebView = 2,
/*! Attempt Facebook Login, prefering system account and falling back to fast app switch if necessary */
FBSessionLoginBehaviorUseSystemAccountIfPresent = 3,
} FBSessionLoginBehavior;
Now to solve this "Definitely I need to get publish permissions while logging in. the question is HOW?" you may - (id)initWithPermissions:(NSArray*)permissions; your Session :
NSArray *permissions = #[#"publish_stream", #"publish_actions"];
appDelegate.session = [[FBSession alloc] initWithPermissions:permissions];

Facebook iOS SDK - share user photo

I need to upload photo to user's album and let user share with some messages. I've uploaded photo to app album using [FBRequestConnection startForUploadPhoto:photo completionHandler:handler], but is there any way to share the uploaded picture?
Thanks.
You can use the startWithGraphPath method provide in the Facebook SDK:
+ (FBRequestConnection*)startWithGraphPath:(NSString*)graphPath
parameters:(NSDictionary*)parameters
HTTPMethod:(NSString*)HTTPMethod
completionHandler:(FBRequestHandler)handler;
Here my code I used to upload a photo with a message, so the photo appear on my timeline with the message:
- (void) requestPostPhoto:(UIImage *)photo withMessage:(NSString *)message
{
if( [self isLocalUserConnected] )
{
NSMutableDictionary * params = [[NSMutableDictionary alloc] init];
if( message != nil || ![message isEqualToString:#""] )
{
[params setObject:message forKey:#"message"];
}
[params setObject:UIImagePNGRepresentation(photo) forKey:#"picture"];
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST" completionHandler:^(FBRequestConnection * connection, id result, NSError * error)
{
//TODO: add some code here
}];
}
}
I think you can change in the startWithGraphPath: the #"me" by the facebook user ID.

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