iOS How to fetch user photo from Facebook use parse swift 4 - ios

I have issues with loading user photo from facebook.
I want to fetch facebook user photo to parse data base.
My code:
let permissions:[String] = ["public_profile", "email"]
PFFacebookUtils.logInInBackground(withReadPermissions: permissions) { (user, error) 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()
} else {
NSLog("User logged in through Facebook!")
}
}
func loadData(){
let fbRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
fbRequest?.start(completionHandler: { (FBSDKGraphRequestConnection, result, error) 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"
let URLRequest = NSURL(string: pictureURL)
let URLRequestNeeded = NSURLRequest(url: URLRequest! as URL)
NSURLConnection.sendAsynchronousRequest(URLRequestNeeded as URLRequest, queue: OperationQueue.main, completionHandler: { (response, data, error) in
if error == nil {
let picture = PFFile(data: data!)
PFUser.current()?.setObject(picture!, forKey: "profilePicture")
PFUser.current()?.saveInBackground()
}
else {
print("Error: \(String(describing: error?.localizedDescription))")
}
})
PFUser.current()!.setValue(name, forKey: "username")
PFUser.current()!.setValue(email, forKey: "email")
PFUser.current()!.saveInBackground()
}
}
})
}
But i all time i have error message, and in data base i have empty row.
How i can fix it?

After trying many methods, this is what works for me.
On AppDelegate, import Parse, ParseFacebookUtilsV4 and FBSDKCoreKit
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
PFFacebookUtils.initializeFacebook(applicationLaunchOptions: launchOptions)
FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
and add two methods
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(
app,
open: url as URL?,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
)
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(
application,
open: url as URL?,
sourceApplication: sourceApplication,
annotation: annotation)
}
And then, on login ViewController:
#IBAction func signInFacebook(_ sender: Any)
{
let permissions = ["public_profile", "email"]
PFFacebookUtils.logInInBackground(withReadPermissions: permissions) { (user : PFUser?, error: Error?) in
if(error != nil)
{
//Display an alert message
let myAlert = UIAlertController(title:"Alert", message:error?.localizedDescription, preferredStyle: UIAlertController.Style.alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertAction.Style.default, handler: nil)
myAlert.addAction(okAction)
self.present(myAlert, animated:true, completion:nil);
return
}
else
{
let query = PFQuery(className: "_User")
query.whereKey("email", equalTo: NSNull())
query.findObjectsInBackground (block: { (objects, error) -> Void in
if error == nil
{
// found related objects
for object in objects! {
//delete error user
print(object.value(forKey: "username")!)
object.deleteEventually()
}
}
else{
print(error!.localizedDescription)
}
}
)}
self.indicator.isHidden = false
self.indicator.startAnimating()
self.setUp.isHidden = false
if(FBSDKAccessToken.current() != nil) {
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email, first_name, last_name"]).start(completionHandler: { (connection, result, error) in
let resultDic = result as! [String: Any]
let nameFB = resultDic["name"] as! String
let emailFB = resultDic["email"] as! String
let idFB = resultDic["id"] as! String
let firstFB = resultDic["first_name"] as! String
let lastFB = resultDic["last_name"] as! String
// correct in case of double First or Last name
let firstFBNoSpaces = firstFB.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
let lastFBNoSpaces = lastFB.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
var userNameNew = firstFBNoSpaces + "_" + lastFBNoSpaces
userNameNew = userNameNew.lowercased()
// send data to server to related columns
let user = PFUser()
user.username = userNameNew.lowercased()
user.email = emailFB.lowercased()
user.password = idFB
user["fullname"] = nameFB.capitalized
UserDefaults.standard.set(user.username, forKey: "username")
// get Facebook profile picture
let userProfile = "https://graph.facebook.com/" + idFB + "/picture?type=large"
let profilePictureUrl = NSURL(string: userProfile)
let profilePictureData = NSData(contentsOf: profilePictureUrl! as URL)
if(profilePictureData != nil)
{
let avaFile = PFFile(data:profilePictureData! as Data)
user["ava"] = avaFile
}
// will try to login with facebook
user.signUpInBackground { (success, error) -> Void in
if success
{
// remember looged user
UserDefaults.standard.set(user.username, forKey: "username")
UserDefaults.standard.set(true, forKey: "byFacebook")
// call login func from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
self.setUp.isHidden = true
self.indicator.isHidden = true
self.indicator.stopAnimating()
}
else
{
let existing : String? = UserDefaults.standard.string(forKey: "username")
// user already exists in app database
PFUser.logInWithUsername(inBackground: existing!, password: user.password!){ (user, error) -> Void in
if error == nil
{
// remember user or save in App Memory did the user login or not
UserDefaults.standard.set(user!.username, forKey: "username")
UserDefaults.standard.set(true, forKey: "byFacebook")
// call login function from AppDelegate.swift class
let appDelegate : AppDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.login()
self.setUp.isHidden = true
self.indicator.isHidden = true
self.indicator.stopAnimating()
}
}
}
}
})
}
else
{
self.setUp.isHidden = true
self.indicator.isHidden = true
self.indicator.stopAnimating()
}
}
}

you can try
#IBAction func loginFacebookAction(sender: AnyObject) {//action of the custom button in the storyboard
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["email"], 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"))
{
self.getFBUserData()
}
}else {
print(error!.localizedDescription)
// self.view.showToast(withMessage: error!.localizedDescription)
}
}
}
func getFBUserData(){
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(result)
// if let data = result as? [String:Any],
// let user = Mapper<User>().map(
// JSONObject: data
// ){
// AppHelper.set(currentuser: user)
// }
}else {
// self.view.showToast(withMessage: error!.localizedDescription)
print(error!.localizedDescription)
}
})
}
}

Related

how to grab the image from FacebookLogin

How do I print out the image from
print((result! as AnyObject).value(forKey: "picture.data.url") as? Any)
I know that the following prints out the data and url but I just need the URL section.
print((result! as AnyObject).value(forKey: "picture") as? Any)
any advise?
I am using FacebookLogin SDK
NOTE: You can create the image URL on your own if you have the userId,
let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
Here is how you can get id,name,email and profile picture url from facebook login. I use this code in my app and it works.
func fetchFacebookFields() {
LoginManager().logIn(permissions: ["email","public_profile"], from: nil) {
(result, error) -> Void in
if let error = error {
print(error.localizedDescription)
return
}
guard let result = result else { return }
if result.isCancelled { return }
else {
GraphRequest(graphPath: "me", parameters: ["fields" : "first_name, last_name, email"]).start() {
(connection, result, error) in
if let error = error {
print(error.localizedDescription)
return
}
if
let fields = result as? [String:Any],
let userID = fields["id"] as? String,
let firstName = fields["first_name"] as? String,
let lastName = fields["last_name"] as? String,
let email = fields["email"] as? String
{
let facebookProfileUrl = "http://graph.facebook.com/\(userID)/picture?type=large"
print("firstName -> \(firstName)")
print("lastName -> \(lastName)")
print("email -> \(email)")
print("facebookProfileUrl -> \(facebookProfileUrl)")
APPDELEGATEOBJ.makeRootVC(vcName : "MainTabBarVC")
}
}
}
}
}

Application is crashing on facebook in apple review

We were unable to review your app as it crashed on launch. We have attached detailed crash logs to help troubleshoot this issue.
Specifically, your app still crashed on launch after the user logged in with facebook.
I m unable to catch the crash or any error.
Here's the code for where I think it's crashing (run right after users log in with Facebook)
#IBAction func Btn_facebook(_ sender: Any)
{
getFacebookUserInfo()
}
func getFacebookUserInfo()
{
let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.logIn(withReadPermissions: ["public_profile","email"], 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"))
{
self.getFBUserData()
self.fbtoken = result!.token.tokenString
}
}
}
}
func getFBUserData()
{
if((FBSDKAccessToken.current()) != nil)
{
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, email, picture"]).start(completionHandler: { (connection, result, error) -> Void in
if result != nil {
guard FBSDKAccessToken.current().tokenString != nil else {
debugPrint("failed to get access token")
return
}
guard let result = result as? NSDictionary, let user_id_fb = result["id"] as? String else {
print("error")
return
}
}
if (error == nil)
{
let fbDetails = result as! NSDictionary
let field = result! as? [String:Any]
if let imageURL = ((field!["picture"] as? [String: Any])?["data"] as? [String: Any])?["url"] as? String {
print(imageURL)
let url = URL(string: imageURL)
print(url!)
self.fburl = imageURL
print(self.fburl!)
}
let checkemail = fbDetails["email"] as? String
if(checkemail != nil)
{
print(" check email not nil ", checkemail as Any)
self.fbemail = (fbDetails["email"] as? String)
self.fbid = (fbDetails["id"] as? String)
self.fbname = (fbDetails["name"] as? String)
self.GandfLogin(name: self.fbname!, email: self.fbemail!, post_image: (self.fburl!))
}
else
{
print(" check email nil ",checkemail ?? String.self)
self.fbid = (fbDetails["id"] as? String)
self.fbname = (fbDetails["name"] as? String)
self.GandfLogin(name: self.fbname!, email: self.fbid!, post_image: (self.fburl!))
}
}
else
{
print(error?.localizedDescription ?? "Not found")
}
})
}
}
Use soft unwraps instead of ! in most cases
Because it can lead to crashes if Facebook does not send data which you a looking for back
Do it this way:
guard let fbDetails = result as NSDictionary else {
//Show error to user or something else
return
}

How to get the cover photo from Facebook + Swift + Parse

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
}
}
})

Can't create new user using Parse 1.7.2 and Facebook SDK 4.1 in Xcode using Swift

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.

Get Facebook Profile picture at Sign-up for Parse backend (Swift)

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()
}
}
}
}

Resources