Use of unresolved identifier 'GraphRequestHTTPMethod' - ios

I am trying to fetch the user details after integrating the FBSDK.But unfortunately I am getting an error like "Use of unresolved identifier 'GraphRequestHTTPMethod'".If anyone helps me ,Would be great. Thankyou!
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
let loginManager = FBSDKLoginManager()
loginManager.logOut()
}
func getUserInfoFromFB() {
let params = ["fields":"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown"]
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: params)
graphRequest!.start {(urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print("error in graph request:", error)
break
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary) // Respose is here.
}
}
}
}

You need to use GraphRequest Instead of FBSDKGraphRequest Here is Working code (Swift 4)
import FacebookCore
import FacebookLogin
func getUserInfoFromFB() {
let params = ["fields":"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown"]
let graphRequest = GraphRequest(graphPath: "me", parameters: params)
graphRequest.start {
(urlResponse, requestResult) in
switch requestResult {
case .failed(let error):
print("error in graph request:", error)
break
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print(responseDictionary) // Respose is here.
}
}
}
}
Output :
["email": abc#gmail.com, "id": 1118625048361749, "name":
Nikunj Kumbhani, "picture": {
data = {
height = 200;
"is_silhouette" = 0;
url = "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=1118695008301542&height=200&width=200&ext=1557315519&hash=AeRP_G5QJ0Tlff-8";
width = 200;
}; }, "last_name": Kumbhani, "first_name": Nikunj]

Related

fetching user details in facebook integration in swift4

I am trying to fetch the user details after integrating the FBSDK.But unfortunately I am getting an error like "Use of unresolved identifier 'FacebookCore'".If anyone helps me ,Would be great. Thankyou!
//Imported SDK
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
func fetchUserProfile()
{
let AccessToken = FBSDKAccessToken.current()
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, email, name, picture.width(480).height(480)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion))
request.start({ (response, requestResult) in
switch requestResult{
case .success(let response):
print(response.dictionaryValue)
case .failed(let error):
print(error.localizedDescription)
}
})
}
You can fetch data by this way. but you need to install new latest library with pod or manually
import FBSDKLoginKit
func signInWithFB(_ forVC:UIViewController , sucess:#escaping (_ data:NSMutableDictionary) -> (Void) , falure:#escaping (_ error:NSError? , _ cancle:Bool?) -> (Void))
{
let obj_facebook = FBSDKLoginManager()
obj_facebook.loginBehavior = .native
obj_facebook.logOut()
// "user_birthday","user_gender"
obj_facebook.logIn(withReadPermissions: ["public_profile","email"], from: forVC) { (result:FBSDKLoginManagerLoginResult?, error:Error?) -> Void in
if ((error) != nil)
{
falure(error as NSError?, false)
}
else if ((result?.isCancelled) == true)
{
falure(nil, true)
}
else
{
let dicLoginData = NSMutableDictionary()
// name,email,first_name,last_name,birthday
let request = FBSDKGraphRequest(graphPath: "/me?fields=name,email,first_name,last_name", parameters: nil)
let _ =
request?.start(completionHandler: { (Connection:FBSDKGraphRequestConnection?, result:Any!, error:Error?) -> Void in
if error == nil
{
guard let results = result as? [String: Any] else {
falure(nil, false)
return
}
sucess(result)
}
else
{
falure(error as NSError?, false)
}
})
}
}
}
import FBSDKCoreKit
import FBSDKLoginKit
var facebookInfoDict = [String:AnyObject]()
var profileURL = ""
var facebookName = ""
var socialDetailDict = [String:AnyObject]()
#IBAction func loginWithFacebookAction(_ sender: UIButton) {
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logOut()
fbLoginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends"], from: self) { (result, error) -> Void in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result!
// if user cancel the login
if (result?.isCancelled)!{
return
}
if(fbloginresult.grantedPermissions.contains("email")) {
if Reachability.isConnectedToNetwork() {
self.getFBUserData()
} else {
}
}
}
}
}
//function is fetching the facebook user data
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.facebookInfoDict = result as! [String : AnyObject]
print(self.facebookInfoDict)
if let profileData = self.facebookInfoDict["picture"]!["data"] as? Dictionary<String, AnyObject> {
self.socialDetailDict = self.facebookInfoDict
self.profileURL = profileData["url"] as! String
self.facebookName = self.facebookInfoDict["name"] as! String
UserDefaults.standard.synchronize()
}
}
})
}
}
You can try integrating the "FacebookCore" and "FacebookLogin"
pod 'FacebookLogin'
pod 'FacebookShare'
After pod install, try this code, it's using for swift 4
import FacebookLogin
import FacebookCore
#IBAction func btnFacebookLoginTapped(_ sender: Any) {
let loginManager = LoginManager()
loginManager.logIn(readPermissions: [.publicProfile, .email], viewController: self) { (result) in
switch result {
case .success(grantedPermissions: _, declinedPermissions: _, token: _):
print("Succesfully logged in into Facebook.")
self.fetchFacebookUser()
case .failed( let error ):
print(error)
self.showAlertError(TL("warning_facebook_connect_failed"))
case .cancelled: break
}
}
}
fileprivate func fetchFacebookUser() {
let graphRequestConnection = GraphRequestConnection()
let graphRequest = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: .defaultVersion)
graphRequestConnection.add(graphRequest, completion: { (httpResponse, result) in
switch result {
case .success(response: let response):
print(responseDict)
case .failed( _):
}
})
graphRequestConnection.start()
}

Swift - Getting error from facebook login

just to start off with I have looked at many examples but can't seem to find a solution. Well I thought I did but it doesn't seem to work.
What I'm trying to do is use the Firebase auth login method for facebook, which works by the way. My issue is I want to link the password auth credentials and facebook auth credentials when the facebook method throws the error that the email/credentials already exist. I read here that I could use error.email but it doesn't give me the option to access the email.error. I might be missing something and I have spent a lot of time trying to figure it out.
Here is my code:
func signInFacebookUser() {
let fbLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in
if let error = error {
self.errorMessagePopUp(title: "Failed to login", message: error)
return
}
guard let accessToken = FBSDKAccessToken.current() else {
print("Failed to get access token")
return
}
let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString)
Auth.auth().signIn(with: credential, completion: { (user, error) in
if let error = error {
let errCode = AuthErrorCode(rawValue: error._code)!
switch errCode {
case .accountExistsWithDifferentCredential:
// somehow obtain email right here.
self.showSigninForm(attributes: self.attributes(), style: .light)
return
default:
return
}
}
self.performSegue(withIdentifier: "signInBtnPressed", sender: nil)
})
}
}
This Works for me Swift4
#objc func loginButtonClicked() {
var alertController = UIAlertController()
let loginManager = LoginManager()
loginManager.logIn(readPermissions: [ReadPermission.email], >viewController: self, completion: {loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(_, _, let accessToken):
print(accessToken)
}
})
}
func getDataUser() {
let request = GraphRequest(graphPath: "me?fields=first_name,last_name,email",
parameters:[:],
httpMethod: .GET)
request.start { httpResponse, result in
switch result {
case .success(let response): do {
print("Graph Request Succeeded: \(response)")
let dicval = response.dictionaryValue
let email = dicval?.keys
print("Graph Request Succeeded: \(String(describing: email))")
}
case .failed(let error):
print("Graph Request Failed: \(error)")
}
}
}
}
Try this code
#IBAction func facebookLoginButtonTapped(_ sender: UIButton) {
if Utility.checkInternet(){
let fbLoginManager: FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["email", "public_profile"], from: self) { (result, error) in
if (error == nil){
let fbLoginResult: FBSDKLoginManagerLoginResult = result!
if fbLoginResult.grantedPermissions != nil {
if(fbLoginResult.grantedPermissions.contains("email")){
self.facebookLogin()
}
}
}
}
}
else{
Utility.showAlert("Connection Error!", message: "Please check internet connection and retry.", viewController: (self.window?.rootViewController)!)
}
}
func facebookLogin() {
Utility.showProgress("")
if((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, name, first_name, last_name, picture.type(large), email "]).start(completionHandler: { (connection, result, error) in
if result == nil {
}
else{
self.userResults = result as! [String : AnyObject]
self.email = (self.userResults["email"] as? String) ?? ""
if (self.email != "") {
}
else{
Utility.showAlert("Login Faild", message: error?.localizedDescription, viewController: self)
}
}
})
}
}

Posting as a Facebook Page using Swift

I would like my app to post to my Facebook business page. I've can get it to post to my person Facebook feed, and I've also gotten it to post to my business page, posting as my personal user account. However, I'd like it to post to the main business page feed, as the business account.
As shown here in Facebook's documentation:
https://developers.facebook.com/docs/pages/publishing
Here's is what I've tried. The following code posts to the page using my personal user account.
I was trying to replace the accessToken parameter in the POST GraphRequest with the pageAccessToken... but couldn't get it to work.
var pageAccessToken : GraphResponse?
func getPageAccessToken() {
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/\(pageID)?fields=access_token")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Success: \(response)")
self.pageAccessToken = response
case .failed(let error):
print("Graph Request Fail: \(error)")
}
}
connection.start()
}
func requestPublishPermissions() {
let loginManager = LoginManager()
loginManager.logIn(publishPermissions: [ .managePages, .publishPages], viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("grantedPermissions = \(grantedPermissions) \n" +
"declinedPermissions = \(declinedPermissions) \n" +
"accessToken = \(accessToken)")
}
}
}
func postMessage() {
let requestPage : GraphRequest = GraphRequest(graphPath: "\(pageID)/feed", parameters: ["message" : "Hello Page!"], accessToken: AccessToken.current, httpMethod: .POST, apiVersion: .defaultVersion)
requestPage.start({ (connection, result) -> Void in
print("RESULT = \(result)")
})
}
Thank you for any advice tips you can give!
swift 5 update
let pageID = "yourFBPage"
var pageAccessToken : String?
func getPageAccessToken() {
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "\(pageID)", parameters: ["fields": "access_token"])) { httpResponse, result,error in
if let error = error {
print(error.localizedDescription)
} else {
let info = result as! [String : AnyObject]
if info["access_token"] as? String != nil {
self.pageAccessToken = info["access_token"] as? String
}
//print(result)
self.postMessage()
}
}
connection.start()
}
func postMessage() {
let requestPage : GraphRequest = GraphRequest(graphPath: "\(pageID)/feed", parameters: ["message" : "Hello Page!"], tokenString: self.pageAccessToken, version: nil , httpMethod: .post )
requestPage.start(completionHandler: { (connection, result, error) -> Void in
if let error = error {
print(error.localizedDescription)
} else {
//print("RESULT = \(result)")
}
})
}
I eventually got it working on my own. I'll share the answer, for those trying to do the same thing.
To post a simple text message to a page on Facebook:
let pageID = {Get Your Page ID On Facebook}
var pageAccessToken : AccessToken?
func requestPublishPermissions() {
let loginManager = LoginManager()
loginManager.logIn(publishPermissions: [ .managePages, .publishPages], viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("grantedPermissions = \(grantedPermissions) \n" +
"declinedPermissions = \(declinedPermissions) \n" +
"accessToken = \(accessToken)")
}
}
}
func getPageAccessToken() {
let connection = GraphRequestConnection()
connection.add(GraphRequest(graphPath: "/\(pageID)?fields=access_token")) { httpResponse, result in
switch result {
case .success(let response):
print("Graph Request Success: \(response)")
self.pageAccessToken = AccessToken.init(authenticationToken: response.dictionaryValue?["access_token"] as! String)
case .failed(let error):
print("Graph Request Fail: \(error)")
}
}
connection.start()
}
func postMessage() {
let requestPage : GraphRequest = GraphRequest(graphPath: "\(pageID)/feed", parameters: ["message" : "Hello Page!"], accessToken: self.pageAccessToken, httpMethod: .POST, apiVersion: .defaultVersion)
requestPage.start({ (connection, result) -> Void in
print("RESULT = \(result)")
})
}

me/albums return data nil facebook swift

i develop an app which take users albums and photos from facebook and show them in app.
I use custom button:
#objc func loginButtonClicked() {
let loginManager = LoginManager()
loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in!")
self.getFBUserData()
}
}
}
if login success i call another method which request albums
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil) {
FBSDKGraphRequest(graphPath: "/me/albums", parameters: nil).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil) {
print("result = \(result)")
let responseDictionary = JSON(result)
if let data = responseDictionary["data"].array {
print("data result = \(data)")
print("----------")
for i in 0..<data.count {
print(data[i])
}
}
}
})
}
}
the printed result is
result = Optional({
data = (
);
})
if i will change request from "me/albums" to "me" i will take some info that won't be nil. Have anybody any ideas?

iOS facebookSDK get user full details

Iam using the last FBSDK (using swift)
// MARK: sign in with facebook
func signInWithFacebook()
{
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
println("already logged in ")
self.returnUserData()
return
}
var faceBookLoginManger = FBSDKLoginManager()
faceBookLoginManger.logInWithReadPermissions(["public_profile", "email", "user_friends"], handler: { (result, error)-> Void in
//result is FBSDKLoginManagerLoginResult
if (error != nil)
{
println("error is \(error)")
}
if (result.isCancelled)
{
//handle cancelations
}
if result.grantedPermissions.contains("email")
{
self.returnUserData()
}
})
}
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
println("the access token is \(FBSDKAccessToken.currentAccessToken().tokenString)")
var accessToken = FBSDKAccessToken.currentAccessToken().tokenString
var userID = result.valueForKey("id") as! NSString
var facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
println("fetched user: \(result)")
}
when I print the fetched user I get only the id and the name ! ,
but i requested a permission for email and friends and profile ,
what's wrong ???
BTW : I moved this project from my macbook to another macbook ( because I formatted mine) it worked very well when it was at the the macbook which I created the project on , but after moving the project (using bitbucket clone) I got this results .
As per the new Facebook SDK, you must have to pass the parameters with the FBSDKGraphRequest
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
Documentations Link : https://developers.facebook.com/docs/facebook-login/permissions/v2.4
User object reference : https://developers.facebook.com/docs/graph-api/reference/user
With public profile you can get gender :
public_profile (Default)
Provides access to a subset of items that are part of a person's public profile. A person's public profile refers to the following properties on the user object by default:
id
name
first_name
last_name
age_range
link
gender
locale
timezone
updated_time
verified
Swift 4
An example in Swift 4 that also shows how to correctly parse out the individual fields from the result:
func fetchFacebookFields() {
//do login with permissions for email and public profile
FBSDKLoginManager().logIn(withReadPermissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//make sure we have a result, otherwise abort
guard let result = result else { return }
//if cancelled nothing todo
if result.isCancelled { return }
else {
//login successfull, now request the fields we like to have in this case first name and last name
FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name"]).start() {
(connection, result, error) in
//if we have an error display it and abort
if let error = error {
log.error(error.localizedDescription)
return
}
//parse the fields out of the result
if
let fields = result as? [String:Any],
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String
{
log.debug("firstName -> \(firstName)")
log.debug("lastName -> \(lastName)")
}
}
}
}
}
I guess this code should help you get the required details
Swift 2.x
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
print("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
let userID : NSString = result.valueForKey("id") as! NSString
print("User Email is: \(userID)")
}
})
In Swift 4.2 and Xcode 10.1
#IBAction func onClickFBSign(_ sender: UIButton) {
if let accessToken = AccessToken.current {
// User is logged in, use 'accessToken' here.
print(accessToken.userId!)
print(accessToken.appId)
print(accessToken.authenticationToken)
print(accessToken.grantedPermissions!)
print(accessToken.expirationDate)
print(accessToken.declinedPermissions!)
let request = GraphRequest(graphPath: "me", parameters: ["fields":"id,email,name,first_name,last_name,picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
case .failed(let error):
print(error)
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.present(storyboard, animated: true, completion: nil)
} else {
let loginManager=LoginManager()
loginManager.logIn(readPermissions: [ReadPermission.publicProfile, .email, .userFriends, .userBirthday], viewController : self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in : \(grantedPermissions), \n \(declinedPermissions), \n \(accessToken.appId), \n \(accessToken.authenticationToken), \n \(accessToken.expirationDate), \n \(accessToken.userId!), \n \(accessToken.refreshDate), \n \(accessToken.grantedPermissions!)")
let request = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, first_name, last_name, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion)
request.start { (response, result) in
switch result {
case .success(let value):
print(value.dictionaryValue!)
case .failed(let error):
print(error)
}
}
let storyboard = self.storyboard?.instantiateViewController(withIdentifier: "SVC") as! SecondViewController
self.navigationController?.pushViewController(storyboard, animated: true)
}
}
}
}
https://developers.facebook.com/docs/graph-api/reference/user

Resources