Facebook中的授权,Swift 3、FBSDK

Authorization in Facebook, Swift 3, FBSDK

我正在尝试为 facebook 上的登录用户创建一个 API,但出现此错误:

Thread 1:EXC_BAD_INSTRUCTION(code=EXC_I386_INVOP,subcode=0x0)

这一行:

self.accessToken = jsonData["access_token"].string!

控制台显示:

我的代码:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

func login(userType: String, completionHandler: @escaping (NSError?) -> Void) {

        let path = "api/social/convert-token/"
        let url = baseURL!.appendingPathComponent(path)
        let params: [String: Any] = [
            "grant_type": "convert_token",
            "client_id": CLIENT_ID,
            "client_secret": CLIENT_SECRET,
            "backend": "facebook",
            "token": FBSDKAccessToken.current().tokenString,
            "user_type": userType
        ]

        Alamofire.request(url!, method: .post, parameters: params, encoding: URLEncoding(), headers: nil).responseJSON { (response) in

            switch response.result {
            case .success(let value):

                let jsonData = JSON(value)

                self.accessToken = jsonData["access_token"].string!
                self.refreshToken = jsonData["refresh_token"].string!
                self.expired = Date().addingTimeInterval(TimeInterval(jsonData["expires_in"].int!))

                completionHandler(nil)
                break

            case .failure(let error):
                completionHandler(error as NSError?)
                break
            }
        }
    }

如果您决定使用FBSDK,您应该使用工具包的功能从Facebook 获取数据。 FBSDK 集成了与网络协同工作的功能。

详情

xCode 8.2.1, Swift 3

完整示例:在Swift 3 FBSDK

中授权Facebook

Podfile

target '{YOUR_PROJECT_NAME}' do
  use_frameworks!
  pod 'FBSDKCoreKit'
  pod 'FBSDKLoginKit'
  pod 'FBSDKShareKit'
end

Info.plist

添加到 plist

<key>CFBundleURLTypes</key>
<array>
    <dict>
        <key>CFBundleURLSchemes</key>
    <array>
        <string>fb{your-app-id}</string>
    </array>
    </dict>
</array>
<key>FacebookAppID</key>
<string>{your-app-id}</string>
<key>FacebookDisplayName</key>
<string>{your-app-name}</string>
<key>LSApplicationQueriesSchemes</key>
<array>
    <string>fbapi</string>
    <string>fb-messenger-api</string>
    <string>fbauth2</string>
    <string>fbshareextension</string>
</array>
<key>NSPhotoLibraryUsageDescription</key>
<string>{human-readable reason for photo access}</string>

AppDelegate

添加到 AppDelegate class

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
    return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, options: options)
}

ViewController.swift

import UIKit
import FBSDKLoginKit

class ViewController: UIViewController {

    let loginManager = FBSDKLoginManager()

    override func viewDidLoad() {
        super.viewDidLoad()

        FBSDKProfile.enableUpdates(onAccessTokenChange: true)

        let button = UIButton(frame: CGRect(x: 40, y: 40, width: 200, height: 40))
        button.setTitle("Button", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        button.addTarget(self, action: #selector(ViewController.login), for: .touchUpInside)
        view.addSubview(button)
    }

    func login() {
        if let token = FBSDKAccessToken.current() {
            // User is logged in, do work such as go to next view controller.
            print(token)
        } else {
            loginManager.logIn(withReadPermissions: ["public_profile"], from: self) { (loginManagerLoginResult, error) in

                FBSDKProfile.enableUpdates(onAccessTokenChange: true)
                print("token \(FBSDKAccessToken.current().tokenString)")

                FBSDKGraphRequest(graphPath: "me", parameters: nil).start(completionHandler: { (connection, result, error) -> Void in
                    if error == nil{
                        if let dict = result as? Dictionary<String, AnyObject>{
                            print(dict)
                        }
                    }
                })
            }
        }
    }
}

结果

您将登录并获得用户 ID 和名称。

了解

https://developers.facebook.com/docs/ios/getting-started https://developers.facebook.com/docs/reference/ios/current/class/FBSDKLoginManager

问题出在 Constants.swift

中的应用信息
let BASE_URL: String = ""
let CLIENT_ID: String = ""
let CLIENT_SECRET: String = ""