Facebook page like in iOS - iphone

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
}
}];
}

Related

Programmatically share videos on facebook by iOS 6 app?

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/

How to get session login information to my UIWebView by FacebookSDK

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.

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;
}

Post to Facebook not working from delegate

I have added FBSdk in my project along with SBJson classes, what files should i import in my second view controller to work my code ?
I want to post on Fb using the description under url so for that i need to include this code into my second view controller, but i am stuck in a part i founded that the below code should be added in the second view controller but the "delegate:self" not works, as i am doing this first time so can any one guide me how should i code in my second view controller keeping into account the values from the app delegate (How should i get the values from the app delegate of FB to the second view so that i can add this code in second code plz can any one correct this code)
facebook = [[Facebook alloc] initWithAppId:#"YOUR_APP_ID"];
// how should i take this id from the app delegate ?
NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
NSMutableDictionary* params = [[NSMutableDictionary alloc]
initWithCapacity:1]
[params setObject:#"Testing" forKey:#"name"];
[params setObject:#"IMAGE_URL" forKey:#"picture"];
[params setObject:#"Description" forKey:#"description"];
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Is the above code correct ?
How should i implement it in my second view controller in -(void)fb_share (method).
My App Delegate File is Like this :
#import "AppDelegate.h"
#import "ViewController.h"
#import "ServerRequests.h"
#import "DBManager.h"
#import "SBJson.h"
#include "FBSession.h"
#import "FBRequest.h"
#import "FBGraphUser.h"
NSString *const FBSessionStateChangedNotification = #"com.myapp:FBSessionStateChangedNotification";
#implementation AppDelegate
#synthesize userId;
#synthesize dbSnyced;
#synthesize fbId;
#synthesize loginView;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ self.fbId = #"-1";
self.dbSnyced = NO;
self.loginView = nil;
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:self.viewController] autorelease];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
[self showLogin:NO];
}
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self checkAccountLogin];
}
- (void) applicationDidEnterBackground:(UIApplication *)application
{
[self hideLogin:NO];
}
- (void) applicationWillTerminate:(UIApplication *)application
{
NSLog(#"applicationWillTerminate");
[self hideLogin:NO];
[FBSession.activeSession close];
}
- (void) checkAccountLogin
{
self.dbSnyced = NO;
if([ServerRequests serverIsReachableAlertIfNo:YES]) {
DBManager *db = [[[DBManager alloc] initWithPath:DB_NAME] autorelease];
NSDictionary *userDic = [[db smartQueryForArrayWithStatement:#"SELECT * FROM table WHERE id=1"] objectAtIndex:0];
NSString *loginType = [userDic objectForKey:#"login_type"];
if([loginType isEqualToString:#"none"]) {
NSLog(#"no login type");
[self showLogin:NO];
}
else {
self.userId = [[userDic objectForKey:#"user_id"] intValue];
if([loginType isEqualToString:#"Facebook"]) {
NSLog(#"Facebook account");
[FBSession.activeSession handleDidBecomeActive];
}
else if([loginType isEqualToString:#"MyApp"]) {
NSLog(#"MyApp account");
}
}
}
}
#pragma - Fb stuff
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
NSLog(#"sessionStateChanged");
switch (state) {
case FBSessionStateOpen:
if (!error) {
[self handleFbUserDetails];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionStateChangedNotification object:session];
if (error) {
NSLog(#"error: %#", error.localizedDescription);
if(self.loginView) {
[self.loginView hideLoading];
}
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (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];
}
- (BOOL) activeFBSession
{
return FBSession.activeSession.isOpen;
}
- (void) closeFBSession
{
NSLog(#"closeFBSession");
[FBSession.activeSession closeAndClearTokenInformation];
}
- (void) showLogin:(BOOL)animated
{
if(!self.loginView) {
self.loginView = [[[LoginViewController alloc] init] autorelease];
[[self.navigationController topViewController] presentViewController:self.loginView animated:animated completion:nil];
}
}
- (void) hideLogin:(BOOL)animated
{
if(self.loginView) {
[self.viewController gotToTab:0];
[self.loginView hideLoading];
[[self.navigationController topViewController] dismissViewControllerAnimated:animated completion:^{
self.loginView = nil;
NSLog(#"self.loginView = nil");
}];
}
}
- (void) handleFbUserDetails
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"fb connected");
self.fbId = [user objectForKey:#"id"];
self.userId = -1;
ASIFormDataRequest *request = [ServerRequests ASIFormDataRequestForSrcipt:#"facebookUser"];
[request setPostValue:[user objectForKey:#"id"] forKey:#"fbId"];
[request setPostValue:user.first_name forKey:#"first_name"];
[request setPostValue:user.last_name forKey:#"last_name"];
[request setPostValue:user.location.name forKey:#"location"];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"facebookUser response: %#", response);
if([response rangeOfString:#"ERROR"].location == NSNotFound) {
self.userId = [response intValue];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
NSString *q = [NSString stringWithFormat:#"UPDATE table SET login_type = 'Facebook', user_id = '%#' WHERE id = 1", response];
NSLog(#"%#", q);
[db executeStatement:q];
[db release];
}
else {
}
[self sessionBecameActive];
}];
[request startAsynchronous];
[self hideLogin:YES];
}
else {
NSLog(#"error: %#", error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook Request Error" message:#"Cannot connect to Facebook." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
if(self.loginView) {
[self.loginView hideLoading];
}
}
[ServerRequests SyncDataBase];
}];
}
- (void) signOut
{
[self closeFBSession];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
[db executeStatement:#"UPDATE table SET login_type = 'none' WHERE id = 1"];
[db release];
[self showLogin:YES];
}
- (void) sessionBecameActive
{
[self.viewController sessionBecameActive];
}
#end
Can any one figure out what code should i write in the -(void)fb_share method in second view controller by getting values from the delegate ?
Any Help !
I did this ... and getting Error: HTTP status code: 400 ... but the user name get's displayed on alert
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
// NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
// #"publish_stream", nil];
// [facebook authorize:permissions delegate:self];
self.params = [[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];
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Upload to FB?"
message:[NSString stringWithFormat:#"Upload to ""%#"" Account?", user.name]
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"No",#"Yes", nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"PostUploaded"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
[tmp release];
}
}];
[tmp show];
[tmp release];
}
}];
.. what should i do now ?
declare facebook as a property in .h file of your appDelegate
then in second view controller import AppDelegate
in .m file where you want the Facebook object
get it like
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
Facebook *facebook = appDelegate.facebook;

After authentication through a webview, how do I redirect my application to show app view

I have made an application that logs onto a simple UIWebview login page and then authenticates on the website that loads. The thing is, I want my app to autheticate on the website and as soon as it is authenticated I want it to redirect my app to the view I have made in Xcode. I am fairly new to iphone programming.
Any help would be appreciated.
The code I made so far also consists of cookies, and it looks as follows:
FOR MY APP DELEGATE:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self initPreferences];
// Override point for customization after application launch.
NSArray *siteArray = [[NSArray alloc] initWithObjects:#"http://...com",
#"http://....com",
#"http://...com",
#"http://...com",
#"http://.com",
nil];
SignonWebView *webView = [[SignonWebView alloc] initWithURL:[siteArray objectAtIndex:2]];
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc addObserver:self selector:#selector(cookieChange:) name:#"NSHTTPCookieManagerCookiesChangedNotification" object:nil];
if ([Constants useAuthenticator])
{
[[self window] addSubview:[webView view]];
}
else
{
[self.window addSubview:navigationController.view];
}
// [self.window makeKeyAndVisible];
// Check for device
if (![self deviceConnected])
{
[Constants setConnectedToDevice:NO];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"ALERT!" message:#"Device Not Detected" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert autorelease];
}
else
{
if ([Constants isLineaPro])
{
NSLog(#"Init LineaPro device");
}
else if ([Constants isVerifone])
{
NSLog(#"Init Verifone device");
DeviceControl *dc = [DeviceControl sharedInstance]; // Singleton initializes device
[[dc payControl] hostPowerEnabled:YES];
NSLog(#"---------------------- Sending message to MSR");
[[dc pinPad] sendStringCommand:#"Q40" calcLRC:YES];
}
}
//AdminViewController = [[AdminViewController alloc] init];
[self.window makeKeyAndVisible];
//[self.navigationController.navigationBar setTintColor:[UIColor colorWithRed:0.933 green:0.114 blue:0.149 alpha:1]];
//[[UIApplication sharedApplication] setupScreenMirroringOfMainWindow:navigationController framesPerSecond:20];
//[[UIApplication sharedApplication] setupScreenMirroringWithFramesPerSecond:20];
return YES;
//[self.parentViewController.view setHidden:YES];
}
-(void)cookieChange:(NSHTTPCookieStorage *)somethin
{
NSLog(#"----------- Cookies have changed sucessfully
---------------");
}
FOR MY LOGIN VIEW WHICH HAS COOKIES:
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
NSLog(#"shouldStartLoadWithRequest");
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(#"webViewDidStartLoad");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(#"***************** webViewDidFinishLoad --- getting all cookies");
NSMutableArray *cookieList = [[NSMutableArray alloc] init];
NSHTTPCookie *cookie;
for (cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookieList addObject:cookie];
// NSLog(#"%# expire: %#\n%#", [cookie name],[cookie expiresDate],cookie);
}
NSLog(#"Number of cookies is %d",[cookieList count]);
if (initialLoad)
{
NSLog(#"---- removing existing cookies -----");
for (NSHTTPCookie *currentCookie in cookieList)
{
NSLog(#"Removing cookie : %#",[currentCookie name]);
//[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:currentCookie];
}
initialLoad = NO;
}
else
{
for (NSHTTPCookie *currentCookie in cookieList)
{
NSLog(#"='%#'",currentCookie);
if ([[currentCookie name]isEqual:#"UserID"]) {
// we have a user id returned from services, so save it
[self setUserIDCookie:currentCookie];
NSLog(#" -- userIDCookie : %#",[[self userIDCookie] value]);
[self setUserID:([[self userIDCookie] value])];
}
if ([[currentCookie name]isEqual:#"UserName"]) {
// we have a user id returned from services, so save it
[self setUserNameCookie:currentCookie];
NSLog(#" -- userNameCookie : %#",[[self userNameCookie] value]);
[self setUserName:([[self userNameCookie] value])];
}
}
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(#"didFailLoadWithError : %#",error);
}
#pragma mark -
#pragma mark Actions
-(void)loadUrl:(NSString*)URL
{
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:URL]]];
}
#end
If the authentication is successful, have the server redirect to a certain URL. Then, in webView:shouldStartLoadWithRequest:navigationType:, check for that URL and move to your other view when it is loaded.
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(#"shouldStartLoadWithRequest");
if([[[request URL] absoluteString] isEqualToString:#"http://authSuccess.website.com"]) {
[[[UIApplication sharedApplication] delegate] authenticationSuccessful];
return NO;
}
return YES;
}
And, in the app delegate:
- (void)authenticationSuccessful {
[[[self.window subviews] objectAtIndex:0] removeFromSuperview];
[self.window addSubview:navigationController.view];
}