I am using interested in obtaining the following info from a user's fb profile :
email
name
profile picture link
age
To do so I use the following code:
let accessToken = FBSDKAccessToken.currentAccessToken()
let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"picture.redirect(false),email,name,gender,age_range,birthday"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
if(error == nil)
{
print("result \(result)")
}
else
{
print("error \(error)")
}
}) }
This returns:
result {
"age_range" = {
min = 21;
};
email = "dedewdd#gmail.com";
gender = male;
id = xxxxxxxxxxxx;
name = "John Smith";
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p50x50/dwqdwddqwdwqdw";
};
};
}
The problem with this is that this image is 50X50 pixels, I would like to obtain a link to a larger image.
So I use Kingfisher to download the image but essentially the NSURL is the key to getting a larger image. IF this doesnt work, then try changing the "50x50" in the url to "250x250" and see if that works
if FBSDKAccessToken.currentAccessToken() != nil {
let userID = FBSDKAccessToken.currentAccessToken().userID
if(userID != nil) //should be != nil
{
print(userID)
}
let URL = NSURL(string: "http://graph.facebook.com/\(userID)/picture?type=large")!
profileImage.kf_setImageWithURL(URL)
}else{
}
}
Try this:
#IBAction func FacebookLogin(sender: AnyObject) {
var message = String()
if Reachability.isConnectedToNetwork() == true {
let loginView : FBSDKLoginManager = FBSDKLoginManager()
loginView.loginBehavior = FBSDKLoginBehavior.Web
if (FBSDKAccessToken .currentAccessToken() != nil) {
loginView.logOut()
}else{
loginView.logInWithReadPermissions(["email","public_profile"], fromViewController: self, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) in
if (error != nil){
print("Login Process Eroor!"+error.localizedDescription)
}else if result.isCancelled{
print("User cancled Login")
}else{
print("Login Success")
if result.grantedPermissions .contains("email"){
self.fetchUserInfo()
}else{
message = message.stringByAppendingString("Facebook email permission error")
WebService.ShowToastMessage(message, viewcontroller: self)
}
}
})
}
} else {
message = message.stringByAppendingString("Make sure your device is connected to the internet.")
WebService.ShowToastMessage(message, viewcontroller: self)
}
}
func fetchUserInfo() -> Void {
if (FBSDKAccessToken .currentAccessToken() != nil) {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id,gender,birthday,email,name,picture.width(480).height(480)"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
print("Error: \(error.localizedDescription)")
}
else
{
print("fetched user: \(result)")
let id : NSString = result.valueForKey("id") as! String
let name:NSString = result.valueForKey("name") as! String
let gender:NSString = result.valueForKey("gender") as! String
let email:NSString = result.valueForKey("email") as! String
print("User ID is: \(id)")
print("User email is:\(email)")
print("User name is :\(name)")
print("User gender is :\(gender)")
}
})
}
}
According to the facebook docs
https://developers.facebook.com/docs/graph-api/reference/user/picture/
You can pass width and height of image,following are the list of params..
So you can try something like ..
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{ #"fields" : #"id,name,picture.width(100).height(100)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
}]
Use this code for getting user id, name and profilepicture with one request : https://stackoverflow.com/a/45462114/1168602
Tested on xcode 8.3.3
Related
hello i need some help i've been searching hours about this subject i tried a lot of thing but i couldn't do it.
Here is my code
let facebookReadPermissions = ["public_profile", "email"]
func getFBUserData() {
if((FBSDKAccessToken.current()) != nil){
self.getFBUserDataSecondStep()
} else {
FBSDKLoginManager().logIn(withReadPermissions: self.facebookReadPermissions, from: self) { (result, error) in
if error != nil {
FBSDKLoginManager().logOut()
} else if (result?.isCancelled)! {
FBSDKLoginManager().logOut()
} else {
self.showLoadingAlert()
let grantedPermissions = result?.grantedPermissions.map( {"\($0)"} )
for permission in self.facebookReadPermissions {
if (grantedPermissions?.contains(permission))! {
print("permission: \(permission)")
// CONSOLE WRITING HERE LIKE THIS
// permission: public_profile
// permission: email
}
}
if (result?.grantedPermissions.contains("email"))! {
print("result is: \(result?.description ?? "nil")")
// result is: <FBSDKLoginManagerLoginResult: 0x1c0441920> ( console )
self.getFBUserDataSecondStep()
} else {
FBSDKLoginManager().logOut()
}
}
}
}
}
func getFBUserDataSecondStep(){
FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
if let dict = result as? Dictionary<String, Any> {
print(result)
// COMING WITH LIKE THIS
//"first_name" = Esn;
//id = 10156020817443470;
//"last_name" = "\U00c7ak\U0131ralar";
//name = "Esn Banu\U015f \U00c7ak\U0131ralar";
//--// Where is email ?
var email = ""
var firstName = ""
var lastName = ""
var facebookId = ""
var facebookToken = ""
if let controlEmail = dict["email"] {
email = controlEmail as! String
}
if let controlFirstName = dict["first_name"] {
firstName = controlFirstName as! String
}
if let controlLastName = dict["last_name"] {
lastName = controlLastName as! String
}
if let controlFacebookId = FBSDKAccessToken.current().userID {
facebookId = controlFacebookId
}
if let controlFacebookToken = FBSDKAccessToken.current().tokenString {
facebookToken = controlFacebookToken
}
loginWithFacebook(email: email, firstName: firstName, lastName: lastName, facebookId: facebookId, accessToken: facebookToken, finishedClosured: { (state) in
if state {
let mainPage = self.mainStoryBoard.instantiateViewController(withIdentifier: "SWRevealViewController")
self.removeLoadingAlert()
self.passPage(page: mainPage)
return
}
self.removeLoadingAlert()
self.alert(message: "Giris Basarisiz")
return
})
}
} else {
print(error?.localizedDescription)
}
})
}
i need go get email of person to register user to my application. But email doesn't come whatever i tried. How can i fix this issue and also if i try with my personel account its ok no problem but another user it can be problem.
Note : This is in swift 4.0
//giving permission
func getpermission(){
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
// fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if (error == nil){
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if(fbloginresult.grantedPermissions.contains("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
}
}
}
// Get all details from here
func getFBUserData(){
var fbId : String = ""
var fbEmail : String = ""
var fbName : String = ""
var fbPickUrl : String = ""
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
//everything works print the user data
print("Result111:\(String(describing: result)) "as Any)
}
let dict = result as! NSDictionary
print("FB Email1st:\(dict)")
fbId = dict["id"] as! String
fbName = dict["name"] as! String
fbEmail = dict["email"] as! String
//get user picture url from dictionary
fbPickUrl = (((dict["picture"] as? [String: Any])?["data"] as? [String:Any])?["url"] as? String)!
print("FB ID: \(fbId)\n FB Email:\(fbEmail) \n FbName:\(fbName) \n FBProfileUrl:\(fbPickUrl)\n")
})
}
}
let loginManager = FBSDKLoginManager()
loginManager.logIn(withReadPermissions: ["user_about_me", "email" , "user_birthday","user_hometown"], from: self) { (loginResult, error) in
if error != nil
{
self.showalert(strMessage: (error?.localizedDescription)!)
}
else
{
if loginResult?.grantedPermissions == nil
{
self.showalert(strMessage: "Login Permissions not granted")
return
}
if (loginResult?.grantedPermissions.contains("email"))!
{
if (loginResult?.grantedPermissions.contains("user_birthday"))!
{
self.getFBUserData()
}
else
{
self.getFBUserData()
}
}
}
}
}
func getFBUserData()
{
FBSDKGraphRequest.init(graphPath: "me?fields=id,name,email,first_name,last_name,cover,picture.type(large),gender,birthday,hometown", parameters: nil).start(completionHandler: { (connection , result , error ) in
if(error == nil){
DispatchQueue.main.async {
let dictionary = result as! NSDictionary
print(dictionary)
print("Name : \(dictionary.value(forKey: "name")!)")
print("FB ID : \(dictionary.value(forKey: "id")!)")
self.FaceBookID = dictionary.value(forKey: "id") as? String
}
}else{
self.showalert(strMessage: "Somthig Went Wrong..!")
}
})
I am having some trouble in my code. I gave the permission of "user_photos" in "loginwithreadpermission" but still not getting the users album. I also tried this "fbuserid/albums" but this is also not working for me. Please help me what I am doing wrong.
This is my Login Code:
#IBAction func facebookLogin(sender: AnyObject)
{
let facebookLogin = FBSDKLoginManager()
facebookLogin.logOut()
facebookLogin.logInWithReadPermissions(["email" , "user_photos"], fromViewController: nil) { (facebookResult, facebookError) in
if facebookError != nil {
print("Login Failed. Error: \(facebookError)")
}
else {
if !(facebookResult.isCancelled)
{
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
if accessToken != nil
{
token = accessToken
let credential = FIRFacebookAuthProvider.credentialWithAccessToken(accessToken)
print("1")
FIRAuth.auth()?.signInWithCredential(credential)
{
(user, error) in
if error != nil
{
print("Error Firebase: \(error)")
}
else
{
if self.userEmails.contains(user!.email!)
{
print("User Already Exist")
NSUserDefaults.standardUserDefaults().setValue(user?.uid, forKey: KEY_UID)
USER_UID = (user?.uid)!
print("id:\(USER_UID)")
LOGIN_FLAG = 1
FaceBookFlag = 1
self.performSegueWithIdentifier("fbLogin", sender: nil)
}
else if user!.email != nil
{
print("Creating a User Data in FB")
var request = FBSDKGraphRequest(graphPath:"me", parameters: ["fields":"email,first_name,age_range"]);
request.startWithCompletionHandler({ (connection, result, error) in
if error == nil
{
print("res: \(result)")
if let dob = result.valueForKey("age_range") as? [String: AnyObject]
{
print("dd: \(dob["min"]!)")
self.dateOfBirth = String(dob["min"]!)
print("dob: \(dob) , date: \(self.dateOfBirth)")
print(" date: \(self.dateOfBirth!)")
}
}
else
{
print("error:: \(error)")
}
let displayName = user?.displayName!.componentsSeparatedByString(" ")
let firstName = displayName![0]
let lastName = displayName![1]
print("url: \(user?.photoURL)")
let profilePicUrl = user?.photoURL
let picture = String(profilePicUrl!)
let userEmail = user!.email!
let _user = ["username": "\(firstName+lastName)","emailAddress": "\(userEmail)", "dateOfBirth": "\(self.dateOfBirth!)"]
ref.child("users").child(user!.uid).setValue(_user)
ref.child("users").child(user!.uid).child("images").setValue([picture])
NSUserDefaults.standardUserDefaults().setValue(user?.uid, forKey: KEY_UID)
USER_UID = (user?.uid)!
LOGIN_FLAG = 1
FaceBookFlag = 1
//Segue to reveal view controller
self.performSegueWithIdentifier("fbLogin", sender: nil)
})
}
}
}
}
}
}
}
}
And This is my Code where I am requesting to give me the albums of current user :
func getAlbums()
{
//for sake of running i hardcoded the FBuserId.
let fbid = "758111074330935"
//169682503464671/photos
let graphRequest = FBSDKGraphRequest(graphPath: "/\(fbid)/albums", parameters: ["fields":"photos,picture"] , HTTPMethod: "GET")
graphRequest.startWithCompletionHandler { (connection, result, error) in
if error != nil
{
print(error)
}
else
{
print("rr:\(result)")
let value = result.valueForKey("data")
print("value:\(value) ... \(result["data"])")
if let graphData = result.valueForKey("data") as? [AnyObject]
{
print("array of Any")
for obj in graphData
{
print("id: \(obj.valueForKey("id")!)")
let id = String(obj.valueForKey("id")!)
self.albumsId.append(id)
//Also save the album link here to.
}
}
}
You have a wrong set of fields for this type of request.
Check this doc to verify the fields that are available: https://developers.facebook.com/docs/graph-api/reference/v2.7/album
In particular, I'm getting the following error (which is self-explained):
{
"error": {
"message": "(#100) Unknown fields: email,first_name.",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "G0POfi9dWkb"
}
}
I have a log in system in my app swift 2.0 integrated with Facebook, I'm able to get some user informations and profile_picture.
I'm wondering how to get the cover Image from the User logged :
let requestParameters = ["fields": "id, email, first_name, last_name, name, gender, cover"]
let userDetails = FBSDKGraphRequest(graphPath: "me", parameters: requestParameters)
userDetails.startWithCompletionHandler { (connection, result, error:NSError!) -> Void in
if(error != nil)
{
print("\(error.localizedDescription)")
return
}
if(result != nil)
{
let userId:String = result["id"] as! String
let userFirstName:String? = result["first_name"] as? String
let userLastName:String? = result["last_name"] as? String
let userEmail:String? = result["email"] as? String
let userName:String? = result["name"] as? String
let userGender:String? = result["gender"] as? String
let userCover:UIImage? = result["cover"] as? UIImage
print(requestParameters)
print(userDetails)
print(userCover)
print("\(userEmail)")
let myUser:PFUser = PFUser.currentUser()!
// Save first name
if(userFirstName != nil)
{
myUser.setObject(userFirstName!, forKey: "firstNameColumn")
}
//Save last name
if(userLastName != nil)
{
myUser.setObject(userLastName!, forKey: "lastNameColumn")
}
// Save email address
if(userEmail != nil)
{
myUser.setObject(userEmail!, forKey: "email")
}
// Save email address
if(userGender != nil)
{
if (userGender == "male"){
myUser.setObject("Masculino", forKey: "genderColumn")
} else {
myUser.setObject("Feminino", forKey: "genderColumn")
}
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Get Facebook profile picture
let userProfile = "https://graph.facebook.com/" + userId + "/picture?type=large"
let profilePictureUrl = NSURL(string: userProfile)
let profilePictureData = NSData(contentsOfURL: profilePictureUrl!)
if(profilePictureData != nil)
{
let profileFileObject = PFFile(data:profilePictureData!)
myUser.setObject(profileFileObject!, forKey: "photoUserColumn")
}
myUser.saveInBackgroundWithBlock({ (success:Bool, error:NSError?) -> Void in
if(success)
{
print("User details are now updated")
}
})
}
This code its not working just for the cover Image.
Any ideas?
Here's a working example using fb sdk in swift. I posted this answer in the other question as well but because this answer came up first for me on google I thought it'll be nice to put it here as well.
I needed to get the cover photo of a page so in the graphPath I used page id. This parameter can be easily changed to fit users / events / etc...
let request = FBSDKGraphRequest(graphPath: "\\(page.id)?fields=cover", parameters: [
"access_token": "your_access_token"
], HTTPMethod: "GET")
request.startWithCompletionHandler({(connection , result , error) in
if ((error) != nil) {
print("Error in fetching cover photo for \\(page.id): \(error)", terminator: "")
}
else {
if let data = result["cover"] as? NSDictionary {
self.fetchImageFromUrl(data["source"] as! String, cb: {(image: UIImage) -> Void in
//do something with image
})
}
})
func fetchImageFromUrl(url: String, cb: (UIImage) -> Void) {
let urlObj = NSURL(string: url)!
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
let data = NSData(contentsOfURL: urlObj)
dispatch_async(dispatch_get_main_queue(), {
let image = UIImage(data: data!)!
cb(image)
});
}
}
P.S - I'm a newbie in swift / ios so this code might not be the best. Comments will be appreciated.
It can be useful.
let emailRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name, id,cover"], tokenString: result?.token.tokenString, version: nil, httpMethod: "GET")
_ = emailRequest?.start(completionHandler: { (nil, resultParameters, error) in
if(error == nil) {
if let cover = (params?["cover"] as? NSDictionary)["source"]{
var coverUrl = cover as? String
}
}
})
Any one please help me how to convert the FBSDKLoginManager code into swift programming Thanks in advance here i attached the code in Objective-C
- (IBAction)btnFacebookPressed:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorBrowser;
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
NSLog(#"result is:%#",result);
[self fetchUserInfo];
[login logOut]; // Only If you don't want to save the session for current app
}
}
}];
}
My view Controller Code Is:
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
let facebookReadPermissions = ["public_profile", "email", "user_friends"]
override func viewDidLoad() {
super.viewDidLoad()
self.performSegueWithIdentifier("showView", sender: self)
/*for view in self.fbLoginView.subviews as! [UIView]
{
if view.isKindOfClass(UIButton)
{
let customButton = view as! UIButton
//customButton.removeFromSuperview()
customButton.setTitle("LOGIN WITH FACEBOOK", forState: .Normal)
customButton.backgroundColor = UIColor(red: 72/255.0, green: 128/255.0, blue: 255/255.0, alpha: 1.0)
customButton.showsTouchWhenHighlighted = true
customButton.frame = CGRectMake(90, 15, 210, 16)
customButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Center
//customButton.willMoveToSuperview(fbLoginView)
}
if (view.isKindOfClass(UILabel))
{
var loginLabel = view as! UILabel;
loginLabel.text = "LOGIN WITH FACEBOOK"
//loginLabel.textColor = UIColor.blackColor()
//loginLabel.textAlignment = NSTextAlignment(rawValue : 50)
//loginLabel.frame = CGRectMake(50, 50, 265, 45)
loginLabel.removeFromSuperview()
}
}*/
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier == "showView")
{
var vc: ViewController1 = segue.destinationViewController as! ViewController1
}
}
// Facebook Delegate Methods
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
println("User Logged In")
if ((error) != nil)
{
// Process error
println(error.localizedDescription)
}
else if result.isCancelled {
// Handle cancellations
}
else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
println("Login complete.")
/*if result.grantedPermissions.contains("email")
{
// Do work
//self.performSegueWithIdentifier("showView", sender: self)
}*/
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
println("User Logged Out")
}
/*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("fetched user: \(result)")
let userName : NSString = result.valueForKey("name") as! NSString
println("User Name is: \(userName)")
let userEmail : NSString = result.valueForKey("email") as! NSString
println("User Email is: \(userEmail)")
}
})
}
*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func customButton(sender: AnyObject) {
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser
fbLoginManager.logInWithReadPermissions(self.facebookReadPermissions, handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.contains("email"))
{
self.fetchUserInfo()
fbLoginManager.logOut()
}
}
})
}
func fetchUserInfo(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
result.valueForKey("email") as! String
result.valueForKey("id") as! String
result.valueForKey("name") as! String
result.valueForKey("first_name") as! String
result.valueForKey("last_name") as! String
}
})
}
}
}
While i'm running my app. The custom button is not at all working the event is not occurring
This is swift version of your code
#IBAction func btnFBLoginPressed(sender: AnyObject) {
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
//fbLoginManager.loginBehavior = FBSDKLoginBehavior.Browser
fbLoginManager.logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.isCancelled) {
//Show Cancel alert
} else if(fbloginresult.grantedPermissions.contains("email")) {
self.returnUserData()
//fbLoginManager.logOut()
}
}
})
}
Update
func returnUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
result.valueForKey("email") as! String
result.valueForKey("id") as! String
result.valueForKey("name") as! String
result.valueForKey("first_name") as! String
result.valueForKey("last_name") as! String
}
})
}
}
for reference you can try this link click
let facebookReadPermissions = ["public_profile", "email", "user_friends"]
func loginToFacebookWithSuccess(successBlock: () -> (), andFailure failureBlock: (NSError?) -> ()) {
if FBSDKAccessToken.currentAccessToken() != nil {
//For debugging, when we want to ensure that facebook login always happens
//FBSDKLoginManager().logOut()
//Otherwise do:
return
}
FBSDKLoginManager().logInWithReadPermissions(self.facebookReadPermissions, handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if error != nil {
//According to Facebook:
//Errors will rarely occur in the typical login flow because the login dialog
//presented by Facebook via single sign on will guide the users to resolve any errors.
// Process error
FBSDKLoginManager().logOut()
failureBlock(error)
} else if result.isCancelled {
// Handle cancellations
FBSDKLoginManager().logOut()
failureBlock(nil)
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
var allPermsGranted = true
//result.grantedPermissions returns an array of _NSCFString pointers
let grantedPermissions = result.grantedPermissions.allObjects.map( {"\($0)"} )
for permission in self.facebookReadPermissions {
if !contains(grantedPermissions, permission) {
allPermsGranted = false
break
}
}
if allPermsGranted {
// Do work
let fbToken = result.token.tokenString
let fbUserID = result.token.userID
//Send fbToken and fbUserID to your web API for processing, or just hang on to that locally if needed
//self.post("myserver/myendpoint", parameters: ["token": fbToken, "userID": fbUserId]) {(error: NSError?) ->() in
// if error != nil {
// failureBlock(error)
// } else {
// successBlock(maybeSomeInfoHere?)
// }
//}
successBlock()
} else {
//The user did not grant all permissions requested
//Discover which permissions are granted
//and if you can live without the declined ones
failureBlock(nil)
}
}
})
}
So, I made application on iphone. I'm using login with facebook and currently upgrade my facebooksdk to lastest version. Some of my code happen to have an error. Below is mycode:
let request = FBRequest.requestForMe()
request.startWithCompletionHandler({ (connection, result, error) -> Void in
if error == nil {
if let userData = result as? NSDictionary {
let facebookId = userData["id"] as! String
self.user.name = userData["name"]as! String
// self._fbuser.location = userData["location"]["name"] as String
self.user.gender = userData["gender"] as! String
self.user.imgUrl = NSURL(string: NSString(format: "https://graph.facebook.com/%#/picture?type=large&return_ssl_resources=1", facebookId) as String)
self.user.isFacebookUser = true
}
} else {
if let userInfo = error.userInfo {
if let type: AnyObject = userInfo["error"] {
if let msg = type["type"] as? String {
if msg == "OAuthException" { // Since the request failed, we can check if it was due to an invalid session
println("The facebook session was invalidated")
self.onLogout("")
return
}
}
}
}
println("Some other error: \(error)")
}
})
So how can I fix it ? what code that equal or similiar to FBRequest.requestme ?
Get user info in facebook sdk 4.x swift
#IBAction func btnFBLoginPressed(sender: AnyObject) {
var fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager .logInWithReadPermissions(["email"], handler: { (result, error) -> Void in
if (error == nil){
var fbloginresult : FBSDKLoginManagerLoginResult = result
if(fbloginresult.grantedPermissions.containsObject("email"))
{
self.getFBUserData()
fbLoginManager.logOut()
}
}
})
}
func getFBUserData(){
if((FBSDKAccessToken.currentAccessToken()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
if (error == nil){
println(result)
}
})
}
}
Output :
{
email = "ashishkakkad8#gmail.com";
"first_name" = Ashish;
id = 910855688971343;
"last_name" = Kakkad;
name = "Ashish Kakkad";
picture = {
data = {
"is_silhouette" = 0;
url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xpf1/v/t1.0-1/p200x200/10394859_900936369963275_5557870055628103117_n.jpg?oh=fefbfca1272966fc78286c36741f9ac6&oe=55C89225&__gda__=1438608579_9133f15e55b594f6ac2306d61fa6b6b3";
};
};
}