结合mysql和Facebook的最佳方式注册/进入

时间:2016-02-28 19:33:31

标签: swift facebook

如何注册我的iOS应用有两种方法。第一个选项是使用mysql/php(用户键入电子邮件,用户名,密码,我将其存储在mysql数据库中。 第二个选项是使用Facebook登录,这里开始我的问题,因为我需要有userId,我可以从Facebook获得,但我的MySQL数据库中也有一个Id(每个用户都应该拥有自己的ID)。 所以我的问题是你建议我做什么。我试图将Facebook用户存储到mysql,所以他收到了他的唯一身份证。(但后来有像密码这样的空列,因为Facebook用户不需要密码)。

这是我的Facebook登录(当我使用我的Facebook帐户登录时,这是可以的,因为我的Facebook ID非常高):

@IBAction func btnFBLoginPressed(sender: AnyObject) {

   loadingIndicator.startAnimating()

    FBSDKLoginManager().logInWithReadPermissions(["public_profile", "email"],
                                                 fromViewController:self,
        handler: { (result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in

            if (error == nil){

                self.getFBUserData()

                self.loadingIndicator.stopAnimating()
            }else{

                self.loadingIndicator.stopAnimating()
                let myAlert = UIAlertController(title: "Alert!", message: error.localizedDescription, preferredStyle: .Alert)
                let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
                myAlert.addAction(okAction)
                self.presentViewController(myAlert, animated: true, completion: nil)

                print(error.localizedDescription)
                print("error")
                return
            }

    })
}

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){
                print(result)

                 print(result["name"])
                 print(result["id"])
                                 NSUserDefaults.standardUserDefaults().setObject(result["name"]!, forKey: "username")
                NSUserDefaults.standardUserDefaults().setObject(result["id"]!, forKey: "userId")
                NSUserDefaults.standardUserDefaults().synchronize()

                let firstPage = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController")as! ViewController
                let appDelegate = UIApplication.sharedApplication().delegate
                appDelegate?.window??.rootViewController = firstPage                                                                           

}else{

                let myAlert = UIAlertController(title: "Alert!", message: error?.localizedDescription, preferredStyle: .Alert)
                let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
                myAlert.addAction(okAction)
                self.presentViewController(myAlert, animated: true, completion: nil)

                print(error.localizedDescription)
                print("error")
                return


            }
        })
    }
}

这是MySQL登录:

 @IBAction func loginTapped(sender: AnyObject) {

let userEmail = emailTextField.text
let userPassword = passwordTextField.text



    if (userEmail!.isEmpty||userPassword!.isEmpty){

        let myAlert = UIAlertController(title: "Alert", message: "All fields must be filled out", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
        myAlert.addAction(okAction)
        self.presentViewController(myAlert, animated: true, completion: nil)
        return
    }
       self.loadingIndicator.startAnimating()

   let myUrl = NSURL(string: "http://localhost/~myPc/userSignIn.php")!
   let request = NSMutableURLRequest(URL: myUrl)
   request.HTTPMethod = "POST"


    let postString = "userEmail=\(userEmail!)&userPassword=\(userPassword!)"

    request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)


    NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (data:NSData?, response:NSURLResponse?, error:NSError?) in

        dispatch_async(dispatch_get_main_queue()){

            if (error != nil){

                let myAlert = UIAlertController(title: "Alert", message: error?.localizedDescription, preferredStyle: .Alert)
                let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
                myAlert.addAction(okAction)
                self.presentViewController(myAlert, animated: true, completion: nil)

                self.loadingIndicator.stopAnimating()

                return
            }

            do {
                let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary

                if let parseJson = json {

                    let userId = parseJson["userId"] as? String
                      if userId != nil{


                        NSUserDefaults.standardUserDefaults().setObject(parseJson["username"], forKey: "username")

                        NSUserDefaults.standardUserDefaults().setObject(parseJson["userId"], forKey: "userId")
                        NSUserDefaults.standardUserDefaults().synchronize()


                     let firstPage = self.storyboard?.instantiateViewControllerWithIdentifier("ViewController")as! ViewController
                     let appDelegate = UIApplication.sharedApplication().delegate

                     appDelegate?.window??.rootViewController = firstPage

                    }else{
                        let userMessage = parseJson["message"] as? String
                        let myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: .Alert)
                        let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
                        myAlert.addAction(okAction)
                        self.presentViewController(myAlert, animated: true, completion: nil)

                        self.loadingIndicator.stopAnimating()

                    }

                    self.loadingIndicator.stopAnimating()

                }

            } catch {
                print(error)

            }           
        }
    }).resume()

    }

0 个答案:

没有答案