Locale-independent FBSDKGraphRequest - ios

I am interested in fetching user's gender from Facebook. The device locale is set to Russian. Code:
let FBRequest = FBSDKGraphRequest(
graphPath: "me",
parameters: [
"fields": "id, gender",
"locale": "en_US"
]
)
FBRequest.startWithCompletionHandler(
{
(connection, result, error) -> () in
if error == nil {
print(result["gender"])
}
}
)
It prints "мужской" instead of "male". How can I get response ignoring the device locale? Thank you in advance!

I've had the same problem as you. I'm trying to change the locale putting a key and value as "locale":"pt_BR" or "locale":"en_US". Both fail.
The only way I found out to resolve is by changing the line below in the file "FBSDKGraphRequestConnection.m" (I installed last version SDK trough cocoapods) in the method called: - (NSString *)urlStringForSingleRequest:(FBSDKGraphRequest *)request forBatch:(BOOL)forBatch
request.parameters[#"locale"] = [NSLocale currentLocale].localeIdentifier;
to for example:
request.parameters[#"locale"] = #"en_US";
The SDK gets the current NSLocale of the device and overrides the parameter you put on it.

Related

Get insights/page_fans for a Facebook page from Facebook's open graph

I'm trying to get the number of fans that a music artist has on their Facebook page, but it's not working. I've combed through the FBAPI docs as well as SO and still nothing. Here's my code:
func getHolychildInfo() {
//Make request
let newGraphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/holychildmusic/insights/page_fans", parameters: ["period" : "lifetime", "show_description_from_api_doc" : "true", "fields": "read_insights"], httpMethod: "GET")
newGraphRequest.start(completionHandler: { (connection, result, error) in
if ((error) != nil) {
print("Holychild error getting insights: \(error.debugDescription)")
} else {
print("\nHolychild insights result:\n\n\(result)")
}
})
}
Here's my result:
data = (
);
paging = {
next = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1487457711&until=1487716911";
previous = "https://graph.facebook.com/v2.8/holychildmusic/insights/page_fans?access_token=EAAIB5k3aWEEBAHBD9lZC5AAzZAVV8K8CGBfqaxcrLdZA7oZB2Gdar8cQphXj4VciloZAnZBKp5ZA59BmGloSNz847nFqZCTVsYZCl9rrOk88OnfCnDwwADKnkOO5EUhGumEbW96riHplgfBLdnZAEYmB2Qz4ZAH1sWbuftmGKDqPft4l5QAHSZAimIyI6sOHaKWiurRK201Af6NQCXGliZBsZAUYosUHttkUbo4CQZD&fields=read_insights&format=json&include_headers=false&period=lifetime&sdk=ios&show_description_from_api_doc=true&since=1486939311&until=1487198511";
};
As you can see, there is nothing in the "data" part of the response. The "page_fans" insights metric is supposed to return a number - among other things - but instead returns nothing.
All insights metrics besides the two public ones (page_fans_country and page_storytellers_by_country) require admin access to the page (admin user or page access token with read_insights permission.)
But the fan_count field of the page object is public, so just request that:
https://developers.facebook.com/tools/explorer/?method=GET&path=holychildmusic%3Ffields%3Dfan_count&version=v2.8

Facebook Login doesn't fetching all User's profile information in swift

In my app I implemented FacebookLogin accessing permissions:
let facebookReadPermissions = ["public_profile", "email", "user_friends"]
Once all permissions granted, I am calling graph API for fetching user's profile info using:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
It is returning just two values: { id = 86160953055XXXX; name = "Devendranath Reddy"; }
I want Address, email, phone, first and last names also.
What is wrong here.
I even enabled for live access in developer.apple.com -> MyApp -> Settings
Please help me out.
Thanks in advance.
try this out, you need to set the parameters value:
so for Swift it would be this:
parameters:#{#"fields": #"id, name"}
In swift it would be something similar
something like this:
let params = ["fields": "email, friends"]
so:
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
Add whatever fields you want to add, like "first_name" "last_name" etc, etc.
let params = ["fields": "email, first_name, gender, last_name, location"]
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
graphRequest.startWithCompletionHandler(
{
(connection, result, error) -> Void in
if ((error) != nil)
{
// Failure code goes here.
}
else
{
// Success code goes here
println("User Name is: \(userName)")
println("User Email is: \(userMail)")
println("Gender is: \(gender)")
}
})
This request won't grab all the information until your app is reviewed by Facebook's app review. It will only give you access to the public profile info, regardless of what permissions the user accepts.

Force locale for reverseGeocodeLocation in iOS

I'm looking for a solution similar to these two questions
how to localize address result from reverseGeocodeLocation?
Reverse geocoding to return results only in English?
But I want to be able to get a non-localized version of address and locality.
In my add, when doing reverse geocoding on a non-latin localized device geocoding service returns CLPlacemark which already contains a localized version of address. For instance in Geneva, when using iPhone in Russian, I'm getting
"Площадь Пленпале" instead of "Place de Plainpalais"
which is probably cool but nonetheless confusing since street names aren't in cyrillic. Also, I'm unable to submit a localized version of the address to another API to find an itinerary. So is there a way to force a locale in reverseGeocodeLocation or briefly trick the OS into thinking locale language is set to something other?
Also, doing something like this just before the request doesn't seem to work, since it requires app restart
NSUserDefaults.standardUserDefaults().setObject("fr", forKey: "AppleLanguages"
NSUserDefaults.standardUserDefaults().synchronize()
It turns out modifying UserDefaults was not possible (at least I found no viable solution to do that), so I had to use external reverse geocoder to what I wanted (force locale). Here's one using Google API and Alamofire and SwiftyJSON, wrapped in with a nice completionHandler to get the address when geocoding is done
func getReversePositionFromGoogle(latitude:Double, longitude:Double, completionHandler: (JSON?, NSError?) -> ()) {
var parameters = ["latlng":"\(latitude), \(longitude)", "sensor": true, "language": "fr"]
Alamofire.request(.GET, "http://maps.google.com/maps/api/geocode/json", parameters: parameters as? [String : AnyObject])
.responseJSON(options: NSJSONReadingOptions.AllowFragments) { (request, response, responseObject, error) -> Void in
let json = JSON(responseObject!)
completionHandler(json, error)
}
}
I know this is old thread, by someone may be looking for updated solution like me.
Tested with Swift 4, iOS 11
You can force to get geocoding results in chosen locale by setting extra argument: preferredLocale: Locale.init(identifier: "en_US").
CLGeocoder().reverseGeocodeLocation(location, preferredLocale: Locale.init(identifier: "en_US"), completionHandler: {(placemarks, error) -> Void in
print(location)
if error != nil {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0]
print(pm.administrativeArea!, pm.locality!)
}
else {
print("Problem with the data received from geocoder")
}
})

Trouble retrieving list of facebook friends from json data in swift

I am using FBSDK in my Swift iOS application and currently I am trying to retrieve the list of friends who also use my app. I have two-three people who should show up but whenever I search the graphrequest result for friends it returns nil..
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result:AnyObject!, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
//get Facebook ID
let faceBookID: NSString = result.valueForKey("id") as NSString
//get username
let userName : NSString = result.valueForKey("name") as NSString
//get facebook friends who use app
let friendlist: AnyObject = result.valueForKey("friends") as AnyObject
}
I have the "email", "user_friends", and "public_profile" permissions which should be enough to retrieve this information. Any Ideas on what I am doing wrong?? this is doing my head in as my friend doing an android version has successfully got his working..
My problem here was that I never Actually requested for the list of friends in my facebook graph request...
after replacing FBSDKGraphRequest(graphPath: "me", parameters: nil)
with FBSDKGraphRequest(graphPath: "me?fields=id,name,friends", parameters: nil)
I was able to retrieve the list of friends because the response actually contained information for this. A very trivial mistake on my part.
In v2.0 of the Graph API, you must request the user_friends permission
from each user. user_friends is no longer included by default in every
login. Each user must grant the user_friends permission in order to
appear in the response to /me/friends.
see here : https://developers.facebook.com/bugs/1502515636638396/

How do I create a test user for a native iOS app?

I'm trying to test my native iOS app and I've been having huge problems with test users. Basically it seems that the normal graph based way of creating test users doesn't work for native apps. When I try I get the following response from the server:
{
"error": {
"message": "(#15) This method is not supported for native apps",
"type": "OAuthException",
"code": 15
}
}
This seems to be supported by various posts on SO and a page on the old FB forums:
http://forum.developers.facebook.net/viewtopic.php?id=93086
People say that the only way to create test users for native apps is to create proper fake accounts on FB, which is against FB terms and conditions. Is this really my only option ? I can't believe the FB devs cannot support test accounts for native apps.
Anyone know of any legitimate way to create native app test users ?
At the top of the developer documentation for test users, a GUI for maintaining test users is also mentioned.
In addition to the Graph API functionality described below for managing test users programmatically, there is also a simple GUI in the Developer App, available on your app's Roles page as shown in the screenshots below. It exposes all of the API functions described in this document.
For some reason I don't understand, the Graph API calls aren't available if your app has an 'App Type' (under Settings -> Advanced) of Native/Desktop. But you can use the GUI instead.
You can create a new facebook test user for your app by calling the below function.
Please user your APP ID (go to this link to get your App's ID:https://developers.facebook.com/apps)
Please go to your app on facebook and get the App secret ID
-(void)createNewUser{
NSString *appID=#"Past your App ID"
NSString *appSecret=#"Past your App secret"
NSDictionary *params = #{
#"true": #"installed",
#"access_token": #"appID|appSecret",
};
NSString *path = [NSString stringWithFormat:#"/appID/accounts/test-users"];
/* make the API call */
[FBRequestConnection startWithGraphPath:path
parameters:params
HTTPMethod:#"POST"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
)
{
if (result && !error)
{
NSLog(#"Test-User created successfully: %#", result);
}
else
{
NSLog(#"Error creating test-user: %#", error);
NSLog(#"Result Error: %#", result);
}
}];
}
Please make sure you don't reveal your App secret ID to anyone and never include it in your app hardcoded like that.
Hope it helps
The following works for me using the Facebook iOS SDK v4.1.0:
// Listed as "App ID": https://developers.facebook.com/apps/
NSString *facebookAppId = #"1234_REPLACE_ME_5678";
// Listed as "App Token": https://developers.facebook.com/tools/accesstoken/
NSString *facebookAppToken = #"ABCD_REPLACE_ME_1234";
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"/%#/accounts/test-users",
facebookAppId]
parameters:#{#"installed" : #"true"}
tokenString:facebookAppToken
version:#"v2.3"
HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
NSDictionary *testUser,
NSError *facebookError) {
if (facebookError) {
NSLog(#"Error creating test user: %#", facebookError);
} else {
NSLog(#"access_token=%#", testUser[#"access_token"]);
NSLog(#"email=%#", testUser[#"email"]);
NSLog(#"user_id=%#", testUser[#"id"]);
NSLog(#"login_url=%#", testUser[#"login_url"]);
NSLog(#"password=%#", testUser[#"password"]);
}
}];
When successful, the output is then something like this:
access_token=CACQSQXq3KKYeahRightYouDontGetToLookAtMyAccessTokenspBkJJK16FHUPBTCKIauNO8wZDZD
email=aqhndli_huisen_1430877783#tfbnw.net
user_id=1384478845215781
login_url=https://developers.facebook.com/checkpoint/test-user-login/1384478845215781/
password=1644747383820
Swift4 version.
import FBSDKCoreKit
// App Token can be found here: https://developers.facebook.com/tools/accesstoken/
let appToken = "--EDITED--"
let appID = "--EDITED--"
let parameters = ["access_token": appID + "|" + appToken, "name": "Integration Test"]
let path = "/\(appID)/accounts/test-users"
guard let request = FBSDKGraphRequest(graphPath: path, parameters: parameters, httpMethod: "POST") else {
fatalError()
}
request.start { _, response, error in
if let error = error {
// Handle error.
return
}
if let response = response as? [AnyHashable: Any],
let userID = response["id"] as? String,
let token = response["access_token"] as? String,
let email = response["email"] as? String {
// Handle success response.
} else {
// Handle unexpected response.
}
}
You can use Facebook's Test User API https://developers.facebook.com/docs/test_users/ to create test users, just be sure to use the same App id.
Given a APP_ID and APP_SECRET, the following gives us an APP_ACCESS_TOKEN
curl -vv 'https://graph.facebook.com/oauth/access_token?client_id=APP_ID&client_secret=APP_SECRET&grant_type=client_credentials'
then we can use the token to create test users:
curl 'https://graph.facebook.com/APP_ID/accounts/test-users?installed=true&name=NEW_USER_NAME&locale=en_US&permissions=read_stream&method=post&access_token=APP_ACCESS_TOKEN
in the response body to this command will the new users' email and password.

Resources