Facebook GET request - Should contain “fields” parameter for /me/friends - ios

func getFbFriendsAndSendToServer() {
let request = FBSDKGraphRequest(graphPath:"/me/friends", parameters: ["fields": "id, name, email"]);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
//Save friends ID
let fbFriendsData : NSArray = result["data"] as! NSArray
for fbData in fbFriendsData {
self.friendsFbIDs.addObject(fbData["id"] as! String);
}
//send friends FB IDs to remote server
self.sendFriendsIDsOnServer()
}
else {
self.showAlertViewWithRetryButton("PullCar", message: "Unable to get your Facebook friends. Please check your internet connection and try again.", tag: 102)
}
}
}
This Piece of code will not give me error as below.
-[ Facebook Graph API GET request - Should contain “fields” parameter ]

Related

How to get user's list of Events they are attending from FBSDK (Swift 4, iOS)

I keep getting back an empty array from the FBSDK even though my user account in Facebook is marked as attending 4 upcoming events.
Here is my code
func loadEvents() {
let parameters = ["fields": "id, name, place"]
FBSDKGraphRequest(graphPath: "me/events", parameters: parameters).start { (connection, result, error) -> Void in
if ((error) != nil) {
print("Error")
print("Error getting events \(String(describing: error))");
}
print(result)
if let result = result as? [String: Any] {
if let data = result["data"] as? NSArray {
//print(data)
}
}
}
And the result im getting in data is the following:
["data": <__NSArray0 0x60c00000b410>(
) ]
Any help appreciated. Is this a permissions issue? or am i passing in the wrong parameters object?
OK it was a permissions issue. I needed to add the user_events permission when login.
loginButton.readPermissions = ["public_profile", "user_events"]

can not get twitter user details in swift

I am trying to load twitter user details using this code
#IBAction func twitterLogin(sender: UIButton) {
if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {
let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierTwitter)
accountStore.requestAccessToAccountsWithType(accountType, options: nil, completion: { (granted : Bool, error : NSError?) -> Void in
if error != nil {
print("Error in getting permission : \(error)")
} else {
if granted {
let accounts : NSArray = self.accountStore.accountsWithAccountType(accountType)
if accounts.count > 0 {
self.twitterAccount = accounts.lastObject as? ACAccount
let url = NSURL(string: "https://api.twitter.com/1.1/users/show.json")
let parameters : NSDictionary = ["fields": "user_id,screen_name"]
let twitterRequest : SLRequest = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: SLRequestMethod.GET, URL: url, parameters: parameters as [NSObject : AnyObject])
twitterRequest.account = self.facebookAccount
twitterRequest.performRequestWithHandler({ (responseData : NSData?, urlResponse : NSHTTPURLResponse?, error : NSError?) -> Void in
if error != nil {
print("Error : \(error)")
} else {
// print("data : \(responseData)")
if let response = responseData {
var dict = NSDictionary()
do {
dict = try! NSJSONSerialization.JSONObjectWithData(response, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
} catch let error as NSError {
print("Error : \(error)")
}
print(dict)
}
}
})
}
} else {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.showAlert(nil, message: "Permission not granted")
})
}
}
})
} else {
self.askForSettingsChange("No Twitter Account", message: "There are no Twitter accounts configured. You can add or create Twitter account in Settings")
}
}
output
{
errors = (
{
code = 215;
message = "Bad Authentication data.";
}
);
}
Get many examples but cannot get proper solution.
I think that may be problem in api call or may be parameters.
Try to correct but no success
Fabric is sdk which is providing twitter login with easy authentication via either guest or user login.
Twitter login using Fabric
Sample Code written in Swift https://docs.fabric.io/ios/twitter/index.html
If you want to use raw REST calls against the API, follow the OAuth details in developer documentation
https://dev.twitter.com/oauth

Why am I getting this error when accessing Facebook information of user?

Why is it giving me the error 2015-09-14 20:56:31.773 Musec[7207:3288153] FBSDKLog: starting with Graph API v2.4, GET requests for /me should contain an explicit "fields" parameter I am trying to access user information like friends, email, etc. How do I fix the error? Below is the login plus the permissions to get access to user info.
#IBAction func loginWithFB(sender: AnyObject) {
var permissions = [ "public_profile", "email", "user_friends"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, block: { (user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
println("User signed up and logged in through Facebook!")
self.performSegueWithIdentifier("success", sender: self)
//let params = ["fields": "name, email, friends"]
let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "name, email, friends"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
//get username
let userName : NSString = result.valueForKey("name") as! NSString
println(userName)
//get Facebook ID
let email: NSString = result.valueForKey("email") as! NSString
println(email)
//get facebook friends who use app
let friendlist: NSString = result.valueForKey("friends") as! NSString
println(friendlist)
}
})
} else {
println("User logged in through Facebook!")
self.performSegueWithIdentifier("success", sender: self)
}
} else {
println("Uh oh. The user cancelled the Facebook login.")
}
})
}
I don't think that FBSDKLog: starting with Graph API v2.4, GET requests for /me should contain an explicit "fields" parameter is actually an error. It is just a Log. If you will run the code and set a break point you will find that, error is actually nil and you will be able to successfully compile the code and see the else portion of the code getting executed.
Now, you are trying to access the name of Facebook user but not passing name in the fields. That is why you will get name as null. Pass name as list of parameters.
let params = ["fields": "name, email, friends"] <----- This line
Or here:
let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "name, email, friends"])
Now, you will be able to fetch name, email and friends of the Facebook user.

Unable to use FBSDKGraphRequest with Parse login

I'm using Parse to login with facebook on my app.
This is my code :
//set permissions required
let permissionsArray = ["user_about_me"]
//log in
PFFacebookUtils.logInWithPermissions(permissionsArray, block: { (pUser, pError) -> Void in
//if user is correctly loggin
if pUser != nil && pError == nil{
//request facebook for more informations
var request = FBSDKGraphRequest(graphPath: "me", parameters: nil)
request.startWithCompletionHandler({ (connection, result, error) -> Void in
NSLog("\(error)")
})
}
})
I am correctly log in with parse, but when i'am asking for my informations, have always have this message :
com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 2500;
message = "An active access token must be used to query information about the current user.";
type = OAuthException;
};
};
code = 400;
}}
I have used Facebook SDK for login, i make a Parse login with returned token and i can get my user's informations after that.
I have solved my issue with this code :
FBSDKLoginManager().logInWithReadPermissions(["user_about_me"], handler: { (result, error) -> Void in
if let resultLogin : FBSDKLoginManagerLoginResult = result as? FBSDKLoginManagerLoginResult{
//if no error
if error == nil
&& resultLogin.grantedPermissions.contains("user_about_me"){
var accessToken = FBSDKAccessToken.currentAccessToken().tokenString
var expiration = FBSDKAccessToken.currentAccessToken().expirationDate
var facebookID = FBSDKAccessToken.currentAccessToken().userID
PFFacebookUtils.logInWithFacebookId(facebookID, accessToken: accessToken, expirationDate: expiration, block: { (pUser, pError) -> Void in
//if user is correctly loggin
if pUser != nil && pError == nil{
//request facebook for more informations
var request = FBSDKGraphRequest(graphPath: "me", parameters: nil)
request.startWithCompletionHandler({ (connection, result, error) -> Void in
NSLog("\(error)")
})
}
})
}
}
})

how to get posts from facebook page using GraphAPI in swift

My app had a functionality which is : get posts from Facebook page and show it in the app.
i searched and i found that i should use Facebook GraphAPI :
https://developers.facebook.com/docs/graph-api/using-graph-api/v2.3#reading
i follow the previous link, but i get error :
"An access token is required to request this resource."
i have the access token for the page, but i really don't know how to assign it in my request.
any help please?
thanks a lot!
1. Using Facebook SDK.
LOGIN FACEBOOK BUTTON
#IBAction func click_Facebook(sender: AnyObject)
{
let loginView : FBSDKLoginManager = FBSDKLoginManager()
loginView.loginBehavior = FBSDKLoginBehavior.Browser
loginView.logInWithReadPermissions(["public_profile","user_friends","user_photos","user_location","user_education_history","user_birthday","user_posts"], handler: { (result : FBSDKLoginManagerLoginResult!, error : NSError!) -> Void in
if ((error) != nil)
{
// Process error
self.alertWithMessaage(error.localizedDescription)
}
else if result.isCancelled {
// Handle cancellations
}
else {
self.returnUserData()
}
})
}
After login calling the below function.
var Requset : FBSDKGraphRequest
println("\(FBSDKAccessToken.currentAccessToken())")
var acessToken = String(format:"%#", FBSDKAccessToken.currentAccessToken().tokenString) as String
println("\(acessToken)")
var parameters1 = ["access_token":FBSDKAccessToken.currentAccessToken().tokenString]
Requset = FBSDKGraphRequest(graphPath:"me/posts", parameters:parameters1, HTTPMethod:"GET")
Requset.startWithCompletionHandler({ (connection, result, error) -> Void in
MBProgressHUD.hideHUDForView(appDelegate.window, animated: true)
if ((error) != nil)
{
println("Error: \(error)")
}
else
{
println("fetched user: \(result)")
var dataDict: AnyObject = result!.objectForKey("data")!
}
})
}
2. Using Default Facebook App.
// Get Access TOKEN
var _accountStore: ACAccountStore = ACAccountStore()
var accountType : ACAccountType = _accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)!
var accounts : NSArray = _accountStore.accountsWithAccountType(accountType)!
var facebookAccount1: ACAccount = accounts.lastObject! as ACAccount
println("== \(facebookAccount1.credential.oauthToken)")
// Pass AccessToken To Parameter
var acessToken = String(format:"%#", facebookAccount1.credential.oauthToken) as String
var parameters = ["access_token":acessToken] as NSDictionary
//SLRequset
var imageURL : NSURL = NSURL(string: "Your graph URL")!
println("=== TOKEN : \(LoginService().currentAccount?.credential.oauthToken)")
var Requset = SLRequest(forServiceType: SLServiceTypeFacebook, requestMethod: SLRequestMethod.GET, URL: imageURL, parameters: parameters)
Requset.account = account
Requset.performRequestWithHandler { (responseData : NSData!, urlResponse : NSHTTPURLResponse!, error : NSError!) -> Void in
if (error != nil)
{
self.alertWithMessaage(error.localizedDescription)
}
else{
var datastring = NSString(data: responseData, encoding: NSUTF8StringEncoding)
println("== \(datastring)")
var error:NSError? = nil
var UserDict = NSJSONSerialization.JSONObjectWithData(responseData, options:nil, error: &error) as? NSDictionary
}
}
Swift 4.2 Update Code
in your viewDidLoad()
create faceBook Button for Login and Logout.
let loginButton = FBLoginButton(permissions: [ .publicProfile, .email, .userPosts, .userPhotos])
loginButton.center = view.center
view.addSubview(loginButton)
Now Create Function to get FaceBook Posts
func getPosts() {
let accessToken = AccessToken.current?.tokenString
let params = ["access_token" : accessToken ?? ""]
let request = GraphRequest(graphPath: "/me/posts/", parameters: params, httpMethod: .get)
request.start(completionHandler: { (test, result, error) in
if(error == nil)
{
print(result!)
}
})
}
In result you will get Data of your facebook posts!

Resources