Programmatically share videos on facebook by iOS 6 app? - iphone

I am working on a app where I need to share videos on Facebook. When I tried developer.facebook.com for solution I found use the graph api to upload a video in ios . It shares video by graph API. Will the graph API work in iOS 6? Please suggest. Also provide any sample code if you have.
Thanks in advance.

Try with this I used Facebook SDK 3.1 https://developers.facebook.com/ios/
.h file
#import <FacebookSDK/FacebookSDK.h>
extern NSString *const SCSessionStateChangedNotificationCamera;
.m file
NSString *const SCSessionStateChangedNotificationCamera = #"com.facebook.Scrumptious:SCSessionStateChangedNotification";
-(IBAction)btnFacebookShareClick:(id)sender {
if (![self openSessionWithAllowLoginUI:YES]) {
[self showLoginView];
}
}
#pragma mark -
#pragma mark - Facebook Method
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
}
else {
action();
}
}
#pragma mark -
#pragma mark Facebook Login Code
- (void)showLoginView {
[self dismissViewControllerAnimated:NO completion:nil];
[self performSelector:#selector(showLoginView1) withObject:nil afterDelay:1.5f];
}
- (void)showLoginView1 {
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
NSArray *permissions = [[NSArray alloc] initWithObjects: #"publish_actions", #"publish_stream", nil];
[FBSession.activeSession reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self uploadVideoOnFacebook];
}
else {
NSLog(#"%#",error);
}
}];
}
else {
[self uploadVideoOnFacebook];
}
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationCamera object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [CameraViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects: #"publish_actions", #"publish_stream", nil];
return [FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends allowLoginUI:allowLoginUI completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if (!error) {
[self sessionStateChanged:session state:state error:error];
}
else {
NSLog(#"%#",error);
}
}];
}
+ (NSString *)FBErrorCodeDescription:(FBErrorCode) code {
switch(code){
case FBErrorInvalid :{
return #"FBErrorInvalid";
}
case FBErrorOperationCancelled:{
return #"FBErrorOperationCancelled";
}
case FBErrorLoginFailedOrCancelled:{
return #"FBErrorLoginFailedOrCancelled";
}
case FBErrorRequestConnectionApi:{
return #"FBErrorRequestConnectionApi";
}case FBErrorProtocolMismatch:{
return #"FBErrorProtocolMismatch";
}
case FBErrorHTTPError:{
return #"FBErrorHTTPError";
}
case FBErrorNonTextMimeTypeReturned:{
return #"FBErrorNonTextMimeTypeReturned";
}
case FBErrorNativeDialog:{
return #"FBErrorNativeDialog";
}
default:
return #"[Unknown]";
}
}
-(void) uploadVideoOnFacebook {
NSURL *pathURL;
NSData *videoData;
pathURL = [NSURL URLWithString:self.strUploadVideoURL];
videoData = [NSData dataWithContentsOfURL:[NSURL URLWithString:self.strUploadVideoURL]];
NSString *strDesc;
strDesc = txtCaption.text;
NSDictionary *videoObject = #{#"title": #"application Name",#"description": strDesc,[pathURL absoluteString]: videoData};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos" parameters:videoObject HTTPMethod:#"POST"];
[self.view setUserInteractionEnabled:NO];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeGreen title:#"Video uploaded successfully" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:3.0];
else
[AJNotificationView showNoticeInView:self.view type:AJNotificationTypeRed title:#"Video uploaded error" linedBackground:AJLinedBackgroundTypeAnimated hideAfter:3.0];
[NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:#selector(popViewAfterMKInfo) userInfo:nil repeats:NO];
}];
}

yes, you can do this, Facebook just has released its new framework 3.5 which will easily work for iOS5 and iOS6 http://developers.facebook.com/ios/

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 fetch friend error

I am new to iOS development. I got an error when fetching the friend from facebook by using the Facebook SDK.Here are my code.
FacebookClass
- (void)fetchFacebookFriend{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_birthday",#"friends_hometown",
#"friends_birthday",#"friends_location",#"friends_work_history",
nil];
if (!FBSession.activeSession.isOpen) {
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error != nil) {
NSLog(#"Failed to retrive facebook friend.");
return;
}
else{
self.myArray = [[NSMutableArray alloc] init];
NSLog(#"permissions::%#",FBSession.activeSession.permissions);
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,hometown,location,work"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
appDelegate.myFacebookArray = [[NSMutableArray alloc] init];
for (NSDictionary *fbData in [result objectForKey:#"data"]) {
NSLog(#"%#",fbData);
[self.myArray addObject:fbData];
}
}];
}
}];
return;
}
}
ViewController
- (IBAction)pickFriendPressed:(id)sender {
NSLog(#"##Begin");
[[FacebookClass sharedInstance] fetchFacebookFriend];
NSLog(#"##End");
}
Output
##Begin
##End
Json data
Please help I get the Json data after display the ##End.Thanks
Here you have a code sample that fetches the friends info:
[facebook requestWithGraphPath:#"me/friends"
andParams:[ NSDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,link,gender,last_name,first_name",#"fields",nil]
andDelegate:self];
Remember to:
implement the proper delegate methods
You must call authorize before fetching the friends information. This way the user will be able to login first.
I hope this helps, cheers
Try this:
get friend list using
[FBRequest requestForMyFriends];
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection connection,NSDictionary result,NSError error) { NSArray friends = [result objectForKey:#"data"]; ......
the coding is as follow but main line is [FBRequest requestForMyFriends];
-(void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
for (int i = 0; i < [arrFacebookFriends count]; i++) {
UserShare *shareObj = [arrFacebookFriends objectAtIndex:i];
[shareObj release];
shareObj = nil;
}
[arrFacebookFriends removeAllObjects];
for (NSDictionary<FBGraphUser>* friend in friends) {
UserShare *shareObj = [[UserShare alloc] init];
shareObj.userName = friend.name;
shareObj.userFullName = friend.username;
shareObj.userId = [friend.id intValue];
NSLog(#"%#",friend.id);
shareObj.userPhotoUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?", friend.id];
[arrFacebookFriends addObject:shareObj];
[shareObj release];
}
[self StopSpinner];
[tblFacebookFriends reloadData];
}];
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationFL object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [FacebookFriendsListViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
see my accepted this answer on How to get the list of friend without opening FBFriendPickerViewController iOS

How to get the list of friend without opening FBFriendPickerViewController iOS

I am using Facebook sdk 3.2 for iOS,
There are various sample project available for iOS
But my problem is how can i get the list of friends without opening FBFriendPickerViewController.
In fact i want all my friends facebook id and there
Any help will be appreciated.
Thanks in Advance
Try this:
get friend list using
**[FBRequest requestForMyFriends];**
**FBRequest* friendsRequest = [FBRequest requestForMyFriends];**
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"]; ......
the coding is as follow but main line is
**[FBRequest requestForMyFriends];**
-(void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
for (int i = 0; i < [arrFacebookFriends count]; i++) {
UserShare *shareObj = [arrFacebookFriends objectAtIndex:i];
[shareObj release];
shareObj = nil;
}
[arrFacebookFriends removeAllObjects];
for (NSDictionary<FBGraphUser>* friend in friends) {
UserShare *shareObj = [[UserShare alloc] init];
shareObj.userName = friend.name;
shareObj.userFullName = friend.username;
shareObj.userId = [friend.id intValue];
NSLog(#"%#",friend.id);
shareObj.userPhotoUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?", friend.id];
[arrFacebookFriends addObject:shareObj];
[shareObj release];
}
[self StopSpinner];
[tblFacebookFriends reloadData];
}];
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationFL object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [FacebookFriendsListViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}

Facebook SDK error 3 and error 2

I have this application I am using for posting on facebook and I am currently facing difficulties in posting on some of the iOS 6.0 devices. I am using facebook SDK 3.1 only and trying to publish action. Following is the code I am using in the class to initiate the read permission.
For the access I am using the following code.
// CALLING THIS CODE BLOCK IN ONE BUTTON ACTION.
if (FBSession.activeSession.isOpen)
{
[self pickaChoice];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", nil]
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
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:
[FBSession setActiveSession:session];
[self pickaChoice];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// ...
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
NSString* message = [NSString stringWithFormat:#"You have disallowed application to post on your behalf."];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)pickaChoice
{
/* Just a class to select message and then retrieve the message in the next function
-(void)didSelectaPhraseToPost:(NSString *)message */
FBPublishViewController *fbPublishViewController = [[FBPublishViewController alloc] initWithNibName:#"FBPublishViewController"
bundle:[NSBundle mainBundle]];
fbPublishViewController.selectionDelegate = self;
[self presentViewController:fbPublishViewController
animated:YES
completion:^(){
//nil
}];
}
-(void)didSelectaPhraseToPost:(NSString *)message
{
// Selecting a message from a class and retrieving here. This is the message to post on the feed.
[self publishMessage:message];
}
- (void) performPublishAction:(void (^)(void)) action
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
- (void)publishMessage:(NSString *)message
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"APP_NAME", #"name",
message, #"message",
APP_LINK, #"link",
#"APP_PICTURE", #"picture",
nil];
[self.spinner startAnimating];
[self performPublishAction:^{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[self.spinner stopAnimating];
NSString *messageTitle = nil;
NSString *message = nil;
// If the result came back okay with no errors...
if (result && !error)
{
NSLog(#"accessToken : %#",[FBSession activeSession].accessToken );
NSLog(#"result : %#",result);
messageTitle = #"Success";
message = #"App has posted to facebook";
}else{
NSLog(#"error : %#",error);
messageTitle = #"Error v1.1";
//message = error.localizedDescription;
message = #"Unable to process the request. Please check the permissions for the application.";
[FBSession.activeSession closeAndClearTokenInformation];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:messageTitle
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
//TODO maybe clear connection here if we want to force an new login
}];
}];
}
Now the problem is on some iOS 6.0 devices it is throwing facebook.sdk.error 3 and on some devices it is throwing facebook.sdk.error 2 even when the application is permitted to post. In the current code I have just changed the message to a custom for more user friendly message but if you go on to print the localizedDescription it will show those.
On most of the iOS 6.0 devices the code is working absolutely fine and the message is posted. Let me know if anyone can find out where the problem exactly is. I have spent like days now in this and still not getting where the problem is.
Edit 1
A pattern I observed that when facebook application is installed and user is logged in through it and not logged in through the native settings I am facing these sort of difficulties.
It would be good if you find out your iOS version and use apple's default facebook shar view for iOS 6.0 and on another side for below version you must need to use Graph API.
I used this method its work for me fine in iOS6, may be its help you.
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
[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: {
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;
}

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!