Jim Sadler Jim Sadler - 1 month ago 9
Swift Question

EXC_BREAKPOINT (code=1, subcode=0x1051fbb50) console prints this: fatal error: Index out of range

I am new to swift development and I apologize if this question has already been answered, but I have no Idea why I am getting this error. it will build successfully, but when the buttonTapped gets tapped I get this error and the app crashes.

here is my code:

import UIKit
import Firebase
import FBSDKLoginKit
import FirebaseAuth
import FBSDKCoreKit

class QuotesViewController: UIViewController {


@IBOutlet weak var quoteLabel: UILabel!


var quotes : [Quote] = []
override func viewDidLoad() {
super.viewDidLoad()

Database.database().reference().child("quotes").observe(DataEventType.childAdded, with: {(snapshot) in
print(snapshot)

let quote = Quote()
quote.quote = (snapshot.value! as! NSDictionary)["quote"] as! String

self.quotes.append(quote)
})

}

@IBAction func buttonTapped(_ sender: Any) {
newQuote()
}


@IBAction func didTappedLogout(_ sender: Any) {
// sign user out of firebase
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
} catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}

// sign user out of Facebook
FBSDKAccessToken.setCurrent(nil)
let mainStoryboard: UIStoryboard = UIStoryboard(name:"Main", bundle:nil)
let SignInViewController: UIViewController = mainStoryboard.instantiateViewController(withIdentifier: "LoginView")

self.present(SignInViewController, animated: true, completion: nil)
}


func newQuote(){ **this is where I get the error**
let myQuote = quotes[Int(arc4random_uniform(UInt32(quotes.count) ))]
quoteLabel.text = myQuote.quote
// print(myQuote.quoteID)

}
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
newQuote()

}
}

Answer Source

the issue was that the signInSegue was out side the credential function like this:

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    if error != nil {
        print(error)
        return
    }
    print("Successfully logged in with Facebook...")
    let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
    Auth.auth().signIn(with: credential) { (user, error) in
        print("User logged in...")



    }
    self.performSegue(withIdentifier: "signInSegue", sender: nil)
}

it should be like this:

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    if error != nil {
        print(error)
        return
    }
    print("Successfully logged in with Facebook...")
    let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
    Auth.auth().signIn(with: credential) { (user, error) in
        print("User logged in...")
        self.performSegue(withIdentifier: "signInSegue", sender: nil)


    }

}