繁体   English   中英

Facebook在iOS swift中使用社交和帐户框架登录

[英]Facebook login using Social and Accounts Frameworks in iOS swift

我正在尝试使用社交和帐户框架登录。

Facebook通过ios中的社交框架登录
按照这个问题,将代码转换为快速但收到错误

该操作无法完成。 (com.apple.accounts错误6.)

在目标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
            }
        }
    }
}

编辑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用户在场,请检查手机设置,如果有,则转到更远但不会授予许可。

这是我在我的应用程序中使用的辅助类

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)
            }
        }
    }
}

Facebook使用帐户框架登录(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")
                        })
                    }

                }
            }

我想我可能知道你的问题是什么......老实说,AcAccountStore不是使用Facebook的最佳方式......

在这里,您在“ACFacebookPermissionsKey”中提供的选项是错误的。 它应该是“public_profile”,而不是“发布”....

祝好运。

这是我的示例视图控制器来测试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)
        }
    }
}
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM