skip to Main Content

I am trying to create an API for login user on facebook, but I have this error:

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

on this line:

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

Console shows:

My Code:

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

2

Answers


  1. Chosen as BEST ANSWER

    The problem was the app info in Constants.swift

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

  2. If you decide to use FBSDK, you should use kit’s functions to get data from Facebook. FBSDK has integrated functions for working with the network.

    Details

    xCode 8.2.1, Swift 3

    Full Sample: authorisation Facebook in Swift 3 FBSDK

    Podfile

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

    Info.plist

    add to 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

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

    Result

    You will be logged in and get user ID and name.

    Read about

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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search