Не удалось войти на Facebook в iOS swift 4 - PullRequest
0 голосов
/ 18 апреля 2019

Я реализовал вход на Facebook в приложение iOS, но получаю эту ошибку:

enter image description here

Я нашел здесь пару решений:

1) используйте кнопку facebook по умолчанию.

2) предоставил контактный адрес электронной почты в консоли разработчика.

3) сделал приложение живым в консоли разработчика.

В режиме разработки он работает нормально, но эта проблема начинает возникать после того, как я опубликовал приложение в магазине приложений.

Я не знаю, что могло быть причиной этого. Может кто-нибудь мне помочь?

EDIT

plist файл Код: -

enter image description here

КОД

Для создания кнопки: -

if FBSDKAccessToken.current() != nil
        {
            let manager = FBSDKLoginManager()
            manager.logOut()
        }

let loginButton = FBSDKLoginButton()
    // Optional: Place the button in the center of your view.
    loginButton.delegate = self
    loginButton.frame = CGRect(x: (self.view.frame.size.width / 2) - (loginButton.frame.size.width / 2), y: self.view_facebook.frame.origin.y, width: loginButton.frame.size.width, height: loginButton.frame.size.height + 12)
    loginButton.readPermissions = ["public_profile", "email"]
    self.view.addSubview(loginButton)

Facebook Логин Код: -

extension LogInAndSignUpViewController : FBSDKLoginButtonDelegate
{
    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {

        if error != nil {

        }else if result.isCancelled {
            print("cancel")
        }else {
            //  self.fbRsponseLable.text = "User  login Successfully"

            print(result!)
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            if fbloginresult.grantedPermissions != nil {
                if(fbloginresult.grantedPermissions.contains("email"))
                {
                    self.serviceCalledForFetchUserInfoFromFacebook()

                }
                else
                {
                    self.serviceCalledForFetchUserInfoFromFacebook()
                }
            }
        }

    }

    func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        print("Did logout via LoginButton")
    }
}

    func serviceCalledForFetchUserInfoFromFacebook()
        {
            if((FBSDKAccessToken.current()) != nil)
            {
                FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email,name"]).start(completionHandler: { (connection, result, error) -> Void in
                    if (error == nil)
                    {
                        print(result!)
                        let dictName : NSDictionary = (result as? NSDictionary)!
                        if let name = dictName.value(forKey: "name")
                        {
                            print(name)
                            self.F_name = name as! String
                        }

                        if let id = dictName.value(forKey: "id")
                        {
                            print(id)
                            self.F_id = id as! String
                        }

                        if let email = dictName.value(forKey: "email")
                        {
                            print(email)
                            self.F_email = email as! String
                        }
                    }
                    else
                    {
                        print(error!)
                    }
                })
            }
        }

КОД ДЕЛЕГАТА ПРИЛОЖЕНИЯ

func applicationWillResignActive(_ application: UIApplication) {
        FBSDKAppEvents.activateApp()
    }

    func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)

    }

    func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {


    return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication:  options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String, annotation:  options[UIApplication.OpenURLOptionsKey.annotation] as? String)

    }

Ответы [ 2 ]

0 голосов
/ 18 апреля 2019
func makeLoginUsingFb() {
        let loginManager = LoginManager()
        loginManager.logIn(readPermissions: [.publicProfile,.email], viewController: self) { (response) in
            switch response {
            case .failed(let err):
                print(err.localizedDescription)
            case .cancelled:
                print("User Cancelled Login")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                self.getDataFromFB(accessToken: accessToken)
                print("Logged in!")
                print(grantedPermissions)
                print(declinedPermissions)
                print(accessToken)
            }
        }
    }

    func getDataFromFB(accessToken: AccessToken?) {
        let connection = GraphRequestConnection()
        connection.add(GraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email, first_name, last_name"], accessToken: accessToken, httpMethod: .GET, apiVersion: .defaultVersion)) { httpResponse, result in
            switch result {
            case .success(let response):


                let response = response.dictionaryValue
                let jResponse = JSON(response!).dictionaryValue
                let fName = jResponse["first_name"]?.stringValue
                let lName = jResponse["last_name"]?.stringValue
                let id = jResponse["id"]?.stringValue
                let email = jResponse["email"]?.stringValue

                //==========Save Data To Server And then goto your next HOME ViewController==========

            case .failed(let error):
                print("Graph Request Failed: \(error)")
            }
        }
        connection.start()
    }

Делегат приложения:

import FacebookCore

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)

        return true
    }

   func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return SDKApplicationDelegate.shared.application(app, open: url, options: options)
    }
0 голосов
/ 18 апреля 2019

Реализовали ли вы метод в AppDelegate, касающийся схемы URL?

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {

        if let appId = FBSDKSettings.appID() { 
            if url.scheme != nil && url.scheme!.hasPrefix("fb\(appId)") && url.host ==  "authorize" {
                //return FBSDKApplicationDelegate.shared.application(app, open: url, options: options)
                return FBSDKApplicationDelegate.sharedInstance()?.application(app, open: url, options: options) ?? false
            }
        }
        return false
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...