How to use facebook pagination in ios - 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.

Related

Get profile picture for other Facebook users in iOS

I'm trying to get the profile image for a Facebook user using the Graph API in the Facebook SDK for iOS but the example code from the website does not work for me.
https://developers.facebook.com/docs/graph-api/reference/user/picture/
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/123456789/picture"
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];
I get the following error in the console.
FBSDKLog: starting with Graph API v2.4, GET requests for //123456789/picture should contain an explicit "fields" parameter
From my understanding of the error message instead of parameters:nil I need to enter something like parameters:#{#"fields": #"id"} but whatever I try result in the completing handler is always nil. I don't know what to enter for the profile picture.
EDIT:
I'm looking to get the profile picture for other users.
Try This One:-
- (IBAction)btnFaceBook:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login setLoginBehavior:FBSDKLoginBehaviorBrowser];
[login logInWithReadPermissions:#[#"public_profile",#"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
[[FBSDKLoginManager new]logOut];
} else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
[self getDataFromFB];
}
}
}];
}
-(void)getDataFromFB
{
MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:true];
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"political,picture.width(500).height(500),id,email,first_name,last_name,gender,name" forKey:#"fields"]]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error && [result count] != 0)
{
[hud hideAnimated:true];
NSLog(#"%#", result);
}
else
{
[hud hideAnimated:true];
[self displayAlertMesage:#"Some error has been occure." title:#"Oops!"];
}
}];
}
}
You can use the following code for getting the data from the facebook login:-
-(void)getFacebookProfileInfos
{
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"me" parameters:#{#"fields": #"id,email,name,birthday,first_name,last_name,gender,picture.type(large)"}];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
dictUserData = [[NSDictionary alloc]init];
dictUserData=result;
}
}];
[connection start];
}
you will get all the data in the "dictUserData" dictionary and from that you will access the facebook profile in this way:-
UIImage * imgProfile = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", dictUserData[#"picture"][#"data"][#"url"]]]]];
NSString * strImageData = [self imageToNSString:imgProfile];

Get Facebook Friend List in iOS

I am trying to get Facebook friend list with name, id, etc in my app.
- (IBAction)onFBLogin:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"email", #"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"%#", result);
[self getFBEmailAddress];
}
}];
}
-(void)getFBEmailAddress{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email, friends"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *pictureURL = [NSString stringWithFormat:#"%#",[result objectForKey:#"picture"]];
mFBId = [NSString stringWithFormat:#"%#",[result objectForKey:#"id"]];
NSLog(#"My Profile : %#", result);
NSLog(#"email is %#", [result objectForKey:#"email"]);
[self getFBFriendList];
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
-(void)getFBFriendList{
NSString* graphPat = [[NSString alloc] initWithFormat:#"%#/friends", mFBId];
FBSDKGraphRequest *requestFriends = [[FBSDKGraphRequest alloc]
initWithGraphPath:graphPat
parameters:#{#"fields": #"id, name"}
HTTPMethod:#"GET"];
[requestFriends startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error && result)
{
NSArray *allFriendsResultData = [result objectForKey:#"data"];
if ([allFriendsResultData count] > 0)
{
for (NSDictionary *friendObject in allFriendsResultData)
{
NSString *friendName = [friendObject objectForKey:#"name"];
NSString *friendID = [friendObject objectForKey:#"id"];
NSLog(#"%# : %#", friendID, friendName);
}
}
}
}];}
I've succeed to login via Facebook and get my profile. After that, I've tried to get friend list via the friends graph api. But at that time, it only said count of friends following as below.
friends = {
data = (
);
summary = {
"total_count" = 2;
};
};
id = 60XXXXXX1295X;
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/hprofile-xfa1/v/t1.0-1/p50x50/1..._501957533...";
};
};
How Can I get full information of friends list such as id, name, etc? Please help me if any one already implemented. Thank you.
This work for me.
NSMutableArray *completeList = [[NSMutableArray alloc] init];
[self fetchFacebookEachFriend:completeList withGrapPath:#"/me/friends" withCallback:^(BOOL success, NSMutableArray * fbList) {
//Finish get All Friends
fbListFinal(success, fbList);
}];
- (void)fetchFacebookEachFriend:(NSMutableArray *)completeList withGrapPath:(NSString *)graphPath withCallback:(returnFbList)fbList
{
NSDictionary *limitDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_name, last_name, middle_name, name, email", #"fields", nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:graphPath parameters:limitDictionary HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Alert!" message:#"Please connect to Facebook to find your friends" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
fbList(NO, completeList);
return;
}
//Add each friend to list
for (NSDictionary *friend in [result valueForKey:#"data"]) {
[completeList addObject:friend];
}
if ([result valueForKey:#"paging"] != nil && [[result valueForKey:#"paging"] valueForKey:#"next"] != nil) {
NSString *nextPage = [[result valueForKey:#"paging"] valueForKey:#"next"];
nextPage = [[nextPage componentsSeparatedByString:#"?"] objectAtIndex:1];
[self fetchFacebookEachFriend:completeList withGrapPath:[NSString stringWithFormat:#"me/friends?%#",nextPage] withCallback:fbList];
} else
fbList(YES, completeList);
}];
}
result.paging.next contains the complete URL, with access token and all. I find the simplest thing is just to pass it on to an NSURLSession data task:
NSString *nextPage = result[#"paging"][#"next"];
if (!nextPage) return;
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:nextPage] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [self decodeJSONResult:data response:response error:error];
// use json
}] resume];
I wrote this as an FBSDKGraphRequest extension: FBSDKGraphRequest+Paging.h

How to use the result of FBSDKGraphRequest Outside the Block

I am designing an application which uses Facebook to display the feeds in a table view ..so in order to get the result of the feeds i have called a method FBSDKGraphRequest but I do not know how to retrieve the values of the results from FBSDKGraphRequest outside since they are located in a completion block.I want to display the name and message in the table view....
The code illustration is below:-
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]initWithGraphPath:Path parameters:#{ #"fields": #"feed{from,message,created_time}",} tokenString:accessToken version:FBSDK_TARGET_PLATFORM_VERSION HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"No Data");
else {
FeedCount = [NSDictionary dictionaryWithDictionary:result];
NSDictionary*feed = [FeedCount objectForKey:#"feed"];
NSArray*array1 = [feed objectForKey:#"data"];
NSArray*array3 = [array1 valueForKey:#"from"];
NSLog(#"Data:%#",array3); ---------------> **Displaying Data**
}
}];
NSLog(#"FeedCount:%#",FeedCount);----------------->**Showing Null**
Any help will be Appreciated
To get the result of dictionary from fbsdk please declare variable as __block NSDictionary *json;
Then assign this inside block like,
json =[FeedCount objectForKey:#"feed"];
Did you try this like,
__block NSDictionary *json;
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]initWithGraphPath:Path parameters:#{ #"fields": #"feed{from,message,created_time}",} tokenString:accessToken version:FBSDK_TARGET_PLATFORM_VERSION HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(error)
NSLog(#"No Data");
else {
FeedCount = [NSDictionary dictionaryWithDictionary:result];
json = [FeedCount objectForKey:#"feed"];
NSArray*array1 = [feed objectForKey:#"data"];
NSArray*array3 = [array1 valueForKey:#"from"];
NSLog(#"Data:%#",array3); ---------------> **Displaying Data**
}
}];
NSLog(#"json:%#",json);

Facebook iOS SDK v4.0, get friends list

Seems like Facebook iOS SDK v4.0 has a lot of changes. I try to get a user's friends list after he login.
I think it's something to do with FBSDKGraphRequestConnection but I'm not sure how it can be used.
Also, if I only want to get friends who are using my app, does facebook sdk support that?
Can anyone give some examples? Thanks!
FBSDKGraphRequest *friendsRequest =
[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/friends"
parameters:parameters];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:friendsRequest
completionHandler:^(FBSDKGraphRequestConnection *innerConnection, NSDictionary *result, NSError *error) {
...
}];
// start the actual request
[connection start];
This shows how to handle the response:
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/friends" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
NSArray * friendList = [result objectForKey:#"data"];
for (NSDictionary * friend in friendList)
{
NSLog(#"Friend id: %#", friend[#"id"]);
NSLog(#"Friend name: %#", friend[#"name"]);
}
}
}];
I used below code to get friend list
self.graphrequest = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/taggable_friends?limit=100"
parameters:#{ #"fields":#"id,name,picture.width(100).height(100)"}];
[self.graphrequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
self.resultsArray = result[#"data"];
[self.fbTableView reloadData];
[self.fbTableView setHidden:NO];
} else {
NSLog(#"Picker loading error:%#",error.userInfo[FBSDKErrorLocalizedDescriptionKey]);
}
}];
You can limit the number of friends using limit keyword.Ex: limit=100

Facebook FBOpenGraphAction user message not working

I'm uploading a photo as an open graph object, then tying it into my open graph action once it returns the URL.
Everything is working great so far, but I'm not able to get the custom user message "TEST TEST TEST TEST!" to show up. I've been hitting this issue from all angles and can't seem to get it nailed down. Any ideas?
- (void)postPhotoThenOpenGraphAction {
FBRequestConnection *connection = [[FBRequestConnection alloc] init];
// First request uploads the photo.
FBRequest *request1 = [FBRequest requestForUploadPhoto:[UIImage imageWithData:[NSData dataWithContentsOfFile:picture.pathSmall]]];
[connection addRequest:request1 completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
} else {
[self showFacebookFailedError];
}
}
batchEntryName:#"photopost"];
// Second request retrieves photo information for just-created
// photo so we can grab its source.
FBRequest *request2 = [FBRequest requestForGraphPath:#"{result=photopost:$.id}"];
[connection addRequest:request2 completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error && result) {
NSString *source = [result objectForKey:#"source"];
[self postOpenGraphActionWithPhotoURL:source];
} else {
[self showFacebookFailedError];
}
}
];
[connection start];
}
- (void)postOpenGraphActionWithPhotoURL:(NSString*)photoURL {
id<PTOGPicture> photoGraphObject = [self pictureObjectForPicture:self.picture];
id<PTOGSharePicture> action = (id<PTOGSharePicture>)[FBGraphObject graphObject];
action.photo = photoGraphObject;
if (self.selectedPlace) {
action.place = self.selectedPlace;
}
if (self.selectedFriends.count > 0) {
action.tags = self.selectedFriends;
}
action.message = #"TEST TEST TEST TEST!";
if (photoURL) {
NSMutableDictionary *image = [[NSMutableDictionary alloc] init];
[image setObject:photoURL forKey:#"url"];
NSMutableArray *images = [[NSMutableArray alloc] init];
[images addObject:image];
action.image = images;
}
// Create the request and post the action to the.
[FBRequestConnection startForPostWithGraphPath:#"me/myappapp:share"
graphObject:action
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
//... code taken out for brevity
}];
}
I have a simpler version that works for what you want:
First you create your action object as you wish:
- (void)shareOnFacebook {
NSMutableDictionary<FBGraphObject> *action = [FBGraphObject graphObject];
action[#"<OPEN_GRAPH_OBJ>"] = obj;
action[#"image[0][url]"] = url;
action[#"image[0][user_generated]"] = #"true";
action[#"message"] = #"some message here";
[FBRequestConnection startForPostWithGraphPath:#"me/<app_namespace>:<action>" graphObject:action completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
}];
}
However, the requirement for this to work, is that you must have these two permissions set on the action setup page:
I hope it helps.

Resources