How to attach data to Facebook app request on the iPhone? - iphone

I'm working on 'deep linking' a Facebook request into my iOS app. A Facebook app is setup and seems to work as I can send a request to a friend, the request badge appears in the friend's Facebook, and clicking on the request launches my app (all on the iPhone).
However, so far I could not pass any data with the request, which I want to use when my app launched from the Facebook app with the request.
I use the following call:
-(void) fbRequestActionWithMessage: (NSString *) message andLink: (NSString *) link
{
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"data1", #"key1",
#"data2", #"key2",
nil];
NSString *requestDataString = [requestData JSONRepresentation];
NSMutableDictionary* params = [NSMutableDictionary
dictionaryWithObjectsAndKeys:
message, #"message",
#"Check this out", #"notification_text",
link, #"link",
requestDataString, #"data",
nil];
[facebook dialog:#"apprequests" andParams:params andDelegate:self];
}
Neither the "data" nor the "link" values in the params dictionary seem to have any effect. Ideally, when my app is launched from this request, I would get back the "data" or the "link" values. Can this be done?
I could not find any Facebook docs about the structure of params dictionary - is there a list of supported keys and their effect?

The "link" parameter and "notification_text" is not supported in iOS but you should be able to pass in data and get it back.
Example, passing in data:
FBSBJSON *jsonWriter = [FBSBJSON new];
NSDictionary *requestData = [NSDictionary dictionaryWithObjectsAndKeys:
#"data1", #"key1",
#"data2", #"key2",
nil];
NSString *requestDataString = [jsonWriter stringWithObject:requestData];
NSMutableDictionary* params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
message, #"message",
requestDataString, #"data",
nil];
[facebook dialog:#"apprequests"
andParams:params
andDelegate:self];
Example, reading it back:
....
#property (nonatomic, retain) NSURL *openedURL;
....
#synthesize openedURL = _openedURL;
....
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
self.openedURL = url;
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBSession.activeSession handleDidBecomeActive];
if (FBSession.activeSession.isOpen) {
[self checkIncomingNotification];
}
}
- (void) notificationGet:(NSString *)requestid {
[FBRequestConnection startWithGraphPath:requestid
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
NSString *title;
NSString *message;
if ([result objectForKey:#"data"]) {
// Process data in request
FBSBJSON *jsonParser = [FBSBJSON new];
NSDictionary *requestData =
[jsonParser
objectWithString:[result objectForKey:#"data"]];
[NSString stringWithFormat:#"Badge: %#, Karma: %#",
NSString *data1 = [requestData objectForKey:#"key1"];
NSString *data2 = [requestData objectForKey:#"key2"];
}
}
}];
}
- (void) checkIncomingNotification {
if (self.openedURL) {
NSString *query = [self.openedURL fragment];
if (!query) {
query = [self.openedURL query];
}
NSDictionary *params = [self parseURLParams:query];
// Check target URL exists
NSString *targetURLString = [params valueForKey:#"target_url"];
if (targetURLString) {
NSURL *targetURL = [NSURL URLWithString:targetURLString];
NSDictionary *targetParams = [self parseURLParams:[targetURL query]];
NSString *ref = [targetParams valueForKey:#"ref"];
// Check for the ref parameter to check if this is one of
// our incoming news feed link, otherwise it can be an
// an attribution link
if ([ref isEqualToString:#"notif"]) {
// Get the request id
NSString *requestIDParam = [targetParams
objectForKey:#"request_ids"];
NSArray *requestIDs = [requestIDParam
componentsSeparatedByString:#","];
// Get the request data from a Graph API call to the
// request id endpoint
[self notificationGet:[requestIDs objectAtIndex:0]];
}
}
// Clean out to avoid duplicate calls
self.openedURL = nil;
}
}
You can find more details on this, using the latest SDK v3.1:
https://developers.facebook.com/docs/howtos/send-requests-using-ios-sdk/

Related

How to tag friends in your Facebook wall post...?

I am trying to tag some of my friends in my wall post and I am sending the following parameters but this posts to my wall the FB ids I provide do not get attached to the post...
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Test 2 ",#"message",
#"100004311843201 , 1039844409", #"to",
#"http://www.google.com", #"link",
#"Test", #"name",
nil];
[self.appDelegate.facebook requestWithGraphPath:#"me/feed" andParams:params andHttpMethod:#"POST" andDelegate:self];
Any help is appreciated...
To tag a friend in ur fb status ..you need "facebook id" of your friend by using FBFriendPickerViewController and "place id" using FBPlacePickerViewController.
Following code will help you.
NSString *apiPath = nil;
apiPath = #"me/feed";
if(![self.selectedPlaceID isEqualToString:#""]) {
[params setObject:_selectedPlaceID forKey:#"place"];
}
NSString *tag = nil;
if(mSelectedFriends != nil){
for (NSDictionary *user in mSelectedFriends) {
tag = [[NSString alloc] initWithFormat:#"%#",[user objectForKey:#"id"] ];
[tags addObject:tag];
}
NSString *friendIdsSeparation=[tags componentsJoinedByString:#","];
NSString *friendIds = [[NSString alloc] initWithFormat:#"[%#]",friendIdsSeparation ];
[params setObject:friendIds forKey:#"tags"];
}
FBRequest *request = [[[FBRequest alloc] initWithSession:_fbSession graphPath:apiPath parameters:params HTTPMethod:#"POST"] autorelease];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[SVProgressHUD dismiss];
if (error) {
NSLog(#"Error ===== %#",error.description);
if (_delegate != nil) {
[_delegate facebookConnectFail:error requestType:FBRequestTypePostOnWall];
}else{
NSLog(#"Error ===== %#",error.description);
}
}else{
if (_delegate != nil) {
[_delegate faceboookConnectSuccess:self requestType:FBRequestTypePostOnWall];
}
}

Getting Facebook username for iOS

I'm using the following to get the Facebook username:
[facebook requestWithGraphPath:#"me" andDelegate:facebook];
from my understanding I then have to use something like the following request to
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Result: %#", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:#"name"];
fb_id = [userInfo objectForKey:#"id"];
}
my question is how do I call this request method from another method?
thanks for any help
check my function below to fetch user data id,pic and name
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
and in the delegate method you will log the name like this
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]] && [result count]>0) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"name"])
NSString *userName = [result objectForKey:#"name"];
NSLog(#"%#",userName);
}

Get friends info from Facebook on my iPhone app

I am developing an application for iPhone that uses facebook.
I need to get my data (the data of current user).
I'm sure I made the correct login and have obtained the proper permissions.
Now,
I want a NSArray with the data and make a print with NSLog oh this data.
I have made this for the friendlist and i have no problem:
-(IBAction)friendsInfo:(id)sender{
// get the logged-in user's friends
[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
//ok so it's a dictionary with one element (key="data"), which is an array of dictionaries, each with "name" and "id" keys
items = [(NSDictionary *)result objectForKey:#"data"];
for (int i=0; i<[items count]; i++) {
NSDictionary *friend = [items objectAtIndex:i];
long long fbid = [[friend objectForKey:#"id"]longLongValue];
NSString *name = [friend objectForKey:#"name"];
NSLog(#"id: %lld - Name: %#", fbid, name);
}
}
But for my info the same method not work:
-(IBAction)myInfo:(id)sender{
// get information about the currently logged in user
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
Can someone help me?
use this function to get your faceBook Info (logged in user info)
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
-(void)addList:(FBSession *)session {
NSString* fql = [NSString stringWithFormat:
#"select uid from user where uid == %lld", session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
sessionView = session;
[[FBRequest requestWithDelegate:self] call:#"facebook.friends.get" params:params];
}
- (void)request:(FBRequest*)request didLoad:(id)result {
if(myList==nil) {
NSArray* users = result;
myList =[[NSArray alloc] initWithArray: users];
for(NSInteger i=0;i<[users count];i++) {
NSDictionary* user = [users objectAtIndex:i];
NSString* uid = [user objectForKey:#"uid"];
NSString* fql = [NSString stringWithFormat:
#"select name from user where uid == %#", uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
}
else {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
txtView.text=[NSString localizedStringWithFormat:#"%#%#,\n",txtView.text,name];
}
}
-(IBAction)getMeFriendsButtonPressed:(id)sender {
FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:#"me/friends" withGetVars:nil];
NSLog(#"getMeFriendsButtonPressed: %#", fb_graph_response.htmlResponse);
NSDictionary *DictTmp = [fb_graph_response.htmlResponse JSONValue];
NSMutableArray *myFriendList=[[DictTmp objectForKey:#"data"];
}
NSString* fql = [NSString stringWithFormat:#"select uid,name from user where uid == %lld", session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
[[FBRequest requestWithDelegate:self] call:#"facebook.friends.get" params:params];

In ShareKit, how can I get the user's Facebook user name?

I'm using ShareKit and have verified that the user is logged in to Facebook. I want to get their Facebook user name. Here's what I tried:
SHKFacebook *facebook = [[SHKFacebook alloc] init];
[facebook getAuthValueForKey:#"username"];
The getAuthValueForKey: method isn't returning anything to me. How can I get their Facebook user name?
You can use Facebook Graph API for get username. Add method bellow to FBSession.m class of FBConnect package.
#import "JSON.h"
...........
static NSString *const kGraphAPIURL = #"https://graph.facebook.com/";
static NSString *const kFBGraphAPIUserName = #"name";
...........
// Get user name via Facebook GraphAPI.
- (NSString *)getUserNameByUID:(FBUID)aUID {
NSString *userName_ = nil;
NSURL *serviceUrl = [NSURL URLWithString:[NSString stringWithFormat:#"%#%qi", kGraphAPIURL, aUID]];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSError *error = nil;
NSString *jsonString = [NSString stringWithContentsOfURL:serviceUrl encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"######### error: %#", error);
}
if (jsonString) {
// Parse the JSON into an Object and
// serialize its object to NSDictionary
NSDictionary *resultDic = [jsonString JSONValue];
if (resultDic) {
userName_ = [resultDic valueForKey:kFBGraphAPIUserName];
}
}
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
return userName_;
}

How to send text and images using Facebook API in iPhone SDK?

In my iPhone app, I want to send text as well as images to facebook.
Currently the facebook API suggest that there are seperate user permissions that enable us to do so.
Is there a way out where in I can do both using only one API in my project?
If Yes, How can we do so?
References to any articles or tutorials would be very helpful
Please Help & Suggest.
Thanks
Yes you can do this.
Please have a look at all the methods as below:
- (IBAction)uploadPhoto:(id)sender {
[self postOnFacebook];
}
//Post Message and Photo on Facebook Function
-(void)postOnFacebook
{
NSString *strPostMessage = [self createMessageForPostOnFacebook:74.112 withLongitude:21.85];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:objClsProductSearch.strProductImageURL]]];
//UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg"]]];
UIImage *img = [[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://d1xzuxjlafny7l.cloudfront.net/wp-content/uploads/2011/08/HUDTutorial.jpg"]]];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
strPostMessage,#"message",img, #"source",
nil];
[_facebook requestWithGraphPath:#"/me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
}
//Create Message for posting on Facebook
-(NSString *)createMessageForPostOnFacebook:(double)pfltLatitude withLongitude:(double)pfltLongitude
{
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",pfltLatitude, pfltLongitude];
//NSString *urlString = [NSString stringWithFormat:#"http://maps.google.com/maps/geo?q=%f,%f&output=csv",#"", #""];
//NSError* error;
//NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString] encoding:NSASCIIStringEncoding error:&error];
//NSArray *listItems = [locationString componentsSeparatedByString:#","];
NSString *strMessage = nil;
/*if([[listItems objectAtIndex:0] isEqualToString:#"200"])
{
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d",objClsProductSearch.strCategoryname,[locationString substringFromIndex:6],appDelegate.dblLatitude,appDelegate.dblLongitude,btnTmp.tag];
}*/
strMessage = [NSString stringWithFormat:#"I found a %# using BH for iPhone \n Location : %# \n Latitude : %f & Longitude : %f \n Product Rating : %d", #"Cat Name", #"Location", 74.112, 21.85, 1];
return strMessage;
}
I hope you will have success using the above code.
Let me know in case of any difficulty.
In you app delegate, have a look at below methods whether it is implemented or not.
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
//return [[controller facebook] handleOpenURL:url];
//return [[objPage2ViewController facebook] handleOpenURL:url];
return [[[self.navigationController topViewController] facebook] handleOpenURL:url];
}
Cheers
I'm not sure that it is possible. I've post image with next solution:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
takedPhoto, #"picture",
#"some text", #"message",
nil];
[facebook requestWithGraphPath:#"/me/photos" andParams:params
andHttpMethod:#"POST" andDelegate:self];
takedPhoto is UIImage.
But it is only loading photos in photo album (and approve it if you allow permissions when logging in).
I don't know how can I post message on wall with this uploaded image...
Regards,