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

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,

Related

sharing text on "facebook Page" in ios from our app

I have a Facebook page, and i want to share some text on that page just like my status as we share on our "me/feed" from our application.
Please someone suggest how i should go about it?
for iOS 6.0 you can do something like that:
NSString *text1 = [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"Check out this nice'... ", #""), self.title];
NSString *text2 = [NSString stringWithFormat:#"%# %#", NSLocalizedString(#"in", #""), self.restaurant.title];
NSString *text3 = NSLocalizedString(#"Sent from FoodRock Menus App", #"");
NSURL *appURL = [NSURL URLWithString:#"http://testappstorelink.com"];
NSArray *activityItems = [NSArray arrayWithObjects:text1, text2, text3, appURL, photo, nil];
UIActivityViewController *actVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems
applicationActivities:nil];
actVC.excludedActivityTypes = [NSArray arrayWithObjects:UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard,
UIActivityTypePrint, UIActivityTypeSaveToCameraRoll, nil];
actVC.completionHandler = ^(NSString *activityType, BOOL completed){
DLog(#"ACTIVITYTYPE: %# FINISHED: %#", activityType, completed ? #"YES" : #"NO");
if (completed) {
NSString *socialString = #"";
if ([activityType containsSubstring:#"PostToTwitter"]) {
socialString = #"Twitter";
} else if ([activityType containsSubstring:#"PostToFacebook"]) {
socialString = #"Facebook";
} else if ([activityType containsSubstring:#"Message"]) {
socialString = #"Message";
} else if ([activityType containsSubstring:#"Mail"]) {
socialString = #"Mail";
}
[[FRNWAchievementsController controller] reportSocialShareEvent:socialString menuItem:self];
}
};
return actVC;
Here are some code snippets to help you out, but you should also have a look at the Facebook developer examples which are pretty good.
// To log in to Facebook with permission to post...
m_Facebook = [[Facebook alloc] initWithAppId:YOUR_FACEBOOK_APPID
andDelegate:self];
m_FacebookPermissions = [[NSArray
arrayWithObjects:/*#"read_stream",*/ #"publish_stream", nil] retain];
[m_Facebook authorize:m_FacebookPermissions];
And in some other method after the fbDidLogin callback tells you you're logged in:
// After successful login…
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
WHAT_YOU_WANT_TO_SAY, #"message",
nil];
[m_Facebook requestWithGraphPath:#"/me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];

Image Post on Facebook?

In my application. I successfully post a image on my Facebook wall (image type JPEG Type). It's work fine in Simulator and and Device also.
But the problem is that When I Capture Image from my iPhone or select an image from library which is captured by camera. It is not Posted on Facebook Wall.
on other hand when i choose any jpeg image (downloaded by internet) from my iPhone library. It post on wall.
In my opinion there is image format problem. Please Guide me
Thanks
My code is here.
-(IBAction)clickButtonClicked
{
// For link post
NSString *Message = [NSString stringWithFormat:#"Testing Iphone App : \"http://www.google.com\" "];
DataClass *obj=[DataClass getInstance];
UIImage *image=[[UIImage alloc]init ];
image= obj.imgFinalImage;
NSMutableDictionary *params1 = [[NSMutableDictionary alloc]init];
[params1 setObject:image forKey:#"source"];
[params1 setObject:Message forKey:#"message"];
NSString *post=#"/me/photos";
[[appDelegate facebook] requestWithGraphPath:post andParams:params1 andHttpMethod:#"POST" andDelegate:self];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Message!" message:#"Invitation Send Sucessfully" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[alert release];
}
My guess is that you pass the image in the wrong property:
NSMutableDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
sobj.imgFinalImage, #"picture",
Message, #"caption",
nil];
[[appDelegate facebook] requestWithMethodName:#"photos.upload"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Then make sure you implement the delegate of Facbook request to check if the image is uploaded.
With the graph API you can't send a UIImage directly, you need to send the NSData representation of the UIImage:
NSMutableDictionary *params1 = [[NSMutableDictionary alloc]init];
NSData *imageDate = UIImagePNGRepresentation(obj.imgFinalImage);
[params1 imageDate forKey:#"source"];
[params1 setObject:Message forKey:#"message"];
NSString *post=#"/me/photos";
[[appDelegate facebook] requestWithGraphPath:post andParams:params1 andHttpMethod:#"POST" andDelegate:self];

How to attach data to Facebook app request on the 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/

uploading image in facebook

While uploading image in facebook wall, image is not at all getting on the wall.
I tried:
[[FBRequest requestWithDelegate:self] call:#"facebook.Users.setStatus" params:
params dataParam:UIImagePNGRepresentation(img)];
to no avail.
You can do it using Sharekit....
Try this code...
-(void)shareOnFacebook {
//take screenshot
UIImage *image = "Your image";
//for debug purpose the image can be stored to photo album
//UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
SHKItem *fbItem = [SHKItem image:image title:#"Check out my Image!"];
[SHKFacebook shareItem:fbItem];
}
Using sharekit you can try following code:
-(IBAction)btnSendToFacebookPressed:(id)sender
{
NSString *var = [[NSUserDefaults standardUserDefaults] valueForKey:#"IMAGE_INDEX"];//This line may not be useful to you...
NSString *imageIndex = [[NSBundle mainBundle] pathForResource:var ofType:#"jpg"];
SHKItem *item = [SHKItem image:[UIImage imageWithContentsOfFile:imageIndex] title:#"Your Title"];
[NSClassFromString(#"SHKFacebook") performSelector:#selector(shareItem:) withObject:item];
}
Try to do it using Sharekit.
Add Sharekit framework to your project.
Change the setting from shkconfig.h file.
pass the key which you can generate from facebook->developer->apps->create new app->generate keys pass it to shkconfig.h
-(IBAction) tryItOnFb:(id)sender
{
SHKItem *item = [SHKItem image:[UIImage imageNamed:#"YES.png"]title:#"FB Test"];
[NSClassFromString(#"SHKFacebook") performSelector:#selector(shareItem:) withObject:item];
}
Images will get into your photo Album and information about it on the wall.
NSMutableDictionary *params =[NSMutableDictionary dictionaryWithObjectsAndKeys:#"Testmessage", #"message", imageData, #"picture", nil];
[facebook requestWithGraphPath:#"/me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];

How to post a photos on facebook through iPhone app?

I am trying to post image on facebook but not successful yet,
my codes are:
- (void)postToWall{
int im = 1;
NSData *myimgData;
myimgData = [NSData dataWithContentsOfFile:saveImagePath];
//pstimg = myimgData;
NSArray *chunks = [pstimg componentsSeparatedByString: #"."];
NSString *atch= [chunks objectAtIndex: 0];
NSString *filePath = [[NSBundle mainBundle] pathForResource:atch ofType:#"jpg"];
img = [[UIImage alloc] initWithContentsOfFile:filePath];
//start
FBDialog* dialog = [[[FBStreamDialog alloc] init] autorelease];
NSString *str = #"Hello";
str = [str stringByReplacingOccurrencesOfString:#" " withString:#"+"];
dialog.cMessage=str;
dialog.userMessagePrompt = #"Enter your message:";
[dialog show];
NSData * findata;
//edited from here
if(im==1)
{
findata = myimgData;
}
else
{
findata = (NSData *)img;
}
NSMutableDictionary * param = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, #"picture",
nil];
FBRequest *uploadPhotoRequest =[FBRequest requestWithDelegate:self] ;
[uploadPhotoRequest call:#"facebook.photos.upload" params:param dataParam:myimgData];
[img release];
}
But it not posted.
To post a photo on Facebook you need to use the iOS SDK from Facebook:
https://github.com/facebook/facebook-ios-sdk
There you'll find sample app with authentication and much more, like posting a photo.