I want to fetch the username of the user in username field into the parse.
I am using loginWithFacebook(withcompletionHandler) and fetchUserInforFromFacebook(withcompletionHandler) to fetch userinfo but I have a problem: These methods create an own object and store in parse username field, but I want to get the user username.
func loginWithFacebook(withcompletionHandler: (success:Bool) ->()){
var permissions : Array = [ "user_location","public_profile"]
PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, {
(user: PFUser?, error: NSError?) -> Void in
if let user = user {
if user.isNew {
self.fetchUserInforFromFacebook(withcompletionHandler)
println("User SIGNED UP and logged in through Facebook!")
}
withcompletionHandler(success: true)
println("User logged in through Facebook!")
} else {
println("Uh oh. The user cancelled the FACEBOOK LOGIN.")
self.showErrorMessage(error!)
withcompletionHandler(success: false)
}
})
}
func fetchUserInforFromFacebook(withcompletionHandler: (success:Bool) ->()){
if ((FBSDKAccessToken.currentAccessToken()) != nil){
var request = FBSDKGraphRequest(graphPath:"me", parameters:nil)
request.startWithCompletionHandler({connection, result, error in
if error == nil {
//FACEBOOK DATA IN DICTIONARY
var userData = result as NSDictionary
var currentUser : PFUser = PFUser.currentUser()
currentUser.setObject(userData.objectForKey("id") as String, forKey: "faceBookID")
currentUser.setObject( userData.objectForKey("name") as String, forKey: "fullName")
currentUser.email = userData.objectForKey("email") as? String
currentUser.username = userData.objectForKey("email") as? String
var location = userData.objectForKey("location") as? NSDictionary
var locName = location?.objectForKey("name") as? String
if let loc = locName {
var fullNameArr = split(loc) {$0 == ","}
var city: String? = fullNameArr.count > 0 ? fullNameArr[0] : nil
var contry: String? = fullNameArr.count > 1 ? fullNameArr[1]: nil
currentUser.setObject(userData.objectForKey("country"), forKey: "countryName")
currentUser.setObject(userData.objectForKey("city"), forKey: "cityName")
}
currentUser.saveInBackground()
withcompletionHandler(success: true)
}else{
println("Error")
self.showErrorMessage(error)
withcompletionHandler(success: false)
}
})
}
}
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email", "user_friends"] , allowLoginUI: true, completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) -> Void in
if (error==nil)
{
FBRequest.requestForMe().startWithCompletionHandler({ (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if (error==nil)
{
// get All Facebook data from user
//http://graph.facebook.com/67563683055/picture?type=square
//NSLog("%#",result as! NSDictionary)
var bUserFacebookDict = result as! NSDictionary
bstrFirstName = bUserFacebookDict.objectForKey("first_name") as! String
bstrLastName = bUserFacebookDict.objectForKey("last_name") as! String
bstrUserName = bUserFacebookDict.objectForKey("name") as! String
}
else
{
//Utility.showErrorAlert(error.description)
}
})
}
})
Much easier approach to get the username:
Firstly you need to call the FBSession method to get basic profile info and ID of the user.
Secondly Once we get user FB ID, we can directly pass the FB ID in graph API: https://graph.facebook.com/?id=1008223822 aand get the username in the following json format:-
{
"id": "1008223822",
"first_name": "Dj\u00e9",
"gender": "male",
"last_name": "Destolicci",
"link": "https://www.facebook.com/dje.destolicci",
"locale": "fr_FR",
"name": "Dj\u00e9 Destolicci",
"username": "dje.destolicci"
}
Here is code:-
//first do simple login and authenticate user to get basic profile info and FB ID
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email", "user_friends"] , allowLoginUI: true, completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) -> Void in
if (error==nil)
{
FBRequest.requestForMe().startWithCompletionHandler({ (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if (error==nil)
{
var bUserFacebookDict = result as! NSDictionary
let FB_USER_ID = bUserFacebookDict["id"]! as! String
// now call FB graph API to to Get username of the user.
var graphProfileURL = NSURL(string: "https://graph.facebook.com/?id=\(FB_USER_ID)")
var request1: NSURLRequest = NSURLRequest(URL: graphProfileURL!)
var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
>=nil
var error: NSErrorPointer = nil
var dataVal: NSData = NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
var err: NSError
println(response)
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
println("Synchronous\(jsonResult)")
let FB_USER_NAME = jsonResult["username"]! as! String //finally you will get username
}
else
{
//Utility.showErrorAlert(error.description)
}
})
}
})
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"
}
}
Can't get the user's name or email when login with Facebook via Parse. I should have set everything else properly in the AppDelegate.
When I login with my email, my User class works, and can use data I registered with. When I try to login via Facebook, I only got the long alphanumerical string as username and stop. I'd like to retrive name, foto, birth and city.
In my User.swift file I'got this:
import Foundation
struct User
{
let username : String
let address : String
}
This is my login button:
#IBAction func facebookLoginAction(sender: UIButton)
{
PFFacebookUtils.logInInBackgroundWithReadPermissions(["public_profile", "user_about_me", "user_birthday"]) {
(user: PFUser?, error: NSError?) -> Void in
if let user = user
{
if user.isNew
{
println("User signed up and logged in through Facebook!")
}
else
{
println("User logged in through Facebook!")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
else
{
println("Uh oh. The user cancelled the Facebook login.")
}
}
}
tried this too, but doesn't work:
func getUserInfo() {
// if let session = PFFacebookUtils.session() {
if let session = PFFacebookUtils.facebookLoginManager() {
if session.isOpen {
println("session is open")
FBRequestConnection.startForMeWithCompletionHandler({ (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
//println("done me request")
if error != nil {
println("facebook me request - error is not nil :(")
} else {
println("facebook me request - error is nil :) ")
let urlUserImg = "http://graph.facebook.com/\(result.objectID)/picture?type=large"
let firstName = result.first_name
let lastName = result.last_name
}
})
}
} else {
//let user:PFUser = PFUser.currentUser()
//println("ohooo \(user)")
}
}
thanks in advance
This is working code I use to get Facebook information with Parse. The function is called after successful authentication with user.isNew. It can also be called even if the user isn't new to make sure you have the most up-to-date information when they log back in.
func loadFacebookData() {
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, name, id"])
graphRequest.startWithCompletionHandler { (connection, result, error) -> Void in
if error != nil {
let error = error!.userInfo["error"] as! String
}
else {
if let userName = result.valueForKey("name") as? String, email = result.valueForKey("email") as? String, id = result.valueForKey("id") as? String {
let pictureURL: NSURL = NSURL(string: "https://graph.facebook.com/\(id)/picture?type=large&return_ssl_resources=1")!
let user = PFUser.currentUser()!
let query = PFUser.query()
query!.whereKey("email", equalTo: email)
query!.getFirstObjectInBackgroundWithBlock({ (oldUser: PFObject?, error) -> Void in
if error != nil && oldUser != nil {
let error = error!.userInfo["error"] as! String
}
else {
self.setFacebookInfo(user, userEmail: email, userName: userName, pictureURL: pictureURL)
}
})
}
}
}
}
I've linked my app to both the Facebook SDK and Parse, but now I'm trying to integrate Facebook's login with Parse but keep running into issues. My current issue is that the app runs, but when I press the FBSDKLoginButton, it will go to safari and ask for permissions (as it should), but then when pressing okay, it simply returns to the app's login screen like nothing happened and does not perform the segue to the rest of the app. I also checked Parse and it did not create a new PFUser. I will post the code I think may be relevant from my LoginViewController below (that means the code will be missing sections like my viewDidLoad for it has nothing in it that affects the login process):
import UIKit
import Parse
import FBSDKCoreKit
import FBSDKLoginKit
protocol LoginViewControllerDelegate {
func onRegister(loginViewController : LoginViewController)
func onFacebookLogin(loginViewController : LoginViewController)
func onLogin(loginViewController : LoginViewController)
}
class LoginViewController: UIViewController {
#IBAction func onFacebookLogin(sender: AnyObject?) {
// Set permissions required from the facebook user account
let permissions = [ "user_about_me", "user_relationships", "user_location", "user_birthday", "public_profile", "user_friends", "user_email", "user_gender"]
// Login PFUser using Facebook
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.loadData()
self.performSegueWithIdentifier("loggedIn", sender: self)
} else {
println("User logged in through Facebook!")
self.performSegueWithIdentifier("loggedIn", sender: self)
}
if self.delegate != nil {
self.delegate!.onFacebookLogin(self)
}
} else {
println("Uh oh. The user cancelled the Facebook login.")
}
})
}
func loadData(){
let request:FBSDKGraphRequest = FBSDKGraphRequest()
request.startWithCompletionHandler { (connection:FBSDKGraphRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if error == nil{
if let dict = result as? Dictionary<String, AnyObject>{
let name:String = dict["first_name"] as AnyObject? as! String
let facebookID:String = dict["id"] as AnyObject? as! String
let email:String = dict["email"] as AnyObject? as! String
let birthday:String = dict["birthday"] as AnyObject? as! String
let gender:String = dict["gender"] as AnyObject? as! String
let hostCount:Int = 0
let attendCount:Int = 0
let pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"
var URLRequest = NSURL(string: pictureURL)
var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
if error == nil {
var picture = PFFile(data: data)
PFUser.currentUser()!.setObject(picture, forKey: "profilePicture")
PFUser.currentUser()!.saveInBackground()
}
else {
println("Error: \(error.localizedDescription)")
}
})
PFUser.currentUser()!.setValue(name, forKey: "name")
PFUser.currentUser()!.setValue(email, forKey: "email")
PFUser.currentUser()!.setValue(birthday, forKey: "birthday")
PFUser.currentUser()!.setValue(gender, forKey: "gender")
PFUser.currentUser()!.setValue(hostCount, forKey: "hostCount")
PFUser.currentUser()!.saveInBackground()
}
}
}
}
}
I use this solution, hope it helps you. If you have a question on it, I can answer :)
func notLoggedIn() -> Bool {
let user = PFUser.currentUser()
// here I assume that a user must be linked to Facebook
return user == nil || !PFFacebookUtils.isLinkedWithUser(user)
}
func loggedIn() -> Bool {
return !notLoggedIn()
}
func performNewUser(){
if notLoggedIn() {
return
}
let user = PFUser.currentUser() // Won't be nil because is logged in
// RETURN IF WE ALREADY HAVE A USERNAME AND FBID (note that we check the fbId because Parse automatically fills in the username with random numbers)
if let fbId = user["fbId"] as? String {
if !fbId.isEmpty {
displayAlert("Erreur", error: "Il existe déjà un utilisateur avec ce compte Facebook")
println("we already have a username and fbId -> return")
return
}
}
// REQUEST TO FACEBOOK
println("performing request to FB for username and IDF...")
if let session = PFFacebookUtils.session() {
if session.isOpen {
println("session is open")
FBRequestConnection.startForMeWithCompletionHandler({ (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
println("done me request")
if error != nil {
println("facebook me request - error is not nil :(")
} else {
println("facebook me request - error is nil :)")
println(result)
println(result.name)
println(result.objectID)
// Save to Parse:
var FBSession = PFFacebookUtils.session()
var currentUser = PFUser.currentUser()
var userToSave = PFObject(className: "Utilisateurs")
var accessToken = FBSession.accessTokenData.accessToken
let url = NSURL(string: "https://graph.facebook.com/me/picture?type=large&return_ssl_resources=1&access_token="+accessToken)
let urlRequest = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(urlRequest, queue: NSOperationQueue.mainQueue(), completionHandler: {
response, data, error in
let image = UIImage(data: data)
currentUser["image"] = data
currentUser.save()
self.performSegueWithIdentifier("connexionApplicationInscriptionViaFacebook", sender: self)
})
let firstName = result["first_name"] as String
let status = "Client"
currentUser.username = result["last_name"] as String
currentUser.email = result.email
userToSave.setObject(currentUser.username, forKey: "nom")
userToSave.setObject(currentUser.username, forKey: "username")
userToSave.setObject(firstName, forKey: "prenom")
userToSave.setObject(status, forKey: "status")
currentUser.setValue(self.tfPrenom.text, forKey: "name")
currentUser.setValue(result.objectID, forKey: "fbId")
currentUser.saveEventually() // Always use saveEventually if you want to be sure that the save will succeed
}
})
}
}
}
After updating to Parse 1.7.4 and deleting the old PFFacebookUtils Framework (keeping the PFFacebookUtilsV4) seems to have fixed the problem by itself! I hope this answer helps other people with the same problem.
I'm creating an application with Parse as backend service. My users should be able to sign-up and login via Facebook.
I did this in the following (works absolutely fine).
#IBAction func registerWithFacebook(sender: UIButton) {
let permissions:[String] = ["user_about_me","user_relationships", "public_profile"]
PFFacebookUtils.logInWithPermissions(permissions, {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
NSLog("Uh oh. The user cancelled the Facebook login.")
} else if user.isNew {
NSLog("User signed up and logged in through Facebook!")
self.loadData()
self.performSegueWithIdentifier("initialToMain", sender: self)
} else {
NSLog("User logged in through Facebook!")
self.performSegueWithIdentifier("initialToMain", sender: self)
}
})
}
func loadData(){
let request:FBRequest = FBRequest.requestForMe()
request.startWithCompletionHandler { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if error == nil{
if let dict = result as? Dictionary<String, AnyObject>{
let name:String = dict["name"] as AnyObject? as String
let email:String = dict["email"] as AnyObject? as String
println(name)
PFUser.currentUser().setValue(name, forKey: "username")
PFUser.currentUser().setValue(email, forKey: "email")
PFUser.currentUser().save()
}
}
}
}
Unfortunately I wasn't able to get the profile picture from the user who's signing up. How can I do that?
The picture is publicly available via the user id at the following url:
https://graph.facebook.com/USER_ID/picture
You can also request various sizes:
https://graph.facebook.com/USER_ID/picture?width=300&height=300
Here's the working solution:
func loadData(){
let request:FBRequest = FBRequest.requestForMe()
request.startWithCompletionHandler { (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
if error == nil{
if let dict = result as? Dictionary<String, AnyObject>{
let name:String = dict["name"] as AnyObject? as String
let facebookID:String = dict["id"] as AnyObject? as String
let email:String = dict["email"] as AnyObject? as String
let pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"
var URLRequest = NSURL(string: pictureURL)
var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
if error == nil {
var picture = PFFile(data: data)
PFUser.currentUser().setObject(picture, forKey: "profilePicture")
PFUser.currentUser().saveInBackground()
}
else {
println("Error: \(error.localizedDescription)")
}
})
PFUser.currentUser().setValue(name, forKey: "username")
PFUser.currentUser().setValue(email, forKey: "email")
PFUser.currentUser().saveInBackground()
}
}
}
}