无法使用Facebook SDK登录

时间:2016-04-30 07:54:20

标签: ios swift facebook

我有一个主页,用户必须使用Facebook登录才能登录。但是当我点击Facebook按钮时 - 它会将我引导至safari页面,它会自动退出并返回主屏幕。

我尝试了所有教程并更改了代码。但对我来说没有任何作用。请帮帮我 - 为什么会这样?

import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class LoginViewController: UIViewController, UIAlertViewDelegate, GIDSignInDelegate, GIDSignInUIDelegate
{

    @IBOutlet weak var UsernameEmailTextField: UITextField?  // init username/email text field
    @IBOutlet weak var PasswordTextField: UITextField? // init password text field
    @IBOutlet var FbLoginButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationController?.navigationBar.barTintColor = UIColor.redColor()
        self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()

        if (FBSDKAccessToken.currentAccessToken() != nil) {
            // User is already logged in, do work such as go to next view controller.
            print("User Already Logged In")
        } else {
            print("User Not Logged In")
        }

        let dismiss: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(LoginViewController.DismissKeyboard))
        view.addGestureRecognizer(dismiss)
    }

    //keyboard dismiss function for input's
    func DismissKeyboard() {
        view.endEditing(true)
    }

    //facebook sign in
    @IBAction func FbLoginButtonTapped(sender: AnyObject) {
        let facebookLogin = FBSDKLoginManager()
        facebookLogin.logInWithReadPermissions(["email","public_profile","user_location"], fromViewController:self, handler:{(facebookResult, facebookError) -> Void in

                if facebookError != nil {
                    print("Facebook login failed. Error \(facebookError)")
                } else if facebookResult.isCancelled {
                    print("Facebook login was cancelled.")
                } else {
                    if((FBSDKAccessToken.currentAccessToken()) != nil) {
                        FBSDKGraphRequest(graphPath: "me",
                            parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email, user_location"]).startWithCompletionHandler({
                                (connection, result, error) -> Void in

                                if (error != nil) {
                                    print(error)
                                } else {
                                    let Email = result.valueForKey("email") as! String
                                    let IdasPassword = result.valueForKey("id") as! String
                                    self.MakeLogin(Email, SocialPassword: IdasPassword)
                                }
                            })
                    }

                }
        })

    }

    func MakeLogin(SocialEmail: String, SocialPassword: String) {
        //Adding Headers
        let headers = ["content-type": "application/x-www-form-urlencoded"]
        //Concatenating the email/username field with postdata
        let ConcatEmail = "email="+SocialEmail
        //Concatenating the password field with postdata
        let ConcatPassword = "&password="+SocialPassword
        //assigning concatenated values in postData
        let postData = NSMutableData(data: ConcatEmail.dataUsingEncoding(NSUTF8StringEncoding)!)
        postData.appendData(ConcatPassword.dataUsingEncoding(NSUTF8StringEncoding)!)
        //assigning request values
        let request = NSMutableURLRequest(URL: NSURL(string: "http login url”)!)
            //declaring POST Method
            request.HTTPMethod = "POST"
            //declaring header fields
            request.allHTTPHeaderFields = headers
            //Adding postData as HTTPBody
            request.HTTPBody = postData
        //declaring the session for url
        let session = NSURLSession.sharedSession()
        //assigning task to get response data
        let task = session.dataTaskWithRequest(request, completionHandler: { (ResposeData, response, error) -> Void in
            if(ResposeData != nil) {
                //declaring completion handler to check whether login.
                do {
                    if let jsonData = try NSJSONSerialization.JSONObjectWithData(ResposeData!, options: [] ) as? NSDictionary {
                        //assigning success jsonData
                        if let success = jsonData["success"] as? Int {
                            //If login success
                            if(success == 1) {
                                //assign access_token value from jsonData
                                let access_token = jsonData["token"]
                                // loading menu
                                dispatch_async(dispatch_get_main_queue()) {
                                    let appdelegate:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
                                    _ = appdelegate.window!.rootViewController
                                    let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                                    let mainViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("HomeViewController") as! HomeViewController
                                    let leftViewController = mainStoryBoard.instantiateViewControllerWithIdentifier("MenuViewController") as! MenuViewController
                                    let leftSideNav = UINavigationController(rootViewController: leftViewController)
                                    let centerNav = UINavigationController(rootViewController: mainViewController)
                                    let centerContainer:MMDrawerController = MMDrawerController(centerViewController: centerNav, leftDrawerViewController: leftSideNav)
                                    centerContainer.openDrawerGestureModeMask = MMOpenDrawerGestureMode.PanningCenterView;
                                    centerContainer.closeDrawerGestureModeMask = MMCloseDrawerGestureMode.PanningCenterView;
                                    NSUserDefaults.standardUserDefaults().setBool(true, forKey: "ISSOCIALLOGGEDIN")
                                    NSUserDefaults.standardUserDefaults().setValue(access_token, forKey: "access_token")
                                    NSUserDefaults.standardUserDefaults().synchronize()
                                    appdelegate.centerContainer = centerContainer
                                    appdelegate.window!.rootViewController = appdelegate.centerContainer
                                    appdelegate.window!.makeKeyAndVisible()
                                }

                                //dismissing the current view
                                self.dismissViewControllerAnimated(true, completion: nil)
                            } else {
                                let ServerMessage = jsonData["message"] as? String
                                print(ServerMessage)
                                dispatch_async(dispatch_get_main_queue(), {
                                    let alert = UIAlertController(title: "Error", message: ServerMessage, preferredStyle: UIAlertControllerStyle.Alert)
                                    // add an action (button)
                                    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                                    // show the alert
                                    self.presentViewController(alert, animated: true, completion: nil)
                                })
                            }
                        }
                    } else {
                        let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding)
                        // No error thrown, but not NSDictionary
                        print("Error could not parse JSON: \(jsonStr)")
                    }

                } catch let parseError {
                    print(parseError)
                    // Log the error thrown by `JSONObjectWithData`
                    let jsonStr = NSString(data: ResposeData!, encoding: NSUTF8StringEncoding)
                    print("Error could not parse JSON: '\(jsonStr)'")
                    dispatch_async(dispatch_get_main_queue(), {
                        let alert = UIAlertController(title: "Error", message: "No Data Received, Please contact Admin/Dev", preferredStyle: UIAlertControllerStyle.Alert)
                        // add an action (button)
                        alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                        // show the alert
                        self.presentViewController(alert, animated: true, completion: nil)
                    })
                }
            } else {
                print("Error: No Response Data")
                dispatch_async(dispatch_get_main_queue(), {
                    let alert = UIAlertController(title: "Invalid Username or Password", message: "No Response from server, You might be facing internet failure or try with different values", preferredStyle: UIAlertControllerStyle.Alert)
                    // add an action (button)
                    alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                    // show the alert
                    self.presentViewController(alert, animated: true, completion: nil)
                })
            }
        })
        task.resume()
    }
}

1 个答案:

答案 0 :(得分:0)

首先,我假设您的项目中有最新版本的Facebook SDK。首先,完成Facebook开发人员网站上提到的有关SDK安装的所有步骤,

  

This会帮助您,以防您无法将Objective-C代码转换为Swift。

继续前进,您可以在yourViewController中实现func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)中的功能,以了解用户按下登录按钮时发生的情况,如下所示:

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
        if (error != nil) {
            print(error.localizedDescription)
        } else if result.isCancelled {
            print("User Cancelled The Login")
        } else {
            if result.grantedPermissions.contains("email") {
                print("Got email access")
            }
        }
    }

只要您获得电子邮件访问权限,就可以调用其他功能来获取您要求的用户详细信息;那是怎么回事:

func graphRequestToReturnUserData(graphParameters: Dictionary<String, String>) {
        let graphRequest: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: graphParameters)
        graphRequest.startWithCompletionHandler({
            (connection, result, error) -> Void in
            if ((error) != nil) {
                print("Error: \(error.localizedDescription)")       //Error Handling
            } else {
                self.facebookD = result as! NSDictionary
            }
        })
    }

当SDK中已经存在所有内容时,创建自己的按钮然后查找详细信息并不是一个好方法。 除此之外,您还需要提及所需的权限。