In LinkedIn sharing,LinkedIn provide a SDK but using this SDK,I can't share image link and text it always shows
LISDKErrorAPIDomain Code=403 The operation couldn’t be completed. (LISDKErrorAPIDomain error 403.)
Code:
NSString *url = #"https://api.linkedin.com/v1/people/~/shares";
NSString *payload = #"{\"comment\":\"Check out developer.linkedin.com! http://linkd.in/1FC2PyG\",\"visibility\":{ \"code\":\"anyone\" }}";
if ([LISDKSessionManager hasValidSession])
{
[[LISDKAPIHelper sharedInstance] postRequest:url stringBody:payload
success:^(LISDKAPIResponse *response) {
// do something with response
NSLog(#"response : %#",response.data);
}
error:^(LISDKAPIError *apiError) {
// do something with error
NSLog(#"error: %#",apiError);
}];
}
Sharing on LinkedIn Error : LISDKErrorAPIDomain Code=403 The operation couldn’t be completed.
if you are repeating same static text to post on LinkedIn, it might be a change to getting same error.
you must get share permission before add post
NSArray *permissions = [NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION,LISDK_W_SHARE_PERMISSION, nil];
full login code
NSArray *permissions = [NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION,LISDK_W_SHARE_PERMISSION, nil];
[LISDKSessionManager createSessionWithAuth:permissions state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState){
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"Session : %#", session.description);
[[LISDKAPIHelper sharedInstance] getRequest:#"https://api.linkedin.com/v1/people/~"
success:^(LISDKAPIResponse *response) {
NSData* data = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSString *authUsername = [NSString stringWithFormat: #"%# %#", [dictResponse valueForKey: #"firstName"], [dictResponse valueForKey: #"lastName"]];
NSLog(#"Authenticated user name : %#", authUsername);
} error:^(LISDKAPIError *apiError) {
NSLog(#"Error : %#", apiError);
}];
} errorBlock:^(NSError *error) {
NSLog(#"Error called : %#", error);
}];
Related
I want to include a "Sign Up using LinkedIn" feature in my app.
I'd like to be able to get some information, such as name and email.
By default I am able to get a name, but I'm stuck on getting the email.
My results are in JSON.
Here's my code:
- (IBAction)logInWithLinkedIn:(id)sender
{
if ([_client validToken])
{
[self requestMeWithToken:[_client accessToken]];
}
else
{
[_client getAuthorizationCode:^(NSString *code)
{
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:#"access_token"];
[self requestMeWithToken:accessToken];
} failure:^(NSError *error) {
NSLog(#"Quering accessToken failed %#", error);
}];
} cancel:^{
NSLog(#"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(#"Authorization failed %#", error);
}];
}
}
- (void)requestMeWithToken:(NSString *)accessToken
{
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(#"current user %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
}];
}
- (LIALinkedInHttpClient *)client
{
LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:#"redirectURL"
clientId:#"key"
clientSecret:#"secret"
state:#"state"
grantedAccess:#[#"r_emailaddress"]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil];
}
My result is:
firstName
headline
lastName
siteStandardProfileRequest
Anyone see how I can get the email?
You should use:
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result)
This may helps :)
You can use LinkedIn SDK
+ (void)loginToLinkedInAndFetchProfileData:(RequestResult)resultHandler
{
void (^PerformDataFetch)() = ^() {
if ([LISDKSessionManager hasValidSession]) {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,maiden-name,email-address)", LINKEDIN_API_URL];
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSString *token = [[LISDKSessionManager sharedInstance].session.accessToken serializedString];
[[NSUserDefaults standardUserDefaults] setValue:token forKey:LinkedInAccessTokenKey];
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
id value = [NSJSONSerialization JSONObjectWithData:objectData options:kNilOptions error:nil];
resultHandler(value, nil);
} error:^(LISDKAPIError *error) {
resultHandler(nil, error);
}];
}
};
NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:LinkedInAccessTokenKey];
if (token.length) {
LISDKAccessToken *accessToken = [LISDKAccessToken LISDKAccessTokenWithSerializedString:token];
if ([accessToken.expiration isLaterThan:[NSDate date]]) {
[LISDKSessionManager createSessionWithAccessToken:accessToken];
PerformDataFetch();
}
} else {
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) {
PerformDataFetch();
} errorBlock:^(NSError *error) {
resultHandler(nil, error);
}];
}
}
Response
> {
> emailAddress = "someEmail#email.com";
> firstName = Name;
> id = "2342d-6Y";
> lastName = LastName;
> }
Also this link can be useful
Update for Swift 3:
// Set preferred scope.
let scope = "r_basicprofile%20r_emailaddress"
// Then
if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?format=json"
-(void)syncLinkedInWithCompetionHandler:(CompletionBlock)block{
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil]
state:#"some state"
showGoToAppStoreDialog:YES
successBlock:^(NSString *returnState) {
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"value=%# \nisvalid=%#",[session value],[session isValid] ? #"YES" : #"NO");
block(returnState, nil);
}
errorBlock:^(NSError *error) {
NSLog(#"%s %#","error called! ", [error description]);
block(nil, error);
}
];
}
-(void)getProfileDataWithCompletion:(CompletionBlock)block {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,headline,location,email-address)", LINKEDIN_API_URL];
NSLog(#"urlString = %#",urlString);
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSError *jsonError;
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"responseDict = %#",responseDict);
block(responseDict, nil);
} error:^(LISDKAPIError *error) {
NSLog(#"error = %#",error);
block(error, nil);
}];
}
I need to provide an authorization with LinkedIn for my app.
I set up my app by this tutorial:
https://developer.linkedin.com/docs/ios-sdk
Then, Try to LogIn using this method:
- (void)login:(UIViewController *)controller{
NSArray *permissions = [NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, LISDK_W_SHARE_PERMISSION, nil];
[LISDKSessionManager createSessionWithAuth:permissions state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) {
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"Session LINKEDIN: %#", session.description);
NSString *url = [NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~"];
if ([LISDKSessionManager hasValidSession]) {
[[LISDKAPIHelper sharedInstance] getRequest:url
success:^(LISDKAPIResponse *response) {
NSData* data = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(#"Authenticated user name : %# %#", [dictResponse valueForKey: #"firstName"], [dictResponse valueForKey: #"lastName"]);
} error:^(LISDKAPIError *apiError) {
NSLog(#"Error : %#", apiError);
}];
}
} errorBlock:^(NSError *error) {
NSLog(#"%s","error called!");
}];
}
My app requires to open LinkedIn app, when I enter there my LI login and password, it asks me to confirm my permissions, but then nothing happens.
What should I do to perform a correct authorization through LinkedIn?
(maybe, there is a way to do this with WebView as FB or Twitter?)
Thanks.
Please use this link for linkedin login
//http://www.theappguruz.com/blog/integrate-linkedin-sdk-in-ios
Figured out how to receive token using OAuth. Just did all the stuff followed by this tutorial!
I want to include a "Sign Up using LinkedIn" feature in my app.
I'd like to be able to get some information, such as name and email.
By default I am able to get a name, but I'm stuck on getting the email.
My results are in JSON.
Here's my code:
- (IBAction)logInWithLinkedIn:(id)sender
{
if ([_client validToken])
{
[self requestMeWithToken:[_client accessToken]];
}
else
{
[_client getAuthorizationCode:^(NSString *code)
{
[self.client getAccessToken:code success:^(NSDictionary *accessTokenData) {
NSString *accessToken = [accessTokenData objectForKey:#"access_token"];
[self requestMeWithToken:accessToken];
} failure:^(NSError *error) {
NSLog(#"Quering accessToken failed %#", error);
}];
} cancel:^{
NSLog(#"Authorization was cancelled by user");
} failure:^(NSError *error) {
NSLog(#"Authorization failed %#", error);
}];
}
}
- (void)requestMeWithToken:(NSString *)accessToken
{
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result) {
NSLog(#"current user %#", result);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"failed to fetch current user %#", error);
}];
}
- (LIALinkedInHttpClient *)client
{
LIALinkedInApplication *application = [LIALinkedInApplication applicationWithRedirectURL:#"redirectURL"
clientId:#"key"
clientSecret:#"secret"
state:#"state"
grantedAccess:#[#"r_emailaddress"]];
return [LIALinkedInHttpClient clientForApplication:application presentingViewController:nil];
}
My result is:
firstName
headline
lastName
siteStandardProfileRequest
Anyone see how I can get the email?
You should use:
[self.client GET:[NSString stringWithFormat:#"https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?oauth2_access_token=%#&format=json", accessToken] parameters:nil success:^(AFHTTPRequestOperation *operation, NSDictionary *result)
This may helps :)
You can use LinkedIn SDK
+ (void)loginToLinkedInAndFetchProfileData:(RequestResult)resultHandler
{
void (^PerformDataFetch)() = ^() {
if ([LISDKSessionManager hasValidSession]) {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,maiden-name,email-address)", LINKEDIN_API_URL];
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSString *token = [[LISDKSessionManager sharedInstance].session.accessToken serializedString];
[[NSUserDefaults standardUserDefaults] setValue:token forKey:LinkedInAccessTokenKey];
[[NSUserDefaults standardUserDefaults] synchronize];
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
id value = [NSJSONSerialization JSONObjectWithData:objectData options:kNilOptions error:nil];
resultHandler(value, nil);
} error:^(LISDKAPIError *error) {
resultHandler(nil, error);
}];
}
};
NSString *token = [[NSUserDefaults standardUserDefaults] stringForKey:LinkedInAccessTokenKey];
if (token.length) {
LISDKAccessToken *accessToken = [LISDKAccessToken LISDKAccessTokenWithSerializedString:token];
if ([accessToken.expiration isLaterThan:[NSDate date]]) {
[LISDKSessionManager createSessionWithAccessToken:accessToken];
PerformDataFetch();
}
} else {
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil] state:nil showGoToAppStoreDialog:YES successBlock:^(NSString *returnState) {
PerformDataFetch();
} errorBlock:^(NSError *error) {
resultHandler(nil, error);
}];
}
}
Response
> {
> emailAddress = "someEmail#email.com";
> firstName = Name;
> id = "2342d-6Y";
> lastName = LastName;
> }
Also this link can be useful
Update for Swift 3:
// Set preferred scope.
let scope = "r_basicprofile%20r_emailaddress"
// Then
if let accessToken = UserDefaults.standard.object(forKey: "LIAccessToken") {
// Specify the URL string that we'll get the profile info from.
let targetURLString = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,maiden-name,email-address)?format=json"
-(void)syncLinkedInWithCompetionHandler:(CompletionBlock)block{
[LISDKSessionManager createSessionWithAuth:[NSArray arrayWithObjects:LISDK_BASIC_PROFILE_PERMISSION, LISDK_EMAILADDRESS_PERMISSION, nil]
state:#"some state"
showGoToAppStoreDialog:YES
successBlock:^(NSString *returnState) {
NSLog(#"%s","success called!");
LISDKSession *session = [[LISDKSessionManager sharedInstance] session];
NSLog(#"value=%# \nisvalid=%#",[session value],[session isValid] ? #"YES" : #"NO");
block(returnState, nil);
}
errorBlock:^(NSError *error) {
NSLog(#"%s %#","error called! ", [error description]);
block(nil, error);
}
];
}
-(void)getProfileDataWithCompletion:(CompletionBlock)block {
NSString *urlString = [NSString stringWithFormat:#"%#/people/~:(id,first-name,last-name,headline,location,email-address)", LINKEDIN_API_URL];
NSLog(#"urlString = %#",urlString);
[[LISDKAPIHelper sharedInstance] getRequest:urlString success:^(LISDKAPIResponse *response) {
NSError *jsonError;
NSData *objectData = [response.data dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
NSLog(#"responseDict = %#",responseDict);
block(responseDict, nil);
} error:^(LISDKAPIError *error) {
NSLog(#"error = %#",error);
block(error, nil);
}];
}
I wrote code as below where file exists in resources. Its not null.
I am successful in adding images, but stuck at videos.
-(void)uploadVideo {
NSLog(#"UPload Videio ");
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"abc" ofType:#"mp4"];
NSError *error = nil;
NSData *data = [NSData dataWithContentsOfFile:filePath options:NSDataReadingUncached error:&error];
if(data == nil && error!=nil) {
//Print error description
NSLog(#"error is %#", [error description]);
}
NSLog(#"data is %#", data);
NSDictionary *parameters = [NSDictionary dictionaryWithObject:data forKey:#"sample.mov"];
if (FBSession.activeSession.isOpen) {
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:parameters
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"OK: %#", result);
} else
NSLog(#"Error: %#", error.localizedDescription);
}];
} else {
// We don't have an active session in this app, so lets open a new
// facebook session with the appropriate permissions!
// Firstly, construct a permission array.
// you can find more "permissions strings" at http://developers.facebook.com/docs/authentication/permissions/
// In this example, we will just request a publish_stream which is required to publish status or photos.
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"publish_stream",
nil];
//[self controlStatusUsable:NO];
// OPEN Session!
[FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// if login fails for any reason, we alert
if (error) {
// show error to user.
} else if (FB_ISSESSIONOPENWITHSTATE(status)) {
// no error, so we proceed with requesting user details of current facebook session.
[FBRequestConnection startWithGraphPath:#"me/videos"
parameters:parameters
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
// [FBRequestConnection setVideoMode:NO];
if(!error) {
NSLog(#"Result: %#", result);
} else
NSLog(#"ERROR: %#", error.localizedDescription);
}];
//[self promptUserWithAccountNameForUploadPhoto];
}
// [self controlStatusUsable:YES];
}];
}
}
In return I am getting error as
The operation couldn’t be completed. (com.facebook.sdk error 5.)
How to upload video to facebook using facebook iOS SDK?
Thanks
Here's a method to upload video to Facebook. This code is testing and 100% working.
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]);
}
}];
Recommendation:
I think this might be a permissions issue but I am not sure where the error is being thrown. The delegate method that would be thrown is not shown in your code. I think reconciling your code with the steps in this sample might be helpful; if so please accept the answer.
Some key aspects of the sample:
Permissions:
- (IBAction)buttonClicked:(id)sender {
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
[permissions release];
}
Build Request:
- (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];
}
Request didLoad delegate method:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
NSLog(#"Result of API call: %#", result);
}
Request didFail delegate method:
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
NSLog(#"Failed with error: %#", [error localizedDescription]);
}
Facebook Video Permissions Link
This Code is Tested successfully On FaceBook SDK 3.14.1
Recommendation: In .plist
set FacebookAppID,FacebookDisplayName,
URL types->Item 0->URL Schemes set to facebookappId prefix with fb
-(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.
Did you ask for a publish_stream permission before?
I'm using Facebook SDK 3.6 within an iOS 6.3 app to upload a video to Facebook.
I've looked over many Stack Overflow posts about this but they are all years old and using much older Facebook SDKs.
Sometimes it works, other times it fails with the following message:
unexpected error:Error Domain=com.facebook.sdk Code=5 "The operation couldn’t be completed. (com.facebook.sdk error 5.)" UserInfo=0x1e2affc0 {com.facebook.sdk:HTTPStatusCode=500, com.facebook.sdk:ParsedJSONResponseKey={
body = {
"error_code" = 1;
"error_msg" = "An unknown error occurred";
};
code = 500;
}, com.facebook.sdk:ErrorSessionKey=, expirationDate: 4001-01-01 00:00:00 +0000, refreshDate: 2013-07-30 10:54:22 +0000, attemptedRefreshDate: 0001-12-30 00:00:00 +0000, permissions:(
"publish_stream"
)>}
Here is my code:
FBRequestConnection *_currentConnection;
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_stream"]
defaultAudience:FBSessionDefaultAudienceOnlyMe
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
NSError *attributesError;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:url.path error:&attributesError];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
long long fileSize = [fileSizeNumber longLongValue];
NSLog(#"file size: %lld", fileSize);
NSString *filename = [url lastPathComponent];
NSLog(#"filename: %#", filename);
NSString *mimeType = [self MIMETypeForFilename:filename
defaultMIMEType:#"video/mp4"];
NSLog(#"mime type: %#", mimeType);
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
videoData, filename,
mimeType, #"contentType",
self.song.name, #"title",
_videoDescription, #"description",
nil];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/videos"
parameters:params
HTTPMethod:#"POST"];
_currentConnection = [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
self.stageLabel.text = #"";
NSLog(#"result: %#, error: %#", result, error);
if(error) {
// Facebook SDK * error handling *
// if the operation is not user cancelled
if (error.fberrorCategory != FBErrorCategoryUserCancelled) {
[self showAlert:#"Video Post" result:result error:error];
}
self.uploadBarButtonItem.enabled = YES;
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Video Uploaded" message:#"Video has been uploaded"
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[self.delegate facebookUploaderUploadSucceeded:self];
}
// Delete the temp video
NSError *err;
[[NSFileManager defaultManager] removeItemAtURL:_sourceURL error:&err];
NSLog(#"Deleting video %#: %#", _sourceURL, [err localizedDescription]);
}];
}];
}
}];
This Code is Tested successfully On FaceBook SDK 3.14.1
-(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.