how can I post large video on facebook sdk in iOS? - iphone

I am using facebook sdk for uploading videos, but I am not able to upload more than 60MB video on facebook. I tried a lot using NSInputStream also for sending data and all :-
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];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/videos" parameters:params HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"result: %#, error: %#", result, error);
}];

Use dataWithContentsOfFile:options instead. Doesn't try to load all the data into memory, which may make your app getting closed by iOS:
NSData *videoData = [NSData dataWithContentsOfFile:video.localURL options:NSDataReadingMappedAlways error:&error];

Related

uploading video to Facebook error 5

I am trying to upload a video from my iPhone to Facebook. I have logged in using FBLoginView and created a FBSession. I have used the following code to initiate a FBRequest of upload the video.
- (void)buttonRequestClickHandler:(id)sender {
if (FBSession.activeSession.isOpen) {
[FBSession.activeSession requestNewPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:nil];
NSString *audioName = [pictureDictionary4 objectForKey:#"photoVideokey"];
NSArray *pathsa = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectorya = [pathsa objectAtIndex:0];
NSString *moviePath = [documentsDirectorya stringByAppendingPathComponent:#"/Movie"];
NSString *fullPatha = [moviePath stringByAppendingPathComponent:audioName];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:fullPatha isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:fullPatha];
NSString *titleString = self.videotitle.text;
NSString *descripString = self.descrp.text;
NSDictionary *videoObject = #{
#"title":titleString,
#"description": descripString,
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos"
parameters:videoObject
HTTPMethod:#"POST"];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog(#"Done: %#", result);
else
NSLog(#"Error: %#", error.localizedDescription);
}];
}
I get an error
Error: The operation couldn’t be completed. (com.facebook.sdk error 5.)
I'm not sure what the error pertains to:
I know I'm logged in
I don't know if I am getting connected but I am on internet with iPhone
Are my parameters incorrect?
I have been messing with this for HOURS with no results
Any help from anyone/everyone would be greatly appreciated.
Finally got this working by going into my iPhone settings-facebook and deleting my account. Then when I tapped to upload the video in my app it loaded a view that asked if Facebook could use my app and I said yes then bam it uploaded. Also had to change my permissions to just publish_actions and get rid of publish_streams since that is a read permission. Anyway it is working now. Next to get defaultAudience to load from a string picked by user and not hard coded. Another post.
I guess its something to do with stream publishing permission. Try this way. It worked for me. I was using Facebook SDK 3.8.0
[self performPublishAction:^{
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"faisal" ofType:#"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSDictionary *videoObject = #{
#"title": #"This is my title",
#"description": #"This is my description",
[pathURL absoluteString]: videoData
};
FBRequest *uploadRequest = [FBRequest requestWithGraphPath:#"me/videos"
parameters:videoObject
HTTPMethod:#"POST"];
[uploadRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
NSLog(#"Done: %#", result);
else
NSLog(#"Error: %#", error.localizedDescription);
}];
}];
and
- (void) performPublishAction:(void (^)(void)) action {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_stream"] == NSNotFound) {
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
} else if (error.fberrorCategory != FBErrorCategoryUserCancelled){
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Permission denied"
message:#"Unable to get permission to post"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}];
} else {
action();
}
}
This Code is Tested successfully On FaceBook SDK 3.14.1
Recommendation: 3 properties in .plist file
set FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb See
-(void)shareOnFaceBook
{
//sample_video.mov is the name of file
NSString *filePathOfVideo = [[NSBundle mainBundle] pathForResource:#"sample_video" ofType:#"mov"];
NSLog(#"Path Of Video is %#", filePathOfVideo);
NSData *videoData = [NSData dataWithContentsOfFile:filePathOfVideo];
//you can use dataWithContentsOfURL if you have a Url of video file
//NSData *videoData = [NSData dataWithContentsOfURL:shareURL];
//NSLog(#"data is :%#",videoData);
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType",
#"Video name ", #"name",
#"description of Video", #"description",
nil];
if (FBSession.activeSession.isOpen)
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
NSLog(#"RESULT: %#", result);
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
}
else
{
NSLog(#"ERROR: %#", error.localizedDescription);
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
}
}];
}
else
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_actions",
nil];
// OPEN Session!
[FBSession openActiveSessionWithPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error)
{
NSLog(#"Login fail :%#",error);
}
else if (FB_ISSESSIONOPENWITHSTATE(status))
{
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if(!error)
{
[self throwAlertWithTitle:#"Success" message:#"Video uploaded"];
NSLog(#"RESULT: %#", result);
}
else
{
[self throwAlertWithTitle:#"Denied" message:#"Try Again"];
NSLog(#"ERROR: %#", error.localizedDescription);
}
}];
}
}];
}
}
And I GOT Error:
The operation couldn’t be completed. (com.facebook.sdk error 5.)
It happens when facebook is being inited. Next time i open my app, it works fine, its always the first time. Tried everything in app, but it seems to be on the Facebook SDK side.
Few causes for seeing com.facebook.sdk error 5:
Session is is not open. Validate.
Facebook has detected that you're spamming the system. Change video name.
Facebook has a defined limit using the SDK. Try a different app.
Wrong publish permission. Give publish_actions a spin.

Share image from bundle and link on Facebook in iphone

I want to share image,link etc to Facebook from my iphone app.My app Link,cation,name and description posted successfully. But i can't share image. Please follow my code..
UIImage *image = [UIImage imageNamed:#"sample.png"];
NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
self.dictionary =[[NSMutableDictionary alloc] initWithObjectsAndKeys: #"https://www.google.com/ios", #"link",
imgData, #"data",
#"AppName", #"name",
#"Testing", #"caption",
#"say something about this", #"description",
nil];
my share facebook code is..
[facebook requestWithGraphPath:#"/me/feed" andParams:dictionary andHttpMethod:#"POST" andDelegate:self];
My problem is how to take image from bundle and how to share selected image to Facebook?Please help me..
use like below:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"image1" ofType:#"png"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"My hat image", #"message", data, #"source", nil];
[facebook requestWithGraphPath:#"/me/photos" andParams:params andHttpMethod:#"POST" andDelegate:self];

How To upload Video on Facebook using FBConncet?

In my application i am trying to upload Video on facebook wall using FbConnect my Code looks oky But i Don't know why my Video is not uploaded Beacuse if i use the Same Code method for Uploading image it successfully upload the image on facebook.here is my code which i use for image uploading
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"2" ofType:#"png"];
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfFile:filePath];
UIImage *img = [[UIImage alloc] initWithData:data];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, #"Picture",
nil];
[_facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
And for Video i am trying this Code so For
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myVideo" ofType:#"mp4"];
NSURL *url = [NSURL URLWithString:filePath];
NSData *videoData = [NSData dataWithContentsOfURL:url];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mp4",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[_facebook requestWithGraphPath:#"me/videos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
The Above code give me no error but it retun some text msg in label (the operation Could not be completed).Which is not in case of image uploading.So can some guide me how to fix it.Thanks
Try these lines:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"myVideo" ofType:#"mp4"];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mp4",
#"video/quicktime", #"contentType",
#"Video Test Title", #"title",
#"Video Test Description", #"description",
nil];
[_facebook requestWithGraphPath:#"me/videos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Hope this help you.its working fine for me.Now add these lines.
http://stackoverflow.com/questions/10509984/how-to-upload-mp4-video-on-facebook-using-graph-api-in-objective-c
http://%5B1%5D:%20https://github.com/reallylongaddress/iPhone-Facebook-Graph-API
http://stackoverflow.com/questions/12861615/upload-video-to-facebook-using-facebook-new-sdk-on-ios-6-0

upload Video to Facebook using iOS6 Social Framework

I want to publish a video file to facebook. Previously I used the Facebook iOS SDK3.0 and it works. However, for iOS6 Social Framework, there is problem.
__block ACAccount * facebookAccount;
ACAccountStore* accountStore = [[ACAccountStore alloc] init];
NSDictionary *options = #{
ACFacebookAppIdKey: #"MY APP ID",
ACFacebookPermissionsKey: #[#"publish_actions", ],
#"ACFacebookAudienceKey": ACFacebookAudienceFriends
};
ACAccountType *facebookAccountType = [accountStore
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [accountStore
accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSLog(#"access to facebook account ok %#", facebookAccount.username);
NSData *videoData = [NSData dataWithContentsOfFile:[self videoFileFullPath]];
NSLog(#"video size = %d", [videoData length]);
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
videoData, #"video.mov",
#"video/quicktime", #"contentType" ,
#"Video title", #"title",
#"Video description", #"description",nil];
NSURL *requestURL = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:requestURL
parameters:params];
request.account = facebookAccount;
[request performRequestWithHandler:^(NSData *data, NSHTTPURLResponse *response,NSError * error){
NSLog(#"response = %#", response);
NSLog(#"error = %#", [error localizedDescription]);
}];
} else {
NSLog(#"access to facebook is not granted");
// extra handling here if necesary
}
}];
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[NSConcreteData
_fastCharacterContents]: unrecognized selector sent to instance 0x2097ead0'
Here is my research:
First, the video data cannot be part of the parameter list, since it will render the SLRequest invalid and that is the crash you are experiencing.
The video data must go in the multi part section of the request.
Now,there is a need to associate the parameters with the multipart data and that is the tricky part. So it is necessary to use the source attribute to make that link.
Source requires a URL in a string format set it in the parameters and set the same value in the filename field in the multipart request.
That should do it.
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
NSURL *videoPathURL = [[NSURL alloc]initFileURLWithPath:videoPath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:videoPath];
NSString *status = #"One step closer.";
NSDictionary *params = #{#"title":status, #"description":status};
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
[request addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[videoPathURL absoluteString]];
I'm working the same issue. I think your error is from ARC and NSData *videoData gets deleted before the return from performRequestWithHandler.

How to Upload Photos on facebook using Graph API in iPhone?

I have made one application, In my application I have integrate Facebook for sharing information.
for Facebook integration I have use Graph API in application.
now In my application, I want to upload photo on user's wall.
I have use this code for upload photo on user's wall.
// for upload photo
- (void)uploadPhoto:(id)sender {
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Image1" ofType:#"jpg"];
NSString *message = [NSString stringWithFormat:#"I think this is a Great Image!"];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/photos"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request addFile:filePath forKey:#"file"];
[request setPostValue:message forKey:#"message"];
[request setPostValue:_accessToken forKey:#"access_token"];
[request setDidFinishSelector:#selector(sendToPhotosFinished:)];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)sendToPhotosFinished:(ASIHTTPRequest *)request {
// Use when fetching text data
NSString *responseString = [request responseString];
NSMutableDictionary *responseJSON = [responseString JSONValue];
NSString *photoId = [responseJSON objectForKey:#"id"];
NSLog(#"Photo id is: %#", photoId);
NSString *urlString = [NSString stringWithFormat:
#"https://graph.facebook.com/%#?access_token=%#", photoId,
[_accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *newRequest = [ASIHTTPRequest requestWithURL:url];
[newRequest setDidFinishSelector:#selector(getFacebookPhotoFinished:)];
[newRequest setDelegate:self];
[newRequest startAsynchronous];
}
But, here I get
responseString is {"error":{"message":"Error validating application.","type":"OAuthException"}} and
Photo id is: (null)
and Image is not upload on user's wall.
so, please tell me how to solve it.
First have you authorized your application to upload pictures by doing this (using the FBConnect SDK), you can checkout all permissions here
NSArray* permissions = [NSArray arrayWithObjects:#"publish_stream", #"user_photos", nil];
[facebook authorize:permissions];
The next problem is that facebook does not allow posts sent in this way to link to pictures hosted on their domains (I know it's REALLY annoying, maybe it would be worth checking if things have changed since april). I spent quite a bit of time working this one out. The way I cracked it was to create a redirect URL using bitly (you can access their services programatically using their API, there's an obj-c wrapper for it here, although I changed it to be asynchronous) and send that URL in the post.
may help u
//facebook post a image on wall
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
userImgView.image, #"picture",
nil];
[facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
another way is bellow for post image on Facebook ...
NSMutableDictionary *variables = [NSMutableDictionary dictionaryWithCapacity:2];
//create a UIImage (you could use the picture album or camera too)
UIImage *picture = [UIImage imageNamed:"yourImageName"];
//create a FbGraphFile object insance and set the picture we wish to publish on it
FbGraphFile *graph_file = [[FbGraphFile alloc] initWithImage:picture];
//finally, set the FbGraphFileobject onto our variables dictionary....
[variables setObject:graph_file forKey:#"file"];
[variables setObject:#"write your Message Here" forKey:#"message"];
//the fbGraph object is smart enough to recognize the binary image data inside the FbGraphFile
//object and treat that is such.....
//FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"117795728310/photos" withPostVars:variables];
FbGraphResponse *fb_graph_response = [fbGraph doGraphPost:#"me/photos" withPostVars:variables];
hope , this help you...
:)
The facebook API uses OAuth to authenticate requests. You will need to use a library that can request the appropriate temporary/client tokens, and generate the appropriate HTTP headers for requests. This is quite a complicated procedure which involves hashing and normalizing of request arguments.
You cannot do this crafting your own manual HTTP requests .
You can use facebook's native function
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: UIImageJPEGRepresentation(postImage, 1.0), #"source", self.postTextView.text, #"message", nil];
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me/photos" parameters:params HTTPMethod:#"POST" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if (error == nil) {
NSLog("Success");
}
else {
NSLog("Failed");
}
}];
Using this code you can post image with message.
Best regards