使用Facebook登录和解析显示Facebook用户名而不是用户令牌

时间:2016-04-08 03:52:39

标签: ios swift facebook facebook-graph-api parse-server

在我的应用中,用户可以通过创建用户名和密码或使用Facebook登录来登录/注册。 Parse存储用户名和密码。它对Facebook也是如此,但它存储用户令牌(我认为)而不是用户名。然后我在表视图中显示用户名,但Facebook用户显示为用户令牌,如:Afjkd233edJ而不是他们的用户名。我也使用Facebook图形api,它将名称存储在我的类User中。然而,我无法发布该名称而不是令牌。这是我在我的View控制器中使用的代码,它处理登录和注册,然后下面是我的表视图控制器,它显示用户以及他们关注或不关注的人。编辑:我忘了提到我正在使用解析服务器,并已将其迁移到Heroku并使用mongoldb dyno。

的viewController

import UIKit
import Parse
import ParseFacebookUtilsV4

class ViewController: UIViewController {

 var signupActive = true

@IBOutlet weak var username: UITextField!

@IBOutlet weak var password: UITextField!


@IBOutlet weak var signupButton: UIButton!

@IBOutlet weak var registeredText: UILabel!


@IBOutlet weak var loginButton: UIButton!


var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()

func displayAlert(title: String, message: String) {

    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    alert.addAction((UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in

        self.dismissViewControllerAnimated(true, completion: nil)

    })))

    self.presentViewController(alert, animated: true, completion: nil)


}










@IBAction func signUp(sender: AnyObject) {

    if username.text == "" || password.text == "" {

        displayAlert("Error in form", message: "Please enter a username and password")

    } else {

        activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
        activityIndicator.center = self.view.center
        activityIndicator.hidesWhenStopped = true
        activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
        view.addSubview(activityIndicator)
        activityIndicator.startAnimating()
        UIApplication.sharedApplication().beginIgnoringInteractionEvents()

        var errorMessage = "Please try again later"

        if signupActive == true {

            let user = PFUser()
            user.username = username.text
            user.password = password.text



            user.signUpInBackgroundWithBlock({ (success, error) -> Void in

                self.activityIndicator.stopAnimating()
                UIApplication.sharedApplication().endIgnoringInteractionEvents()

                if error == nil {

                    // Signup successful

                    //self.performSegueWithIdentifier("login", sender: self)

                    let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

                    var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
                    appDelegate.window?.rootViewController = initialViewController
                    appDelegate.window?.makeKeyAndVisible()


                } else {

                    if let errorString = error!.userInfo["error"] as? String {

                        errorMessage = errorString

                    }

                    self.displayAlert("Failed SignUp", message: errorMessage)

                }

            })

        } else {

            PFUser.logInWithUsernameInBackground(username.text!, password: password.text!, block: { (user, error) -> Void in

                self.activityIndicator.stopAnimating()
                UIApplication.sharedApplication().endIgnoringInteractionEvents()

                if user != nil {

                    // Logged In!

                    //self.performSegueWithIdentifier("login", sender: self)

                    let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

                    var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
                    appDelegate.window?.rootViewController = initialViewController
                    appDelegate.window?.makeKeyAndVisible()


                } else {

                    if let errorString = error!.userInfo["error"] as? String {

                        errorMessage = errorString

                    }

                    self.displayAlert("Failed Login", message: errorMessage)

                }

            })

        }

    }






}

@IBAction func logIn(sender: AnyObject) {


    if signupActive == true {

        signupButton.setTitle("Log In", forState: UIControlState.Normal)

        registeredText.text = "Not registered?"

        loginButton.setTitle("Sign Up", forState: UIControlState.Normal)

        signupActive = false

    } else {

        signupButton.setTitle("Sign Up", forState: UIControlState.Normal)

        registeredText.text = "Already registered?"

        loginButton.setTitle("Login", forState: UIControlState.Normal)

        signupActive = true

    }

}


@IBAction func faceBookLogIn(sender: AnyObject) {



    let permissions = ["public_profile"]






    PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, block: {

        (user: PFUser?, error: NSError?) -> Void in

        if let error = error {

            print(error)

        } else {





            let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, gender"])
            graphRequest.startWithCompletionHandler( {

                (connection, result, error) -> Void in

                if error != nil {

                    print(error)

                } else if let result = result {


                    PFUser.currentUser()?["name"] = result["name"]!

                    PFUser.currentUser()?.saveInBackground()

                    let userId = result["id"]! as! String



                }

            })







            if let user = user {

                //self.performSegueWithIdentifier("login", sender: self)

                let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

                var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
                appDelegate.window?.rootViewController = initialViewController
                appDelegate.window?.makeKeyAndVisible()



            }



        }



    })



}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.





}

override func viewDidAppear(animated: Bool) {


    if let username = PFUser.currentUser()?.username {

        let appDelegate = UIApplication.sharedApplication().delegate! as! AppDelegate

        var initialViewController = self.storyboard!.instantiateViewControllerWithIdentifier("myTabbarControllerID") as! UIViewController
        appDelegate.window?.rootViewController = initialViewController
        appDelegate.window?.makeKeyAndVisible()


    }

}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


 }

TABELVIEW

import UIKit
import Parse

class TableViewController: UITableViewController {

var usernames = [""]
var userids = [""]
var isFollowing = ["":false]

var refresher: UIRefreshControl!

func refresh() {

    var query = PFUser.query()

    query?.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

        if let users = objects {

            self.usernames.removeAll(keepCapacity: true)
            self.userids.removeAll(keepCapacity: true)
            self.isFollowing.removeAll(keepCapacity: true)

            for object in users {

                if let user = object as? PFUser {

                    if user.objectId! != PFUser.currentUser()?.objectId {

                        self.usernames.append(user.username!)
                        self.userids.append(user.objectId!)

                        var query = PFQuery(className: "followers")

                        query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
                        query.whereKey("following", equalTo: user.objectId!)

                        query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

                            if let objects = objects {

                                if objects.count > 0 {

                                    self.isFollowing[user.objectId!] = true

                                } else {

                                    self.isFollowing[user.objectId!] = false

                                }
                            }

                            if self.isFollowing.count == self.usernames.count {

                                self.tableView.reloadData()

                                self.refresher.endRefreshing()

                            }


                        })



                    }
                }

            }



        }



    })





}

override func viewDidLoad() {
    super.viewDidLoad()

    refresher = UIRefreshControl()

    refresher.attributedTitle = NSAttributedString(string: "Pull to refresh")

    refresher.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)

    self.tableView.addSubview(refresher)

    refresh()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return usernames.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell

    cell.textLabel?.text = usernames[indexPath.row]

    let followedObjectId = userids[indexPath.row]

    if isFollowing[followedObjectId] == true {

        cell.accessoryType = UITableViewCellAccessoryType.Checkmark

    }


    return cell
}


override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    var cell:UITableViewCell = tableView.cellForRowAtIndexPath(indexPath)!

    let followedObjectId = userids[indexPath.row]

    if isFollowing[followedObjectId] == false {

        isFollowing[followedObjectId] = true

        cell.accessoryType = UITableViewCellAccessoryType.Checkmark

        var following = PFObject(className: "followers")
        following["following"] = userids[indexPath.row]
        following["follower"] = PFUser.currentUser()?.objectId

        following.saveInBackground()

    } else {

        isFollowing[followedObjectId] = false

        cell.accessoryType = UITableViewCellAccessoryType.None

        var query = PFQuery(className: "followers")

        query.whereKey("follower", equalTo: PFUser.currentUser()!.objectId!)
        query.whereKey("following", equalTo: userids[indexPath.row])

        query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in

            if let objects = objects {

                for object in objects {

                    object.deleteInBackground()

                }
            }


        })



    }

}
}

0 个答案:

没有答案