Вход в Facebook с использованием социальных сетей и учетных записей в iOS swift

Я пытаюсь войти в систему с помощью социальных сетей и учетных записей.

Вход в Facebook через социальную структуру в ios
Следуйте этому вопросу и преобразовать код в быстрый, но получить ошибку

Операция не может быть завершена. (ошибка 6 com.apple.accounts.)

Найдите много вопросов о переполнении стека в задаче c, но не в Swift.

Мой код:

import Social
import Accounts

class ViewController: UIViewController {

    var facebookAccount : ACAccount!       
    let appIdKey : NSString = "*************"
    var facebookAccount : ACAccount!
    var isFacebookAvailable = Int()
    var globalMailId = NSString()
    var fbName = NSString()

    override func viewDidLoad() {
        super.viewDidLoad()

        self.accountStore = ACAccountStore()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func fbLogin(sender: UIButton) {

        let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)

        var dictFB = [String : AnyObject]()
        dictFB[ACFacebookAppIdKey] = "*************"
        dictFB[ACFacebookPermissionsKey] = ["publish_profile","email","user_friends"]
        dictFB[ACFacebookAudienceKey] = ACFacebookAudienceFriends

        self.accountStore.requestAccessToAccountsWithType(accountType, options: dictFB) { (granted : Bool, error : NSError?) -> Void in
            if granted {
                let accounts : NSArray = self.accountStore.accountsWithAccountType(accountType)
                self.facebookAccount = accounts.lastObject as! ACAccount

                let facebookCredentials = self.facebookAccount.credentials

            } else {
                print("Error getting permission : \(error!.localizedDescription)")
                self.isFacebookAvailable = 0
            }
        }
    }
}

EDIT 1: я обновил свой код следующим образом

@IBAction func fbLogin(sender: UIButton) {

   if SLComposeViewController.isAvailableForServiceType(SLServiceTypeFacebook) {

       let accountType = self.accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)

        var dictFB = [String : AnyObject]()
        dictFB[ACFacebookAppIdKey] = "463272290501295"
        dictFB[ACFacebookPermissionsKey] = ["publish_profile","email","user_friends"]
        dictFB[ACFacebookAudienceKey] = ACFacebookAudienceFriends

        self.accountStore.requestAccessToAccountsWithType(accountType, options: dictFB) { (granted : Bool, error : NSError?) -> Void in
             if error != nil {
                 print("Error getting permission : \(error)")
              } else {
                  print("granted : \(granted)") //print false here
                  if granted {
                     let accounts : NSArray = self.accountStore.accountsWithAccountType(accountType)
                     self.facebookAccount = accounts.lastObject as! ACAccount

                     let facebookCredentials = self.facebookAccount.credentials
                    } else {
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            self.showAlert(nil, message: "Permission not granted For Your Application")
                        })
                    }
                }
            }
        } else {
            self.askForSettingsChange("Please login to a Facebook", message: "Go to settings to login Facebook")
        }
    }
    func showAlert(title : String? , message : String?) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let action = UIAlertAction(title: "OK", style: .Cancel, handler: nil)
        alert.addAction(action)

        self.presentViewController(alert, animated: true, completion: nil)
    }
    func askForSettingsChange(title : String? , message : String?) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        let settingAction = UIAlertAction(title: "Settings", style: .Default) { (action : UIAlertAction) -> Void in
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                UIApplication.sharedApplication().openURL(NSURL(string: UIApplicationOpenSettingsURLString)!) // go to settings
            })
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: .Default, handler: nil)

        alertController.addAction(settingAction)
        alertController.addAction(cancelAction)
        self.presentViewController(alertController, animated: true, completion: nil)
    }

проверьте настройки телефона, если пользователь facebook присутствует или нет, если он присутствует, перейдите к дальнейшему, но он не даст разрешения.


person Gunja Patel    schedule 20.10.2015    source источник
comment
удалите информацию о вашем APIKey, кто-то может использовать ее не очень хорошо....   -  person Dumitru Rogojinaru    schedule 09.01.2017


Ответы (4)


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

import Accounts
import Social

class LoginManager: NSObject {

    var facebookAccount: ACAccount?

    func facebookLogin(completion: (credential: ACAccountCredential?) -> Void) {
        let store = ACAccountStore()
        let facebook = store.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)
        let apiKey = "YOUR_FACEBOOK_API_KEY"
        let loginParameters: [NSObject: AnyObject] = [ACFacebookAppIdKey: apiKey, ACFacebookPermissionsKey: []]
        store.requestAccessToAccountsWithType(facebook, options: loginParameters) { granted, error in
            if granted {
                let accounts = store.accountsWithAccountType(facebook)
                self.facebookAccount = accounts.last as? ACAccount

                let credentials = self.facebookAccount?.credential
                completion(credential: credentials)
            } else {
                completion(credential: nil)
            }
        }
    }
}
person mustafa    schedule 20.10.2015
comment
предоставленное разрешение возвращает false в моем случае - person Gunja Patel; 20.10.2015
comment
Вам необходимо войти в facebook в настройках. И вам также необходимо настроить параметры приложения facebook - person mustafa; 20.10.2015
comment
Я уже вхожу в систему с настройками и настройками приложения facebook, в основных я добавил идентификатор пакета и в предварительных настройках, включил собственное приложение .... что-то осталось???? - person Gunja Patel; 20.10.2015
comment
Не знаю. Но вы можете отладить этот код и посмотреть, что говорит параметр ошибки - person mustafa; 20.10.2015

Вход через Facebook с помощью Accounts Framework (Swift)

var facebookAccount: ACAccount?

        let options: [NSObject : AnyObject] = [ACFacebookAppIdKey: "YOUR_FACEBOOK_API_KEY", ACFacebookPermissionsKey: ["publish_stream","publish_actions"],ACFacebookAudienceKey:ACFacebookAudienceFriends]
        let accountStore = ACAccountStore()
        let facebookAccountType = accountStore.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)

            accountStore.requestAccessToAccountsWithType(facebookAccountType, options: options) { (granted, error) -> Void in
                if granted
                {
                    let accounts = accountStore.accountsWithAccountType(facebookAccountType)
                    self.facebookAccount = accounts.last as? ACAccount
                    let accountsArray=accountStore.accountsWithAccountType(facebookAccountType) as NSArray

                    self.facebookAccount=accountsArray.lastObject as? ACAccount
                    var dict:NSDictionary
                    dict=NSDictionary()

                    dict=self.facebookAccount!.dictionaryWithValuesForKeys(["properties"])
                    let properties:NSDictionary=dict["properties"] as! NSDictionary
                    print("facebook Response is-->:%@",properties)
                }
                else
                {
                    if error.code == Int(ACErrorAccountNotFound.rawValue) {
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            self.displayAlert("There is no Facebook accounts configured. you can add or created a Facebook account in your settings.")
                        })
                    } else {
                        dispatch_async(dispatch_get_main_queue(), { () -> Void in
                            self.displayAlert("Permission not granted For Your Application")
                        })
                    }

                }
            }
person Reema    schedule 15.04.2016

Думаю, я знаю, в чем ваша проблема... Честно говоря, AcAccountStore - не лучший способ использовать Facebook...

Вот, пожалуйста, параметры, которые вы указали в своем «ACFacebookPermissionsKey», неверны. Это должно быть "public_profile", а не "publish"....

Удачи.

person An Chin    schedule 24.07.2016
comment
Только что потратил около 8 часов на устранение неполадок моего клиента Swift и понял, что вы НЕ можете запрашивать user_actions.fitness через AcAccountStore... Он ничего не показывает, кроме сбоя... Ни кода ошибки, ничего... - person An Chin; 24.07.2016
comment
вероятно, не только user_actions.fitness, но и больше разрешений невозможно запросить через AcAccountStore. У меня больше нет сил устранять неполадки... Просто имейте в виду... Затем я попробовал, и это сработало: public_profile, электронная почта, user_friends и user_about_me. Или, может быть, это потому, что у меня нет user_actions.fitness на Facebook... Кто знает, это не выдает никаких сообщений об ошибках... не используйте это, это было бы лучшим решением. - person An Chin; 24.07.2016

Вот мой пример контроллера просмотра для проверки входа в Facebook. Убедитесь, что настройки вашего приложения Facebook верны.

import UIKit
import Accounts
import Social

class ViewController: UIViewController {

// MARK: - Properties
var facebookAccount: ACAccount?

// MARK: - Lifecycle
override func viewDidLoad() {
    super.viewDidLoad()
}

// MARK: - Actions
@IBAction func buttonFBLoginAction() {
    facebookLogin { [unowned self] credential in
        guard let _ = credential else { return }
        // TODO: - Send token to service for login process.
        self.performSegueWithIdentifier("ShowSecondVC", sender: nil)
    }
}

// MARK: - Custom Methods
private func facebookLogin(completion: (credential: ACAccountCredential?) -> Void) {
    let store = ACAccountStore()
    let facebook = store.accountTypeWithAccountTypeIdentifier(ACAccountTypeIdentifierFacebook)
    let apiKey = "**************"
    let readPermissions = ["public_profile", "email"]
    let loginParameters: [NSObject: AnyObject] = [ACFacebookAppIdKey: apiKey, ACFacebookPermissionsKey: readPermissions]
    store.requestAccessToAccountsWithType(facebook, options: loginParameters) { granted, error in
        if granted {
            let accounts = store.accountsWithAccountType(facebook)
            self.facebookAccount = accounts.last as? ACAccount

            let credentials = self.facebookAccount?.credential
            completion(credential: credentials)
        } else {
            if let error = error {
                print(error.localizedDescription)
            }
            completion(credential: nil)
        }
    }
}
}
person serhanaksut    schedule 26.07.2016