How can we like a url using FB Login? - iphone

I want to like a url using a like button as shown in the given link.
At bottom Like button is there
click on the like button will like this page and shows in your facebook profile page under Activity block as shown below:
How can we like a url like that in iPhone App.If user is login with fb then just like if not login then login and then like.
Thanks in Advance.

are you looking for this : Facebook like button

Finally, I have done it.
Code to like Page URL using graph API is as Follows:
- (IBAction)likepageonFB:(id)sender
{
[appDelegate openSession];
NSString *likePage=#"http://www.facebook.com/ipreencekmr";
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);
}];
}
You can check this example I have uploaded FBLike Button

Related

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

Publish Feed with SSO in Facebook (IOS)

I am working on Facebook integration and trying for Single Sign-On with publish feed functionality.
I am using latest FacebookSDK. I have Facebook's Hackbook example code but, i am new to all this so it is being difficult to understand completely all this things.
While searching on SSO i got some code, It is working fine. Here is the code i am using (At the end of this page there is a source code attached)
FBUtils.h and FBUtils.m class
ViewController.m
- (IBAction)publishFeed:(id)sender {
//For SSO
[[FBUtils sharedFBUtils] initializeWithAppID:#"3804765878798776"];
NSArray *permision = [NSArray arrayWithObjects:#"read_stream",#"publish_stream", nil];
[[FBUtils sharedFBUtils] LoginWithPermisions:permision];
[FBUtils sharedFBUtils].delegate = self;
FBSBJSON *jsonWriter = [FBSBJSON new];
/// for publishfeed
NSArray* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:
#"Get Started",#"name",#"https://itunes.apple.com?ls=1&mt=8",#"link", nil], nil];
NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
// Dialog parameters
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"I have lot of fun preparing.", #"name",
#" exam", #"caption",
#" ", #"description",
#"https://itunes.apple.com", #"link",
#"http://mypng", #"picture",
actionLinksStr, #"actions",
nil];
AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
[[delegate facebook] dialog:#"feed"
andParams:params
andDelegate:self];
When i tap Facebook button in my app it is redirect me to Facebook and then retuning back to my app. Now , what i want is to fire publishFeed event right after returning back to the app and it should ask direct for post or cancel options to the user. But it is asking for login again like this.
Can any one help me in this or please suggest me the right way.
Your Suggestions would be a great help.
In your method, you're not checking if the app has permissions to publish post and if the user logged in before. So, every time you call this method, the app wants you to login. I think that is the problem.
If I'm right, you need to add permission and login control in your method like this. This is my sample code from another project, you can get the logic behind it.
- (IBAction)facebookShare:(id)sender
{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
// You check the active session here.
if (FBSession.activeSession.isOpen)
{
// You check the permissions here.
if ([FBSession.activeSession.permissions
indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, ask for it
[FBSession.activeSession
reauthorizeWithPublishPermissions:
[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// If permissions granted, publish the story
[self postFacebook];
[[[UIAlertView alloc] initWithTitle:#"Result"
message:#"Posted in your wall."
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}
}];
} else {
// If permissions present, publish the story
[self postFacebook]; // ------> This is your post method.
[[[UIAlertView alloc] initWithTitle:#"Sonuç"
message:#"Duvarında paylaşıldı."
delegate:self
cancelButtonTitle:#"Tamam"
otherButtonTitles:nil]
show];
}
}
else
{
// If there is no session, ask for it.
[appDelegate openSessionWithAllowLoginUI:YES];
}
// NSLog(#"Post complete.");
}

Integration error while posting message on friends wall?

i m using facebook_skd_3.1 (Xcode ios 4.5) i got the friends list by calling
FBFriendPickerViewController, on clicking done button i have tried to post the message
on the selected friends wall but i got this error :-
Warning: Attempt to dismiss from view controller
while a presentation or dismiss is in progress!
2012-12-06 19:37:09.187 ........project[5474:19a03] Error: HTTP status code: 403
error in the alert view
error =Error Domain=com.facebook.sdk code=5" ..........
message = "(#200)the user hasn't authorized the application to perform this action";
type = OAuthException
};
};
code=403;
com.acebook.sdk:HTTPStatuscode=403}
code :-
-(void)facebookViewControllerDoneWasPressed:(id)sender {
NSString* userid;
for (id<FBGraphUser> user in self.friendPickerController.selection)
{
NSLog(#"\nuser=%#\n", user);
userid = user.id;
}
NSMutableDictionary* dictaram = [[NSMutableDictionary alloc]
initWithObjectsAndKeys:#"like this!", #"message", nil];
[FBRequestConnection startWithGraphPath:[NSString stringWithFormat:#"%#/feed", userid]
parameters:params HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Shared"
message:[NSString stringWithFormat:# %#! error=%#", fbUserName, error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
];
[self dismissModalViewControllerAnimated:YES];
Do i need some permissions or there is some coding error please help.
thanks in advance.
Please dismiss viewcontroller after some delay.
I have figured it by re authorizing the permissions as follows in delegate i have read permissions for session so that didn't worked for posting. write the following code to in the ButtonAction and you will get the proper output.
NSArray *permissions =[NSArray arrayWithObjects:#"publish_actions",#"publish_stream",#"manage_friendlists", nil];
[[FBSession activeSession] reauthorizeWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
/* handle success + failure in block */
}];

Facebook API: Post on friend wall

Is it possible to post something on a users friends wall, without having to get all the friends first (So you can get the friend id)?
[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
See this
-(IBAction)PostToBuddyWall
{
NSMutableDictionary *postVariablesDictionary = [[NSMutableDictionary alloc] init];
[postVariablesDictionary setObject:#"LOL" forKey:#"name"];
[postVariablesDictionary setObject:self.postTextView.text forKey:#"message"];
[objDelegate.facebook requestWithGraphPath:[NSString stringWithFormat:#"%#/feed",friendId] andParams:postVariablesDictionary andHttpMethod:#"POST" andDelegate:nil];
NSLog(#"message: %#",postVariablesDictionary);
[postVariablesDictionary release];
UIAlertView *facebookAlter=[[UIAlertView alloc] initWithTitle:#"Message" message:#"Posted successfully on facebook" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil, nil];
[facebookAlter show];
[facebookAlter release];
[self dismissModalViewControllerAnimated:YES];
}
You can get the friends of the logged in user by issuing a request to me/friends.
Then you can create a ui element that shows the list of friends and the user can select the ones he want to share with.
Then, after the user selected you simply post on their walls by issuing a POST to FRIEND_ID/feed (Feed connection of the User object).
You'll need to have the publish_stream permissions which lets you: Enables your app to post content, comments, and likes to a user's stream and to the streams of the user's friends (http://developers.facebook.com/docs/authentication/permissions/)

Getting Facebook ID number with API

I know - I have read the documentation - but frankly Facebook is horrible at it. I can't figure out how to send a request that illicits a response. Here's what I'm trying:
NSURL *fbID = [NSURL URLWithString:#"https://graph.facebook.com/me?fields=id"];
fbUserID = [[NSData alloc] initWithContentsOfURL: fbID];
Where should this code go? Is there a specific class it is looking for if I have set 'self' as delegate?
How are you trying to integrate FB into your app? I have been looking into Facebook connect recently and found their documentation very helpful (http://developers.facebook.com/docs/guides/mobile/#ios). I know you said you looked at the documentation, but for me after going through their steps for iOS I was able to make an app that allowed users to sign in and give me access to their basic information, including ID. After going through authorization, I had the following code in my app delegate:
- (void) fbDidLogin {
//get information about the currently logged in user
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
NSString *name = [result objectForKey:#"name"];
NSString *msg = [[NSString alloc] initWithFormat:#"To prove this works, your name is %#",name];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Thanks for Logging In!"
message:msg
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
[alert release];
}
This gets the user's full name after logging in and displays it. You can do the same thing for getting their ID.