iOS facebook check if friends have app installed [duplicate] - iphone

This question already has answers here:
Facebook Graph API - Friends using application
(2 answers)
Closed 5 years ago.
Is there already a way with the facebook ios API to get a list of friends who have your app installed? I basically require something similar to "Words with Friends" where they can determine which of your FB friends are playing the game. I have one solution which requires some extra database use but was hoping maybe the FB api had something built in for this kind of query.

Create a FBFriendPickerDelegate delegate class and override this function:
-(BOOL)friendPickerViewController:(FBFriendPickerViewController *)friendPicker shouldIncludeUser:(id<FBGraphUser>)user{
BOOL installed = [user objectForKey:#"installed"] != nil;
return installed;
}
For users that do not have your app installed, installed field will be nil, but you have to request it when you load data:
self.friendsController = [[FBFriendPickerViewController alloc] initWithNibName:nil bundle:nil];
//...
NSSet *fields = [NSSet setWithObjects:#"installed", nil];
self.friendPickerController.fieldsForRequest = fields;
//...
[self.friendsController loadData];

I think fql is a little complex for me,so I use this function in FBRequest to call the Graph API to solve this problem in Facebook SDK 3.5
+ (FBRequest *)requestWithGraphPath:(NSString*)graphPath parameters:(NSDictionary*)parameters HTTPMethod:(NSString*)HTTPMethod;
And the code is:
FBRequest *request = [FBRequest requestWithGraphPath:#"me/friends"
parameters:#{#"fields":#"name,installed,first_name"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBRequestConnection *connection,
id result,
NSError *error){
}];
You can put all your interesting fields in the parameters dictionary.
And according to the SDK Reference,object containing type (this is always "user"), id (the ID of the user), and optional installed field (always true if returned); The installed field is only returned if the user has installed the application, otherwise it is not part of the returned object

I've used this code in the past to get app using friends from a user.
facebook is the Facebook class that comes with FB Connect.
NSString *fql = [NSString stringWithFormat:#"SELECT name,uid, pic_small FROM user WHERE is_app_user = 1 AND uid IN (SELECT uid2 FROM friend WHERE uid1 = %#) order by concat(first_name,last_name) asc",userId,userId]];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:fql ,#"query", [facebook accessToken], #"access_token", nil];
[facebook requestWithMethodName:#"fql.query" andParams:params andHttpMethod:#"GET" andDelegate:self];

The easiest solution is using the
- (BOOL)friendPickerViewController: shouldIncludeUser:
method implemented by the FBFriendPickerDelegate protocol in the latest 3.5.1 Facebook SDK (June 2013), asking the delegate whether to include a friend in the list, based on the "installed" field when fetching me/friends.
The installed field is present (true) if the friend is also a user of the calling application.
You can use like this:
- (BOOL)friendPickerViewController:(FBFriendPickerViewController *)friendPicker
shouldIncludeUser:(id <FBGraphUser>)user {
return [[user objectForKey:#"installed"] boolValue];
}
IMPORTANT!
You have to include the followings to include the field in the request and to inform friendPicker about its delegate:
self.fieldsForRequest = [NSSet setWithObject:#"installed"];
self.delegate = self;
You can verify with the Graph Api Explorer that only friends with the apps installed display by using the Graph API Explorer and entering the query
me/friends?fields=installed
and you can get back a list of your friends like this, where one of the user has installed your application (true):
...
{
"id": "100002656xxxxxx"
},
{
"installed": true,
"id": "100004366xxxxxx"
},
...

Related

Facebook me/invitable_friends, return link on small picture

Picture url for not app friend: https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/c0.3.631.631/s50x50/1796710_1380751512198760_2043305802_n.jpg?oh=7e5cde9326c5bedd0416bf091b198b75&oe=55247955&__gda__=1433029165_feddf79888157b002c65970ea505c266
Picture size will be 50x50,
Can I somehow get bigger image than the one API returns in picture.data.url ?
Or can I get a normal id for not app friends?
(me/invitable_friends return id such sAVkqWm2Ns53i0og7xtBcGzDkBxJ7sKTO7sUaC_e1A3uDxeTZLyV08E6slPz4H64VeqQA5SpxBtA7un8CQXgZXqHpi_1fEwTKlWd7RVZWrtoILA)
for using http://graph.facebook.com/"ID"/picture?type=large
me/invitable_friends?fields=picture.width(320).height(320)
on iPhone you can do it like this
[FBRequestConnection startWithGraphPath:#"/me/taggable_friends"
parameters:#{#"fields" : #"name,picture.width(500).height(500)"}
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
/* handle the result */
/* returns a list of friends with links to bigger pictures */
}];
the key there is parameters

FBWebDialog without friend list

In my app I want to use FBWebDialog to send "app request" to the multiple users. But I dont want to select those users from the list which comes with the FBWebDialog. I just want to pass the friends from the FBfriendpicker viewcontroller to the FBWebDialog and send them from there. is it possible? How can I do that? Thanks.
You need to set the "to" parameter as documented in two pages referenced below, it will disable the drop down friend list and send to only one targeted audience
https://developers.facebook.com/docs/howtos/send-requests-using-ios-sdk/
Sending targeted requests
You can filter the suggested list down or target one user. To filter
down the list you can pass in a parameter, suggestions that contains a
comma-separated list of friends to show in the selection. To target
one recipient, pass that user's ID in a to parameter
And also documented on request dialog page
to A user ID or username, or a comma-separated list of them. These may
or may not be a friend of the sender. If this is specified by the app,
the sender will not have a choice of recipients. If not, the sender
will see a multi-friend selector and will be able to select a maximum
of 50 recipients. (Due to URL length restrictions, the maximum number
of recipients is 25 in IE7/IE8 when using a non-iframe dialog.)
Another documentation in games section of facebook with picture
https://developers.facebook.com/docs/tutorials/ios-sdk-games/requests/
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
// 2. Optionally provide a 'to' param to direct the request at
#"286400088", #"to", // Ali
nil];
Upgrad from 3.2 to 3.5.1 in part to allow me to use frictionless friend requests. The process works fine with:
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:nil];
FBFrictionlessRecipientCache *friendCache = [[FBFrictionlessRecipientCache alloc] init];
[friendCache prefetchAndCacheForSession:nil];
[FBWebDialogs presentRequestsDialogModallyWithSession:[FBSession activeSession]
message:[NSString stringWithFormat:#"I just posted an action - give me some points!"]
title:#"Get Points from your friends"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Case A: Error launching the dialog or sending request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// Case B: User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
NSLog(#"Request Sent.");
}
}}
friendCache:friendCache];
This helps you to upgrade your Facebook sdk https://developers.facebook.com/docs/tutorial/iossdk/upgrading-from-3.2-to-3.5/

FBGraph and FQL use to get the friends contact number and emailID in iphone

I am using Facebook API to get the contact number and email id of friends, I worked on fbgraph and fql and uses all queries from https://developers.facebook.com/docs/reference/fql/, but in forum page of facebook I found there is no way to get the contact number and email ID.
I also used the extended permission of the Facebook API but I didn't find anything.
If anyone know about it then please give the answer ...
answer will be appreciated...
Thanks in advance!!!!!
If you use this code with the users access token
var url = "https://graph.facebook.com/me/?access_token=" + token;
var req = new XMLHttpRequest();
req.open("get", url, true);
req.send(null);
req.onerror = function () { alert("Error"); };
Then you will find the req.responseText has all the user information you are after. You can also get the user access token once they login.
Make sure you have the "email" permission when the user authenticates
NSArray *permissions = [NSArray alloc] initWithObjects:#"permissions",nil];
[facebook authorize:permissions];
[permissions release];
Then, when the user has logged in, get the "me" from the graph:
[facebook requestFromGraph:#"me/" withDelegate:self];
You get the information from the "requestDidLoad" callback method:
if([result objectForKey:#"first_name"]){
// do stuff w/ user info
}
The id is:
[request objectForKey:#"id"];

How to get friend's birthday list using facebook api?

I am trying to get friend birthday list.
But how to find using my api I dont know.
Note: This is no longer possible. See this answer.
Use the OpenGraph API in whatever environment you use to retrieve the information. The birthday is in the user information object, see docs: http://developers.facebook.com/docs/reference/api/user
You can also use facebook api :
$friends_birthday = $facebook->api("/me/friends?fields=id,name,birthday");
you must also have permission friends_birthday in the scope of your app
Since v2.0 of the Graph API, it´s not possible to get friend birthdays anymore. You can only get the birthday of the authorized user by using the user_birthday permission. See the changelog for more information: https://developers.facebook.com/docs/apps/changelog
There is only one other possibility: If the friend authorized the App with user_birthday, you can get his birthday with the following call: /friend-id?fields=birthday
Of course you need to authorize users with user_friends too, in order to make this work. And you can also just store the birthday of all authorized users and don´t waste an extra API call on it.
Firstly, read the readme on the project page to get started with the SDK.
You'll then need to look at the API reference and more specifically the user profile section.
After you've done all that you'll end up with a JSON object you can parse using the org.json package in the Android SDK.
Hopefully that helps you out.
You have to use FQL to get a list of friend's birthday.
FQL would be (just replace your access token):
"https://api.facebook.com/method/fql.query?query=select name, birthday_date from user where uid in (select uid2 from friend where uid1=me())&access_token=your_access_token"
This is the link for Graph API Explorer
https://developers.facebook.com/tools/explorer/?method=GET&path=me go the link and click on Get Access Tocken you can have a pop-up for select permissions
and select your access token.
and at the node section select the fields you want ( example select friends and as a sublink in friends select birthday) and GET a query by clicking on SUBMIT then you can have a friend's birthday and id along with yours as a Json Data.
get the full friend list with Graph api , iterate json data array and then check for birthday=today .. that is
you can get friend list in ios this way:
- (IBAction)pickFriendsClick:(UIButton *)sender {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_birthday",#"friends_hometown",
#"friends_birthday",#"friends_location",
nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:nil];
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,location,updated_time,email"];
[ friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSArray *data = [result objectForKey:#"data"];
NSMutableArray *friends= [data mutableCopy];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"updated_time"
ascending:TRUE];
[friends sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
for (FBGraphObject<FBGraphUser> *friend in friends) {
NSLog(#"%#:%#", [friend name],[friend birthday]);
}}];
}
Thanks.
try this , it require only few lines
FBRequest * request = [FBRequest requestForGraphPath:#"me/friends?
fields=id,name,birthday&limit=5000"];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
if(error == nil){
NSLog(#"%#",result);
}
}];
FB.api('me/friends?fields=id,name,birthday') doesnt work as of 09/12/2017.
Below is the debug message from graph explorer tool when i try to hit the endpoint.
Only friends who installed this app are returned in API v2.0 and higher. total_count in summary represents the total number of friends, including those who haven't installed the app
For returning just the friends list of the user, you can try hitting the below endpoint with a valid access token
FB.api('me/friendlists')
But note that you need read_custom_friendlists permission from the user.
Here is the example URL from Facebook Graph API Explorer:
me?fields=email,birthday,friends{birthday}
Android Java Code:
GraphRequest request = GraphRequest.newMeRequest(
accessToken,
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Insert your code here
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "email,birthday,friends{birthday}");
request.setParameters(parameters);
request.executeAsync();
iOS SDK:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me"
parameters:#{ #"fields": #"email,birthday,friends{birthday}",}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];
Javascript SDK:
FB.api(
'/me',
'GET',
{"fields":"email,birthday,friends{birthday}"},
function(response) {
// Insert your code here
}
);
cURL:
curl -i -X GET \
"https://graph.facebook.com/v15.0/me?fields=email%2Cbirthday%2Cfriends%7Bbirthday%7D&access_token=YOUR_ACCESS_TOKEN"
You can add more parameters inside the curly braces if you need more details. i.e {birthday, email, first_name, gender, location} and so on.

How to detect the active iTunes store on the iPhone/iPod Touch/iPad?

I'd like to be able to determine which store the user connects to from inside my app, so that I can direct them to some appropriate content for their device AND store. Does anyone know how to get this information?
Basically, if the user is in the UK, and connects to the UK store, I want my function/method to return GB, if in Korea, I want KR, Australia = AU etc. Any help would be appreciated.
The approach of getting the country code of the user's locale will work ... but only if the user's iTunes store is the same as their locale. This won't always be the case.
If you create an in-app purchase item, you can use Apple's StoreKit APIs to find out the user's actual iTunes country even if it's different from their device locale. Here's some code that worked for me:
- (void) requestProductData
{
SKProductsRequest *request= [[SKProductsRequest alloc] initWithProductIdentifiers:
[NSSet setWithObject: PRODUCT_ID]];
request.delegate = self;
[request start];
}
- (void) productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
NSArray *myProducts = response.products;
for (SKProduct* product in myProducts) {
NSLocale* storeLocale = product.priceLocale;
storeCountry = (NSString*)CFLocaleGetValue((CFLocaleRef)storeLocale, kCFLocaleCountryCode);
NSLog(#"Store Country = %#", storeCountry);
}
[request release];
// If product request didn't work, fallback to user's device locale
if (storeCountry == nil) {
CFLocaleRef userLocaleRef = CFLocaleCopyCurrent();
storeCountry = (NSString*)CFLocaleGetValue(userLocaleRef, kCFLocaleCountryCode);
}
// Now we're ready to start creating URLs for the itunes store
[super start];
}
Since iOS 13.0, Apple introduced the SKStorefront API.
It allows you to check the current AppStore country the user is connected to.
SKStorefront: An object containing the location and unique identifier of an Apple App Store storefront.
Overview
In-app products you create through App Store Connect are available for sale in every region with an App Store. You can use the storefront information to determine the customer's region, and offer in-app products suitable for that region. You must maintain your own list of product identifiers and the storefronts in which you want to make them available.
Topics
countryCode: The three-letter code representing the country associated with the App Store storefront.
identifier: A value defined by Apple that uniquely identifies an App Store storefront.
https://developer.apple.com/documentation/storekit/skstorefront
So far you can use 2 methods with their pros and cons:
StoreFront
->SDK >= 13
->The three-letter code representing the country associated with the App Store storefront
if let storeFront = SKPaymentQueue.default().storefront{
print("StoreFront CountryCode = ", storeFront.countryCode)
}
else {
print("StoreFront NOT Available")
}
OR
SKCloudServiceController
-> Available from iOS 9.3.
-> Requires permission. On tvOS it can become messy as I can't find a way to change the permissions in settings...
-> Permission text quite confusing.
let skCloudServiceController = SKCloudServiceController()
SKCloudServiceController.requestAuthorization { (status) in
guard status == .authorized else {
return
}
skCloudServiceController.requestStorefrontCountryCode(completionHandler: { (countryCode, error) in
if let error = error {
print("Failure: ", error)
}
else if let countryCode = countryCode {
print("Country code: ", countryCode)
}
})
}
Don't forget to include that in your .plist file:
<key>NSAppleMusicUsageDescription</key>
<string>Store information</string>
A hard way to get this function is to set up up a single app for every app store country. Each app holds it's own country store information. This assumes, that a user sticks to one store, which should be true for most people.
I suggest you try iTunes deep links. For example, http://itunes.com/apps/appname should take the user to the local App Store where she spends money.
I need the same functionality. At the moment I'm considering reading using data from NSLocale as default, but adding a setting in settings.app for user to customise this if it does not match.
This function is taken from an answer to another question of mine.
- (NSString *)getUserCountry
{
NSLocale *locale = [NSLocale currentLocale];
return [locale objectForKey: NSLocaleCountryCode];
}
You should probably use
[[userDefaults dictionaryRepresentation] objectForKey:#"NSLocaleCode"];
This will return a language code like en_US or en_UK or en_AU or even zh_CN, zh_MY, jp_JP and so on.
Parse the correct codes which you support and direct them accordingly.