How to post a photo. iOS Facebook SDK 3.1 - facebook-graph-api

I needed to publish a picture on my wall. The pic is generated in my iPad app.

This is the simplest way I've found
- (void) postImageToFB:(UIImage*)image
{
NSData* imageData = UIImageJPEGRepresentation(image, 90);
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"This is my drawing!", #"message",
imageData, #"source",
nil];
[FBRequestConnection startWithGraphPath:#"me/photos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
}];
}
if you want to post on a friend's wall, change #"me/photos" by #"[friendID]/photos"
Then, ask for permissions to publish and call the method
if ([FBSession.activeSession.permissions indexOfObject:#"publish_stream"] == NSNotFound)
{
// No permissions found in session, ask for it
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error)
{
// If permissions granted, publish the story
if (!error) [self postImageToFB:currentDrawing];
}];
}
// If permissions present, publish the story
else [self postImageToFB:currentDrawing];
An "[App Name] Photos" album will be created, if doesn't exist
It does work for me!

For iOS from 4.3 and the UI look like iOS 6.0, I think you want something like this: IOS sharing framework for twitter, facebook, flicr, tumblr

Related

How to get Facebook User details in tvOS

i am using Facebook SDK in tvOS for Login. Currently i have used below code.
FBSDKDeviceLoginButton *button = [[FBSDKDeviceLoginButton alloc] initWithFrame:CGRectZero];
button.readPermissions = #[#"email"];
button.center = self.view.center;
[self.view addSubview:button];
first m confused at which Action can i use readPermissions = #[#"email"]; or publishPermissions = #[#"publish_actions"];
and then How to get user details like firstName, lastName, email, Birth date, and Id from facebook Responce
Getting details of the user can be accomplished by connecting to our Graph API once you have a valid token. For example, after a success login to get first name and last name:
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me?fields=first_name,last_name" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
}
}];
}
It is not same as mobile-sdk you should try graph api like how #chrispan is suggesting i've tried that & it is working perfectly. Just add as many fields you want in parameters and you'll get all the data which is set to public by user.
FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields" : "email, gender, name, birthday"]).startWithCompletionHandler({ (
FBSDKGraphRequestConnection connection, id result, let error: NSError? ) -> Void in
if(error == nil)
{
print("fetched user: %#", result)
}
})
Now, your question about permission. When user is signing up(first time) at that particular point you ask for "Read permission" and "Publish permission" is used when you want to post something to his/her timeline.

Using pre-signed S3 URL using AFNetworking to upload from an iOS app

I am trying to upload an image from my iPhone app to S3 and then store the S3 url back into my rails app. I am not supposed to embed credentials in the iOS app so the approach i'm taking is to:
Step 1. iPhone app sends a request to my rails server to return a pre-signed S3 URL for uploading the image.
Step 2. Rails server uses aws-sdk gem to generate and return a pre-signed URL How to store data in S3 and allow user access in a secure way with rails API / iOS client?
Step 3. iPhone app uses AFNetworking to post the NSData of the image to S3.
I did my best to follow all the directions I found online but it's not working and the result of step 3 returns Error 401 forbidden. Since I am a newbie at this I don't even know what I am doing wrong.
In Step 2, my code looks like this:
def getS3Url
s3 = AWS::S3.new(
:access_key_id => "MY S3 KEY",
:secret_access_key => "MY SECRET ACCESS KEY"
)
object = s3.buckets[params["bucket"]].objects[params["path"]]
#s3url = object.url_for(:write, { :expires => 20.minutes.from_now, :secure => true }).to_s
end
The url returned from step2 looks something like this: https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature]
And once i get that URL i try to post to it by doing the following:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST:[responseObject valueForKey:#"s3url"] parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:jpegData name:#"file" fileName:self.filename mimeType:#"image/png"];
} success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Success: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
In this code I extract the url out from the returned object with [responseObject valueForKey:#"s3url"], and then pass that as the URL to post. But it doesn't work. Here's the log when i run it in XCode:
Error: Error Domain=AFNetworkingErrorDomain Code=-1011 "Request failed: forbidden (403)" UserInfo=0x156daaf0 {NSErrorFailingURLKey=https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature], NSLocalizedDescription=Request failed: forbidden (403), NSUnderlyingError=0x156aef90 "Request failed: unacceptable content-type: application/xml", AFNetworkingOperationFailingURLResponseErrorKey= { URL: https://s3.amazonaws.com/myapp-bucket-name/images/avatar/user1.png?AWSAccessKeyId=[access key id]&Expires=[expiration timestamp]&Signature=[Signature] } { status code: 403, headers {
Connection = close;
"Content-Type" = "application/xml";
Date = "Mon, 30 Jun 2014 07:21:33 GMT";
Server = AmazonS3;
"Transfer-Encoding" = Identity;
"x-amz-id-2" = "FJwEeOjV1/osJKgKeHO+/OjXVBEbvW09XxNX2kn1UYIuHswU+LKh0mJODRJDNLXm";
"x-amz-request-id" = 46E84D0967B6D4CD;
} }}
At this point I don't even know what I am doing wrong. Maybe I'm not even posting to the correct URL. Maybe I need to do more than just POST. I spent the entire weekend trying to figure this out and failed. Could someone please help? Thanks.
I faced a similar "challenge". I had to upload with AFNetworking 2.0 an image to an S3 bucket with a pre-signed URL from my server. In one of my many try and error attempts of doing it I got the same 403 error, and what happened to me was that I had to put the right headers in the request:
Content-Type with the mime type of the image
x-amz-acl as public-read for my bucket configuration
The Content-Length seemed to be optional and note that I haven't uploaded the image in multipart.
So this is what I ended up doing:
+(void) uploadImage:(UIImage *)image atUrl:(NSString *)url withMimeType:(NSString *)mimeType withSuccess:(void (^)(id responseObject))success failure:(void (^)(NSError *error))failure {
NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
NSURL *requestURL = [NSURL URLWithString:url];
AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:requestURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setHTTPMethod:#"PUT"];
[request setValue:mimeType forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:imageData];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[imageData length]] forHTTPHeaderField:#"Content-Length"];
[request setValue:#"public-read" forHTTPHeaderField:#"x-amz-acl"];
[request setURL:requestURL];
NSURLSessionDataTask *task = [client dataTaskWithRequest:request completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error == nil) {
if (success) {
success(responseObject);
}
} else {
if (failure) {
failure(error);
}
}
}];
[task resume];
}
where url is the presigned url that I've got from my server. Check the JPEG compression that I have at 0.1 as you might want a different compression. In my case the image quality is not important.
Adding to josebama's answer above,
I didnt need to add "x-amz-acl" header field, but instead I added "x-amz-date" and "authorization" headers. Both these headers were returned, from the an API that handled communication with Amazon service, along with a signed URL. The upload to the URL was only successful when I added the two aforementioned header values.
Simply including the "x-amz-acl" header, in my case, would result in a failure to upload.
Perhaps some server side parameters differ or perhaps some setup parameters for amazon vary, needless to say that a solution that works for me might not work for others so it might be good a idea to look at your backend setup a bit..

code to invite facebook friend in ios 7?

I am new in IOS development?
In my project I want to invite Facebook friend.when Facebook app is installed and not installed in both cases i want to invite my friend?
how can be done
//Below is my code
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just smashed friends! Can you beat it?"]
title:#"StopNSwap"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// Case B: User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
NSLog(#"Request Sent.");
}
}}
friendCache:nil];
As far as I understand you are trying to send an app-to-user request to invite user's Facebook friends to start using your application, correct? Checkout the first answer here, Paul suggests an effective way of doing it using the Facebook SDK : How to send add friend request (to facebook user) from iOS application?

Facebook Posting on page's wall instead of user's wall

I am using oauth to get offline access token for facebook.
With user (wall) access token, image/text is posted on wall which is right.
But when I use page access token to post some thing on Page than it is not posting on page instead it is posting on user's wall.
Can anyone help me please...
Do it like this. It will work. Replace pageID with your own pageID at which u want to post.
NSMutableDictionary *variablesForEvent=[NSMutableDictionary dictionaryWithCapacity:1];
[variablesForEvent setObject:#"my message" forKey:#"message"];
NSString *postToFBEventRequest = [NSString stringWithFormat:#"%#/feed",#"pageID"];
[FBRequestConnection startWithGraphPath:postToFBEventRequest
parameters:variablesForEvent
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
}];

Video posting to Facebook wall

How to post a recorded video into Facebook wall with message and please tell me is there any possibility for posting a video into Facebook.
Please check this article :How-To: Use the Graph API to Upload a Video (iOS)
- (void)fbDidLogin {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"sample" ofType:#"mov"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[facebook requestWithGraphPath:#"me/videos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}