Facebook授权,Swift 3,FBSDK

时间:2017-03-28 18:22:33

标签: swift xcode facebook fbsdk

我正在尝试在Facebook上为登录用户创建API,但我有这个错误:

  

主题1:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

在这一行:

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

控制台显示:

我的代码:

  

致命错误:在展开Optional值时意外发现nil       (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
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

如果您决定使用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类

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

答案 1 :(得分:0)

问题是Constants.swift中的应用信息

let BASE_URL: String = ""
let CLIENT_ID: String = ""
let CLIENT_SECRET: String = ""