Get friends' work data from facebook SDK on iOS - ios

I am trying to fetch work info for FB friends on iOS using Facebook SDK. Here's the code that I am using:
if (FBSession.activeSession.isOpen) {
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"work", #"fields",
nil];
FBRequest *request = [FBRequest requestWithGraphPath:#"me/friends" parameters:params HTTPMethod:#"GET"];
[request startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary *result, NSError *error) {
if (!error) {
if (result) {
if (result.count) {
NSMutableArray *friendsWithJobTitles = [NSMutableArray array];
for (id aFriend in [result objectForKey:#"data"]) {
if ([aFriend objectForKey:#"work"]) {
[friendsWithJobTitles addObject:aFriend];
}
}
NSLog(#"result = %#", friendsWithJobTitles);
}
}
}
}];
}
The friendsWithJobTitles is always blank for some reason. Please help.

Related

How to use facebook pagination in ios

Hi I have recently started coding for iOS.I am trying to get videos from facebook using the following code.
-(void)facebookGetVideos:(UIViewController*)vc completionHandler:(void (^)(NSMutableArray*))completionBlock{
__block NSMutableArray * itemArray;
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/videos/uploaded"
parameters:#{#"fields":#"source,description,thumbnail,title"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if(error!=nil){
NSLog(#"Error after fb dwnld %#",error);
[MBProgressHUD hideHUDForView:vc.view animated:true];
[self showAlert:#"Error" message:error.localizedDescription viewController:vc];
}else{
NSLog(#"Results %#",result);
itemArray = [[NSMutableArray alloc]init];
// [itemArray addObject:[result valueForKey:#"data"]];
itemArray =[result valueForKey:#"data"];
completionBlock(itemArray);
}
}];
}
The response I am getting from there is as below:-
{
data = (
{
id = 1845903302379295;
source = "https://video.xx.fbcdn.net/v/t43.1792-2/27475816_220074475216744_8742438766032977920_n.mp4?efg=eyJybHIiOjE1MDAsInJsYSI6MTAyNCwidmVuY29kZV90YWciOiJzdmVfaGQifQ%3D%3D&rl=1500&vabr=382&oh=d4c3f6028a979c5919fdd8e444e24179&oe=5A89882A";
},
{
id = 1814936632142629;
source = "https://video.xx.fbcdn.net/v/t42.14539-2/23925286_2650490725061654_2502749796398268416_n.mp4?efg=eyJybHIiOjU3NiwicmxhIjo1MTIsInZlbmNvZGVfdGFnIjoic2QifQ%3D%3D&rl=576&vabr=320&oh=2fde1aea6eff33d8139ccb8fe7a33fd4&oe=5A8980C0";
}
);
paging = {
cursors = {
after = MTgxNDkzNjYzMjE0MjYyOQZDZD;
before = MTg0NTkwMzMwMjM3OTI5NQZDZD;
};
};
}
I am trying to use this after before as parameters as below:-
-(void)afterValues:(NSString*)afterVal{
NSDictionary * parameters =#{#"fields":#"source",#"after": afterVal};
FBSDKGraphRequest *request1 = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/videos/uploaded"
parameters:parameters
HTTPMethod:#"GET"];
[request1 startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
NSLog(#"after videos%#",result);
}];
}
And getting the following as response:-
after videos{
data = (
);
}
Can anyone please point out at my mistake.Any kind of help/suggestion or guidance in this directions would be highly appreciated.Thanks in advance!
Have you requested the manage_pages permission from the respective user through the login dialog? I think you see an empty result because of the missing permission.

not getting facebook friend list

i am getting null in friends list this is my code
-(void)getFriendList
{
FBRequest *friendsRequest=[FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler:^(FBRequestConnection *connection,NSDictionary* result,NSError *error)
{
arrFriendFB = [result objectForKey:#"data"];
arrFriendFB=[arrFriendFB valueForKey:#"first_name"];
NSLog(#"friemd=%#",arrFriendFB);
NSLog(#"friends description :%#",[arrFriendFB description]);
}];
}
As new facebook APi doc there is some modification. see some change's mention below
first you need to get access token with "user_friends" permission.
its graph API url:-
https://graph.facebook.com/me/friends?access_token=
For more information follow this link
https://developers.facebook.com/docs/facebook-login/permissions/v2.0
use this method to get friend list.
-(void)getFriendList
{
[FBSession setActiveSession:[self appDelegate].session];
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,location"];
[ friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSArray *data = [result objectForKey:#"data"];
//NSLog(#"response : %#",data);
for (FBGraphObject<FBGraphUser> *friend in data)
{
NSLog(#"name : %#",[friend name]);
}
}];
}

Request infomation from facebook account iOS

I am making an app login feature with Facebook account. I have the Facebook tokenkey by running this command: appDelegate.session.accessTokenData.accessToken. Then I take username and user_ID like this:
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (error == nil) {
// result is a dictionary with the user's Facebook data
NSDictionary *userData = (NSDictionary *)result;
NSString *facebookID = userData[#"id"];
NSLog(#"facebookID = %#",facebookID);
or
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
self.userNameLabel.text = user.name;
self.userProfileImage.profileID = user.id;
}
}];
}
the result is the same and when I debug It always jump up in if(!error).
Where does this error come from?

How to share video in facebook SDK?

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?

Retrieve the friends Email address From Facebook SDK in ios

I am tried to retrieve the Email Address from Facebook Friends.but,It cannot retrieved the email address.
I printed the email address.but,It displays the null.
I added email address in permissions array,FBRequest.
-(void)LoginButtonTapped
{
[FBSession.activeSession openWithCompletionHandler:^(FBSession *session,
FBSessionState state,
NSError *error)
{
if (FBSession.activeSession.isOpen)
{
NSLog(#"TOKEN : %#",[[FBSession activeSession]accessTokenData]);
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,email,location"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
NSArray *data = [result objectForKey:#"data"];
for (FBGraphObject<FBGraphUser> *friend in data)
{
[delegate.friendsListArray addObject:friend];
NSLog(#"%#:%#:%#:", [friend name],[friend birthday],[friend id]);
NSString *email=[friend objectForKey:#"email"];
NSLog(#"Email:%#",email);
}
}];
}
}];
}
- (void) performPublishAction:(void (^)(void)) action
{
NSArray *permissions = [[NSArray alloc] initWithObjects:#"user_birthday",#"user_location",#"friends_email",#"friends_hometown",#"friends_birthday",#"friends_location",#"publish_actions",#"user_photos",nil];
[[delegate facebook]authorize:permissions];
if ([FBSession.activeSession.permissions indexOfObject:permissions] == NSNotFound)
{
[FBSession.activeSession requestNewPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
}];
}
else
{
action();
}
[permissions release];
}
Any ideas please help me.
Shot in the dark but did you check your error value? Also what's the count of the # of records you get back?
Also could just try this instead, which seems to work (you might need to use objectForKey to get email out of the object):
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];

Resources