I am building an app with Swift that fetches your email address, first name and last name from your Facebook profile once logged in and displays it on screen.
To make it simpler, I am focusing on making the email work and then I will work on the first and last name.
I created a label called EmailLabel that is supposed to display the email address on screen. However, when I try to change EmailLabel's text to the actual email address, I get the
Thread1: EXC_BAD_INSTRUCTION ERROR (code=EXC_1386_INVOP, subcode=0x0)
and the
fatal error:unexpectedly found nil while unwrapping an Optional value
message.
I know that the EmailLabel is always unwrapping as a nil. To fix this I wrote:
self.EmailLabel = UILabel()
It stopped giving me the error but the EmailLabel wouldn't update its text to the actual email address.
I would really appreciate any help! By the way, I am quite new to programming so please try to give a simple answer :)
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
@IBOutlet var EmailLabel: UILabel!
@IBOutlet var SomeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.center = self.view.center
loginButton.delegate = self
self.view.addSubview(loginButton)
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result:FBSDKLoginManagerLoginResult!, error: NSError!) {
fetchProfile()
if error == nil
{
print("Login complete")
self.performSegueWithIdentifier("showInfo", sender: nil)
}
else
{
print(error.localizedDescription)
}
}
func fetchProfile(){
print("fetchProfile")
let parameters = ["fields": "email, first_name, last_name"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).startWithCompletionHandler { (connection, result, error) -> Void in
if error != nil{
print(error)
return
}
if var email = result["email"] as? String {
print(email)
self.EmailLabel.text = "\(email)"
}
if let first_name = result["first_name"] as? String {
print(first_name)
}
if let last_name = result["last_name"] as? String {
print(last_name)
}
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
}
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool {
return true
}
}
I tried looking at other questions but it isn't working
Is there a reason for the label being a nil apart from the IB Outlet not being connected?