How to post the Theta 360 degree photo to facebook in ios - ios

I am using the Theta Camera SDK to take the picture in 360 degrees.
I want to post this photo to Facebook this is 360 photo.
UIImage *image = [UIImage imageNamed:#"IMG_0133.JPG"];
NSString *token = [NSString stringWithFormat:#"%#", [FBSDKAccessToken currentAccessToken].tokenString];
NSDictionary *param = #{#"message": #"test",
#"access_token": token,
#"photo":image,
#"allow_spherical_photo": [NSNumber numberWithBool:true]
};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/photos"
parameters:param
HTTPMethod:#"post"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error)
{
if (!error)
{
NSLog(#"post success");
}
}];
but it was post like normal image not with 360 view

UIImage *image = [[UIImage alloc]initWithData:[[NSUserDefaults standardUserDefaults] objectForKey :#"image_NSdata]];
NSData *imgData = UIImageJPEGRepresentation(image, 1);
NSLog(#"Size of Image(bytes):%ld",(unsigned long)[imgData length]);
float actualHeight = image.size.height;
float actualWidth = image.size.width;
NSDictionary * postDictionary = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:#"equirectangular", [NSNumber numberWithFloat:actualWidth] ,[NSNumber numberWithFloat:actualHeight], [NSNumber numberWithFloat:actualWidth] ,[NSNumber numberWithFloat:actualHeight], #"0",#"0", nil]
forKeys:[NSArray arrayWithObjects:#"ProjectionType", #"CroppedAreaImageWidthPixels",#"CroppedAreaImageHeightPixels", #"FullPanoWidthPixels",#"FullPanoHeightPixels", #"CroppedAreaLeftPixels",#"CroppedAreaTopPixels", nil]];
NSError * error = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDictionary options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultAsString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"jsonData as string:\n%# Error:%#", resultAsString,error);
NSString *token = [NSString stringWithFormat:#"%#", [FBSDKAccessToken currentAccessToken].tokenString];
NSDictionary *param = #
{
#"access_token": token,
#"photo":image,
#"allow_spherical_photo": [NSNumber numberWithBool:true],
#"spherical_metadata":resultAsString
};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/photos"
parameters:param
HTTPMethod:#"post"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error)
{
if (!error)
{
NSLog(#"post success");
}
}];

I wrote a framework for this exact purpose:
https://github.com/AppCoders-io/Facebook360
Assuming that you've requested the permission to share, this is what you'd use:
[[Facebook360Manager sharedInstance] shareImage:[UIImage imageNamed:#"spherical360.jpg"]
userCaption:#"Example caption..."
horizontalFOV:360.0
sharePreference:FacebookShareManagerPreferenceSphericalImage
completionBlock:^(NSError * _Nullable error, NSString * _Nullable postID) {
if (error) {
NSLog(#"Error: %#",error);
}else{
NSLog(#"Shared successfully. Post ID: %#",postID);
}
}];

Related

How to get Email param of facebook using SLRequest in iOS Social Framework

I tried the below code for getting email of the person who logged in iOS Settings Facebook.
Please help me how to get email from SLRequest.
- (void) getMyDetails {
if (! _accountStore) {
_accountStore = [[ACAccountStore alloc] init];
}
if (! _facebookAccountType) {
_facebookAccountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
}
NSDictionary *options = #{ ACFacebookAppIdKey: FB_APP_ID };
[_accountStore requestAccessToAccountsWithType: _facebookAccountType
options: options
completion: ^(BOOL granted, NSError *error) {
if (granted) {
NSArray *accounts = [_accountStore accountsWithAccountType:_facebookAccountType];
_facebookAccount = [accounts lastObject];
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:url
parameters:nil];
request.account = _facebookAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingMutableContainers
error:nil];
NSLog(#"id: %#", responseDictionary[#"id"]);
}];
}
}];
}
Here is the code tested on iOS 8 that returns email. The solution doesn't require Facebook SDK, although the system grants access to Facebook account only if a user logged in with Facebook in Settings app.
// Required includes
#import Accounts;
#import Social;
// Getting email
ACAccountStore *theStore = [ACAccountStore new];
ACAccountType *theFBAccountType = [theStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *theOptions = #{
ACFacebookAppIdKey : #"YOUR_APP_ID",
ACFacebookPermissionsKey : #[#"email"]
};
[theStore requestAccessToAccountsWithType:theFBAccountType options:theOptions completion:^(BOOL granted, NSError *error) {
if (granted) {
ACAccount *theFBAccount = [theStore accountsWithAccountType:theFBAccountType].lastObject;
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://graph.facebook.com/me"]
parameters:#{#"fields" : #[#"email"]}];
request.account = theFBAccount;
[request performRequestWithHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error == nil && ((NSHTTPURLResponse *)response).statusCode == 200) {
NSError *deserializationError;
NSDictionary *userData = [NSJSONSerialization JSONObjectWithData:data options:0 error:&deserializationError];
if (userData != nil && deserializationError == nil) {
NSString *email = userData[#"email"];
NSLog(#"%#", email);
}
}
}];
}
}];
You can get email id by below mentioned way.
Call Facebook graph API by the help of access token that you got from Account store
And yes, to get email id from Facebook, you need to provide "email" permission while requesting access token, without the permission you won't be able to get email parameter
Here is my code
NSString *FB_EncodedToken = [APP_CONSTANT.facebookToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
AFHTTPRequestOperationManager *opearation = [AFHTTPRequestOperationManager manager];
opearation.requestSerializer = [AFHTTPRequestSerializer serializer];
opearation.responseSerializer = [AFJSONResponseSerializer serializer];
NSString *strUrl = [NSString stringWithFormat:#"https://graph.facebook.com/me?"];
NSDictionary *param = [NSDictionary dictionaryWithObjectsAndKeys:FB_EncodedToken,#"access_token", nil];
[opearation GET:strUrl parameters:param success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLogs(#"Description %#",responseObject);
//Lets pasre the JSON data fetched from facebook
[self parseUserDetail:responseObject];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLogs(#"Error description %#",error.description);
self.completionHandler(error);
}];
Then parse the data
-(void)parseUserDetail:(NSDictionary *)dict
{
FBProfileBO *profile = [[FBProfileBO alloc] init];
profile.userFirstName = [dict objectForKey:#"first_name"];
profile.userLastName = [dict objectForKey:#"last_name"];
profile.userEmail = [dict objectForKey:#"email"];
profile.userName = [dict objectForKey:#"name"];
profile.userDOB = [dict objectForKey:#""];
profile.facebookId = [dict objectForKey:#"id"];
//Call back methods
self.completionHandler(profile);
profile = nil;
}

video share on facebook

I am making a test app through that I want to post a video on facebook. I am using latest sdk of facebook. But I am not able to post it on facebook. The video is coming from web service.
How to convert video url in nsdata and mu code is below
NSString *astrUserid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"user_id"];
NSString *astrImageid=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"image_id"];
NSString *astrExt=[[mutTimeline objectAtIndex:indexpath] objectForKey:#"ext"];
NSString *aStrDisplyimage=[NSString stringWithFormat:#"http://followme.pmcommu.com/audio/user/%#-%#.%#",astrUserid, astrImageid,astrExt ];
NSURL *aimageurl=[NSURL URLWithString:aStrDisplyimage];
NSString *filePathOfVideo = [aimageurl path];
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);
}
}];
}
}];
}
I am new for that can any one help me please
or this will help you for upload and streaming video, i think
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *facebookAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
// Specify App ID and permissions
NSDictionary *options = #{ACFacebookAppIdKey: FACEBOOK_ID,
ACFacebookPermissionsKey: #[#"publish_stream", #"video_upload"],
ACFacebookAudienceKey: ACFacebookAudienceFriends}; // basic read permissions
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accountsArray = [accountStore accountsWithAccountType:facebookAccountType];
if ([accountsArray count] > 0) {
ACAccount *facebookAccount = [accountsArray objectAtIndex:0];
NSDictionary *parameters = #{#"description": aMessage};
SLRequest *facebookRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:[NSURL URLWithString:#"https://graph.facebook.com/me/videos"]
parameters:parameters];
[facebookRequest addMultipartData: aVideo
withName:#"source"
type:#"video/mp4"
filename:#"video.mov"];
facebookRequest.account = facebookAccount;
[facebookRequest performRequestWithHandler:^(NSData* responseData, NSHTTPURLResponse* urlResponse, NSError* error) {
if (error == nil) {
NSLog(#"responedata:%#", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
}else{
NSLog(#"%#",error.description);
}
}];
}
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[e localizedDescription]);
}
}];
Get the publish permission
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
Try this
- (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];
}
try this
[NSData dataWithContentsOfURL:[NSURL URLWithString:#"Your URL"]]
-(void)facbookSharng {
NSLog(#"Permission for sharing..%#",[FBSDKAccessToken currentAccessToken].permissions);
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"contact_email"])
{
FBSDKShareVideo *ShareVideo = [FBSDKShareVideo videoWithVideoURL:appDelegateObj.finalVideoUrl];
ShareVideo.videoURL = appDelegateObj.finalVideoUrl;
FBSDKShareVideoContent *ShareContnt = [[FBSDKShareVideoContent alloc] init];
ShareContnt.video = ShareVideo;
[FBSDKShareAPI shareWithContent:ShareContnt delegate:self]
// write the deleate methdo for post ID..
}

upload photo to photo album on Facebook using iOS sdk

I am trying to create a new album on a user's Facebook account, and upload images to that album. I have succeeded to create an album, but when I start uploading images to it only the last image selected gets uploaded the number of times the images I have selected.
This is my piece of code to create a Facebook album and upload images to it
- (void)createFacebookAlbum {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setObject:albumNAME forKey:#"name"];
[parameters setObject:#"Test message" forKey:#"message"];
FBRequest* request = [FBRequest requestWithGraphPath:#"me/albums" parameters:parameters HTTPMethod:#"POST"];
NSLog(#"creating facebook album");
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
[connection addRequest:request
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
albumId = [result objectForKey:#"id"];
NSLog(#"OK %#", albumId);
[self publishContentToAlbum:[result objectForKey:#"id"]];
}
else {
NSLog(#"Error: %#",error.userInfo);
}
}];
[connection start];
}
-(void)uploadBulkPhotosToAlbum:(NSMutableArray *)photoArray albumId:(NSMutableArray *)albumId{
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
NSString *graphPath = [NSString stringWithFormat:#"%#/photos",albumId];
NSMutableString *jsonFormat = [[NSMutableString alloc] init];
[jsonFormat setString:#"["];
for (int i = 0; i < (NSUInteger *)countere; i++)
{
if (i != 0)
{
[jsonFormat appendString:#","];
}
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSString *jsonRequest = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"attached_files\": \"%#\" }",graphPath,fileName];
[jsonFormat appendString:[NSString stringWithFormat:#" %#",jsonRequest]];
}
[jsonFormat appendString:#" ]"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonFormat,#"batch",nil];
for (int i = 0; i <(NSUInteger *)countere; i++)
{
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSData *data = UIImagePNGRepresentation([photoArray objectAtIndex:i]);
[params setObject:data forKey:fileName];
}
FBRequest *request1 = [FBRequest requestWithGraphPath:graphPath
parameters:params
HTTPMethod:#"POST"];
[connection addRequest:request1
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Photo uploaded successfuly! %#",result);
} else {
NSLog(#"Photo uploaded failed :( %#",error.userInfo);
}
}];
[connection start];
}
Can anyone help me to solve my problem?
Thanks for the reply.

iOS AFNetworking GET/POST Parameters

I want to do a POST request with AFNetworking which contains GET and POST parameters.
I am using this code:
NSString *urlString = [NSString stringWithFormat:#"upload_stuff.php?userGUID=%#&clientGUID=%#",
#"1234",
[[UIDevice currentDevice] identifierForVendor].UUIDString];
NSString *newUrl = #"https://sub.domain.com";
NSURL *baseURL = [NSURL URLWithString:newUrl];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
[httpClient defaultValueForHeader:#"Accept"];
NSDictionary *getParams = [NSDictionary dictionaryWithObjectsAndKeys:
#"1234", #"userGUID",
[[UIDevice currentDevice] identifierForVendor].UUIDString, #"clientGUID",
nil];
NSDictionary *postParams = [NSDictionary dictionaryWithObjectsAndKeys:
[#"xyz" dataUsingEncoding:NSUTF8StringEncoding], #"FILE",
nil];
[httpClient postPath:urlString parameters:postParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
}failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error retrieving data: %#", error);
}];
Now I have two questions:
How can I use BOTH GET and POST dictionaries in the same request? For the time, I am integrating the GET dictionary into the URL and using only the POST dictionary ([httpClient postPath:...])
I am getting an error from the server stating that the parameter "FILE" is missing. Unfortunately I can't examine any server logs (not my server). But using a standard NSURLConnection I was able to send requests with the FILE parameter to this server. So what is going wrong here?
Stackoverflow for you:
NSData* sendData = [self.fileName.text dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *sendDictionary = [NSDictionary dictionaryWithObject:sendData forKey:#"name"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:remoteUrl];
NSMutableURLRequest *afRequest = [httpClient multipartFormRequestWithMethod:#"POST"
path:#"/photos"
parameters:sendDictionary
constructingBodyWithBlock:^(id <AFMultipartFormData>formData)
{
[formData appendPartWithFileData:photoImageData
name:self.fileName.text
fileName:filePath
mimeType:#"image/jpeg"];
}
];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:afRequest];
[operation setUploadProgressBlock:^(NSInteger bytesWritten, NSInteger totalBytesWritten, NSInteger totalBytesExpectedToWrite) {
NSLog(#"Sent %d of %d bytes", totalBytesWritten, totalBytesExpectedToWrite);
}];
[operation setCompletionBlock:^{
NSLog(#"%#", operation.responseString); //Gives a very scary warning
}];
[operation start];
By #Igor Fedorchuk from POST jpeg upload with AFNetworking
AFNetworking has no method to setup both GET and POST params.
You have to setup GET params to your url, and use [AFHTTPClient requestWithMethod:path:parameters:] setup POST params.
- (NSURLRequest *)requestForPath:(NSString *)path method:(NSString *)method
{
NSMutableString *pathWithGetParams = [NSMutableString stringWithString:path];
BOOL hasPathContainsQueryChar = [path rangeOfString:#"?"].location != NSNotFound;
[pathWithGetParams appendString:hasPathContainsQueryChar ? #"&" : #"?"];
for (id key in self.getArguments.allKeys)
{
if ([key isKindOfClass:[NSString class]])
{
NSString *value = self.getArguments[key];
if ([value isKindOfClass:[NSString class]])
{
[pathWithGetParams appendString:[[self class] urlEncode:key]];
[pathWithGetParams appendString:#"="];
[pathWithGetParams appendString:[[self class] urlEncode:value]];
[pathWithGetParams appendString:#"&"];
}
}
}
NSString *upperCaseMethod = [method uppercaseString];
BOOL isMethodInGet = [upperCaseMethod isEqualToString:#"GET"];
NSURLRequest *request = [[self shareAFClient] requestWithMethod:method
path:pathWithGetParams
parameters:isMethodInGet ? nil : self.postArguments];
return request;
}
+ (NSString *)urlEncode:(NSString *)stringToEncode
{
return [self urlEncode:stringToEncode usingEncoding:NSUTF8StringEncoding];
}
+ (NSString *)urlEncode:(NSString *)stringToEncode usingEncoding:(NSStringEncoding)encoding
{
return (__bridge_transfer NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(__bridge CFStringRef)stringToEncode,
NULL,
(CFStringRef)#"!*'\"();:#&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
+ (NSString*)urlDecode:(NSString *)stringToDecode
{
return [self urlDecode:stringToDecode usingEncoding:NSUTF8StringEncoding];
}
+ (NSString*)urlDecode:(NSString *)stringToDecode usingEncoding:(NSStringEncoding)encoding
{
return (__bridge_transfer NSString *) CFURLCreateStringByReplacingPercentEscapesUsingEncoding(NULL,
(__bridge CFStringRef)stringToDecode,
(CFStringRef)#"",
CFStringConvertNSStringEncodingToEncoding(encoding));
}

Facebook Batch Photo Upload iOS

I am having some trouble trying to get the Facebook iOS SDK to batch upload photos. Currently I can upload them one by one, but I would like to batch the requests if possible. I have read this post over and over along with the fb batch docs. Here is what I have thus far.
Facebook *facebook = [(AppDelegate*)[[UIApplication sharedApplication] delegate] facebook];
NSData *imageData = UIImagePNGRepresentation([imgs objectAtIndex:0]);
NSString *jsonRequest1 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\", \"attached_files\": \"file1\" }"];
NSString *jsonRequest2 = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"me/photos\", \"attached_files\": \"file2\" }"];
NSString *jsonRequestsArray = [NSString stringWithFormat:#"[ %#, %# ]", jsonRequest1, jsonRequest2];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonRequestsArray,#"batch",imageData,#"file1",imageData,#"file2" nil];
I am mapping the imageData to the key it is looking for, but I get this response every time.
{
body = "{\"error\":{\"message\":\"File batch has not been attached\",\"type\":\"GraphBatchException\"}}";
code = 400;
headers = (
{
name = "WWW-Authenticate";
value = "OAuth \"Facebook Platform\" \"invalid_request\" \"File batch has not been attached\"";
},
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Cache-Control";
value = "no-store";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
},
{
body = "{\"error\":{\"message\":\"File file2 has not been attached\",\"type\":\"GraphBatchException\"}}";
code = 400;
headers = (
{
name = "WWW-Authenticate";
value = "OAuth \"Facebook Platform\" \"invalid_request\" \"File file2 has not been attached\"";
},
{
name = "HTTP/1.1";
value = "400 Bad Request";
},
{
name = "Cache-Control";
value = "no-store";
},
{
name = "Content-Type";
value = "text/javascript; charset=UTF-8";
}
);
}
)
Any help is very much appreciated.
Have you tried using the Social framework for iOS 6 to share photos? It allows you to add all the photos and share them.
- (IBAction)postToFacebook:(id)sender {
if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook]) {
SLComposeViewController *controller = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
[controller setInitialText:#"First post from my iPhone app"];
[controller addURL:[NSURL URLWithString:#"http://www.jinibot.com"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
//add as many images as you want
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[controller addImage:[UIImage imageNamed:#"socialsharing-facebook-image.jpg"]];
[self presentViewController:controller animated:YES completion:Nil];
}
}
Try with this.
Please notice that Facebook limit the number of requests which can be in a batch to 50.
-(void)uploadBulkPhotosToAlbum:(NSArray *)photoArray albumId:(NSString *)albumId
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
NSString *graphPath = [NSString stringWithFormat:#"%#/photos",albumId];
NSMutableString *jsonFormat = [[NSMutableString alloc] init];
[jsonFormat setString:#"["];
for (int i = 0; i < photoArray.count; i++)
{
if (i != 0)
{
[jsonFormat appendString:#","];
}
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSString *jsonRequest = [NSString stringWithFormat:#"{ \"method\": \"POST\", \"relative_url\": \"%#\", \"attached_files\": \"%#\" }",graphPath,fileName];
[jsonFormat appendString:[NSString stringWithFormat:#" %#",jsonRequest]];
}
[jsonFormat appendString:#" ]"];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:jsonFormat,#"batch",nil];
for (int i = 0; i < photoArray.count; i++)
{
NSString *fileName = [NSString stringWithFormat:#"file%d",i];
NSData *data = UIImagePNGRepresentation([photoArray objectAtIndex:i]);
[params setObject:data forKey:fileName];
}
FBRequest *request = [FBRequest requestWithGraphPath:#"me" parameters:params HTTPMethod:#"POST"];
[connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error)
{
[self resetViewAfterUpload:result];
}
else
{
[MBProgressHUD hideHUDForView:self.navigationController.view animated:YES];
NSLog(#"Photo uploaded failed :( %#",error.userInfo);
[[[UIAlertView alloc] initWithTitle:#"Error occurred!!" message:#"Some error occured while uploading." delegate:nil cancelButtonTitle:#"Dismiss" otherButtonTitles:nil] show];
}
}];
[connection start];
}
With the new Facebook SDK (3.0) try something like this:
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
FBRequest *request1 = [FBRequest requestForUploadPhoto:image1];
[connection addRequest:request1
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
//handle error/success
}
];
FBRequest *request2 = [FBRequest requestForUploadPhoto:image2];
[connection addRequest:request2
completionHandler:
^(FBRequestConnection *connection, id result, NSError *error) {
//handle error/success
}
];
[connection start];
How about using an NSOperationQueue to queue up all the upload requests?
Here is function I have used in one of our project by Facebook SDK 3.x
-(void)postOnFacebookWall : (id )response{
NSString *strPost = [NSString stringWithFormat:#"Group Name:%#",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_name"]];
NSString *strUrl = [NSString stringWithFormat:#"%#",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_picture_path"]];
NSURL *urlToShare = [NSURL URLWithString:strUrl];
UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:urlToShare]];
FBAppCall *appCall = [FBDialogs presentShareDialogWithLink:urlToShare
name:#"Heook"
caption:#"string"
description:#"The 'Has."
picture:urlToShare
clientState:nil
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if (error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
if (!appCall) {
// Next try to post using Facebook's iOS6 integration
BOOL displayedNativeDialog = [FBDialogs presentOSIntegratedShareDialogModallyFrom:self
initialText:strPost
image:image
url:nil
handler:nil];
if (!displayedNativeDialog) {
[self performPublishAction:^{
// NSString *message = [NSString stringWithFormat:#"Group Name:%#\nGroup Image:%#\n",[[response valueForKey:#"GroupDetail"] valueForKey:#"group_name"],[[response valueForKey:#"GroupDetail"] valueForKey:#"group_picture_path"]];
[FBRequestConnection startForPostStatusUpdate:strPost
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[self showAlert:#"Group shared on facebook" result:result error:error];
}];
}];
}
}
}

Resources