Can't find fatal error: unexpectedly found nil while unwrapping an Optional value [closed] - swift

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
It was working last night, but when I run my code, now I am receiving a:
fatal error: unexpectedly found nil while unwrapping an Optional value.
Can someone help me locate this error?
import UIKit
class UserRegistration: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate, UITextFieldDelegate {
//USER REGISTRATION FORM
//Activity Indicator
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
//Error
func displayAlert(title:String, error:String){
//create Alert
var alert = UIAlertController(title: title, message: error, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: .Cancel, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//User Profile Picture Selection
var profileImage = UIImage()
var isThereImage = false
#IBOutlet var uploadProfilePictureButton: UIButton!
#IBAction func uploadProfilePicture(sender: AnyObject) {
//Settings needed for image upload
var image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.PhotoLibrary //can use '.camera' to access camera
image.allowsEditing = true
//Select image. FYI Completion is a function that happens when viewcontroller is presented
self.presentViewController(image, animated: true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController!, didFinishPickingImage image: UIImage!, editingInfo: [NSObject : AnyObject]!) {
//Store image in local variable to be resized later
profileImage = image
println("Image is selected")
//Manually Close View Controller
self.dismissViewControllerAnimated(true, completion: nil)
//Remove button title
uploadProfilePictureButton.setTitle("", forState: .Normal)
//Display Image
uploadProfilePictureButton.setBackgroundImage(image, forState: .Normal)
//Set isThereImage Boolean
isThereImage = true
}
//---------------------------------------
//User Input Information
#IBOutlet var userEmailAddress: UITextField!
#IBOutlet var userPasswordOne: UITextField!
#IBOutlet var userPasswordTwo: UITextField!
#IBOutlet var passwordConfirmationMatch: UILabel!
var confirmedPassword = Bool()
//---------------------------------------
//Submit User Input to Database
#IBAction func userRegistration(sender: AnyObject) {
var error = ""
//Verify if User Exist and Passwords Match
if userEmailAddress.text == "" || userPasswordOne.text == "" || confirmedPassword == false {
error = "Please enter an email address and password, or make sure your passwords match."
println("Registration had an error")
}
if error != "" {
displayAlert("Error in Registration", error: error)
} else {
//Sign Up User
var user = PFUser()
//Resize Profile Picture
let size = CGSizeApplyAffineTransform(profileImage.size, CGAffineTransformMakeScale(0.5, 0.5))
let hasAlpha = true
let scale: CGFloat = 0.0 // Automatically use scale factor of main screen
UIGraphicsBeginImageContextWithOptions(size, !hasAlpha, scale)
profileImage.drawInRect(CGRect(origin: CGPointZero, size: size))
let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
//User Information
user.password = userPasswordTwo.text
user.email = userEmailAddress.text
user.username = userEmailAddress.text
if isThereImage == false {
displayAlert("Please upload a picture for your profile.", error: error)
}else if isThereImage == true {
var imageData = UIImagePNGRepresentation(scaledImage)
var imageFile = PFFile(name: userEmailAddress.text + ".png", data:imageData)
user.setObject(imageFile, forKey: "userProfileImage")
}
user.setObject("", forKey: "firstName")
user.setObject("", forKey: "lastName")
user.setObject("", forKey: "userLocation")
//Insert Activity Indicator here
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0, 0, 50, 50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
//-------------------------------
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, signupError: NSError!) -> Void in
//Stop activity indicator whether there is an error or not
self.activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
if signupError == nil {
// Hooray! Let them use the app now.
println("Registration Completed")
} else {
//Keep this here!
if let errorString = signupError.userInfo?["error"] as? NSString{
error = errorString
} else {
error = "Please try again later."
}
self.displayAlert("Could not Sign Up", error: error)
println(signupError)
}
}
}
//Print Confirmation to Cortana
}
//---------------------------------------
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
passwordConfirmationMatch.hidden = true
//UITextField Delegate
self.userEmailAddress.delegate = self
self.userPasswordOne.delegate = self
self.userPasswordTwo.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//Password Matching Function
func passwordCheck() {
if userPasswordTwo.text == userPasswordOne.text {
passwordConfirmationMatch.hidden = false
confirmedPassword = true
println("Password match")
} else {
passwordConfirmationMatch.hidden = true
confirmedPassword = false
println("Passwords don't match")
}
}
//Handle Keyboard
override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {
self.view.endEditing(true)
passwordCheck()
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
userEmailAddress.resignFirstResponder()
userPasswordOne.resignFirstResponder()
userPasswordTwo.resignFirstResponder()
passwordCheck()
return true
}
}

The error you get indicates that one of your variables that has been declared as optional was nil when your code tried to access it.
Do you get any more info from the error? Like the name of the variable for example? If not, use some breakpoints to find the culprit and make sure it is not nil when the time to use it comes.

Related

Application doesn't update my location

I'm trying to launch simple geolocation app, however it is building without errors, it is doesn't update my location data as it should be. I'm using swift 3, xcode 8
class CurrentLocationViewController: UIViewController, CLLocationManagerDelegate {
let locationManager = CLLocationManager()
var location: CLLocation?
#IBOutlet weak var messageLabel: UILabel!
#IBOutlet weak var latitudeLabel: UILabel!
#IBOutlet weak var longitudeLabel: UILabel!
#IBOutlet weak var tagButton: UIButton!
#IBAction func getMyLocation(_ sender: Any) {
let authStatus = CLLocationManager.authorizationStatus()
if authStatus == .notDetermined {
locationManager.requestWhenInUseAuthorization()
return
}
if authStatus == .denied || authStatus == .restricted {
showLocationServicesDeniedAlert()
return
}
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
locationManager.startUpdatingLocation()
updateLabels()
}
//Showing Alert message if location service is disabled
func showLocationServicesDeniedAlert() {
let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable location services for this app in Settings.", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
//Updating Labels if Location is tutned on
func updateLabels() {
if let location = location {
latitudeLabel.text = String (format: "%.8f", location.coordinate.latitude)
longitudeLabel.text = String (format: "%.8f", location.coordinate.longitude)
tagButton.isHidden = false
messageLabel.text = ""
} else {
latitudeLabel.text = ""
longitudeLabel.text = ""
tagButton.isHidden = true
messageLabel.text = "Tap 'Get My Location' to Start"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - CLLocationManagerDelegate
func locationManager (manager: CLLocationManager, didFailWithError error: NSError) {
print("didFailWithError \(error)")
}
func locationManager (manager: CLLocationManager, didUpdateLocations locations : [CLLocation]) {
let newLocation = locations.last!
print("didUpdateLocations \(newLocation)")
location = newLocation
updateLabels()
}
}
I can't even catch error during debugging, because when I try to write print in console there is nothing happens.
Your problem resides in testing location-based code on the simulator. Whilst it is possible, the simulator has no way of knowing your location as it doesn't have access to any GPS hardware.
However, by it's very nature it is a Simulator and therefore you can simulate your location. This is easy to do, just open the simulator and navigate to Debug>Location as shown in the below image.
Apple gives us a couple of built in options but they are all in the USA so I like to use a custom one. You just need to click custom and enter a coordinate. Then reinstall your app and reauth your location, and it should be working as expected. Let me know if it is not.

How can I change the Image in UIViewController permantly

Apologies again if this is a noobie question, but still relatively new to swift, so please bear with me,
I am trying to change the image in a UIViewController even after the user has left the page or closed the app, the idea being that the image is pressed a password enter and the image is changed, (which I have done with the help of dzk) and the image changes as it should.
but when i leave the app page and then come back in it has reset to it's original image, so frustrating!
below is the code as it stands that will change the image after UIAlertController is validated.
Any help would be grateful.
class Man_VS_Cocktail : UIViewController{
#IBOutlet weak var Cocktail_Image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nil
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Cocktail_check_button(sender: AnyObject) {
var password_Text: UITextField?
let alertController = UIAlertController(title: "One more ticked off", message: "ask the barman to enter the password", preferredStyle: UIAlertControllerStyle.Alert)
let tickoff_action = UIAlertAction(title: "sign it off", style: UIAlertActionStyle.Default) {
action -> Void in
if let password = password_Text?.text{
print("password = \(password)")
if password == "pass123" {
self.Cocktail_Image.image = UIImage(named: "riddler_question_marks")
}
} else {
print("No password entered")
}
}
alertController.addTextFieldWithConfigurationHandler { (txtpassword) -> Void in
password_Text = txtpassword
password_Text!.secureTextEntry = true
password_Text!.placeholder = ""
}
alertController.addAction(tickoff_action)
self.presentViewController(alertController, animated: true, completion: nil)
}
As a side note would it be possible to have master rest action that resets all images to their original state? I presume this would be an if statement?
This is an example on using NSDefaults. You can change and format in a way that would fit your needs more.
class Man_VS_Cocktail : UIViewController{
let defaults: NSUserDefaults
#IBOutlet weak var Cocktail_Image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Check saved password.
let passSaved = defaults.stringForKey("password")
if passSaved == "pass123" {
self.Cocktail_Image.image = UIImage(named: "riddler_question_marks")
} else {
// Set default image.
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func Cocktail_check_button(sender: AnyObject) {
var password_Text: UITextField?
let alertController = UIAlertController(title: "One more ticked off", message: "ask the barman to enter the password", preferredStyle: UIAlertControllerStyle.Alert)
let tickoff_action = UIAlertAction(title: "sign it off", style: UIAlertActionStyle.Default) {
action -> Void in
if let password = password_Text?.text{
print("password = \(password)")
if password == "pass123" {
// Save the password
self.defaults.setObject(password_Text, forKey: "password")
// End save password
self.Cocktail_Image.image = UIImage(named: "riddler_question_marks")
}
} else {
print("No password entered")
}
}
alertController.addTextFieldWithConfigurationHandler { (txtpassword) -> Void in
password_Text = txtpassword
password_Text!.secureTextEntry = true
password_Text!.placeholder = ""
}
alertController.addAction(tickoff_action)
self.presentViewController(alertController, animated: true, completion: nil)
}
You could even do a check in you your AppDelegate with the same format. You could even add some some kind of delay or clear the saved password via the AppDelegate applicationWillTerminate.

Black background image using camera with Swift2

I'm trying to display the user camera (back camera) using the AVFoundation, but I must be doing something wrong because It's only showing a black background image.
I have checked my Privacy > Camera and there isn't any option regarding the camera with my App, and I am not able to display the .Alert action to ask the user the permission to access the camera.
Here is my code, I hope you could help me because this is very weird:
import UIKit
import AVFoundation
class CodigoBarrasViewController: UIViewController, AVCaptureMetadataOutputObjectsDelegate {
#IBOutlet weak var messageLabel:UILabel!
#IBOutlet weak var imagenFondo:UIImageView!
#IBOutlet weak var BackgroundView:UIView!
var string:String!
var captureSession:AVCaptureSession?
var videoPreviewLayer:AVCaptureVideoPreviewLayer?
var qrCodeFrameView:UIView?
// Added to support different barcodes
let supportedBarCodes = [AVMetadataObjectTypeQRCode, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeCode39Code, AVMetadataObjectTypeCode93Code, AVMetadataObjectTypeUPCECode, AVMetadataObjectTypePDF417Code, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeAztecCode]
override func viewDidAppear(animated: Bool) {
captureSession?.startRunning()
self.qrCodeFrameView?.hidden = true
}
override func viewDidLoad() {
//captureSession?.startRunning()
super.viewDidLoad()
// Get an instance of the AVCaptureDevice class to initialize a device object and provide the video
// as the media type parameter.
let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo)
do {
input = try AVCaptureDeviceInput(device: captureDevice) as AVCaptureDeviceInput
}
catch let error as NSError {
print(error)
}
// Initialize the captureSession object.
captureSession = AVCaptureSession()
// Set the input device on the capture session.
captureSession?.addInput(input)
//captureSession?.addInput(input as AVCaptureInput)
// Initialize a AVCaptureMetadataOutput object and set it as the output device to the capture session.
let captureMetadataOutput = AVCaptureMetadataOutput()
captureSession?.addOutput(captureMetadataOutput)
// Set delegate and use the default dispatch queue to execute the call back
captureMetadataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
captureMetadataOutput.metadataObjectTypes = supportedBarCodes
// Initialize the video preview layer and add it as a sublayer to the viewPreview view's layer.
videoPreviewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
videoPreviewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
videoPreviewLayer?.frame = view.layer.bounds
view.layer.addSublayer(videoPreviewLayer!)
// Start video capture.
captureSession?.startRunning()
// Move the message label to the top view
view.bringSubviewToFront(imagenFondo)
view.bringSubviewToFront(messageLabel)
view.bringSubviewToFront(BackgroundView)
// Initialize QR Code Frame to highlight the QR code
qrCodeFrameView = UIView()
qrCodeFrameView?.layer.borderColor = UIColor(hex: 0x00B7BB).CGColor
qrCodeFrameView?.layer.borderWidth = 2
view.addSubview(qrCodeFrameView!)
view.bringSubviewToFront(qrCodeFrameView!)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
//self.navigationController?.hidesBarsOnSwipe = true
self.navigationController?.setNavigationBarHidden(true, animated: false)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
// Check if the metadataObjects array is not nil and it contains at least one object.
if metadataObjects == nil || metadataObjects.count == 0 {
qrCodeFrameView?.frame = CGRectZero
//messageLabel.text = "No QR code is detected"
return
}
else
{
// Get the metadata object.
let metadataObj = metadataObjects[0] as! AVMetadataMachineReadableCodeObject
// Here we use filter method to check if the type of metadataObj is supported
// Instead of hardcoding the AVMetadataObjectTypeQRCode, we check if the type
// can be found in the array of supported bar codes.
if supportedBarCodes.filter({ $0 == metadataObj.type }).count > 0 {
// If the found metadata is equal to the QR code metadata then update the status label's text and set the bounds
let barCodeObject = videoPreviewLayer?.transformedMetadataObjectForMetadataObject(metadataObj as AVMetadataMachineReadableCodeObject) as! AVMetadataMachineReadableCodeObject
qrCodeFrameView?.frame = barCodeObject.bounds
if metadataObj.stringValue != nil {
captureSession?.stopRunning()
self.qrCodeFrameView?.hidden = false
launchApp(metadataObj.stringValue)
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "seeProduct" {
let destinationController = segue.destinationViewController as! ProductoCamViewController
let string = (sender as! String!)
let backItem = UIBarButtonItem()
backItem.title = " "
navigationItem.backBarButtonItem = backItem
destinationController.ean = string
}
}
func launchApp(decodedURL: String) {
let alertPrompt = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
//let alertPrompt = UIAlertController(title: "", message: decodedURL, preferredStyle: .ActionSheet)
let confirmAction = UIAlertAction(title: "See product", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.performSegueWithIdentifier("seeProduct", sender: decodedURL)
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.captureSession?.startRunning()
self.qrCodeFrameView?.hidden = true
})
//let cancelAction = UIAlertAction(title: "Cancelar", style: UIAlertActionStyle.Cancel, handler: nil)
alertPrompt.addAction(confirmAction)
alertPrompt.addAction(cancelAction)
self.presentViewController(alertPrompt, animated: true, completion: nil)
}
}
Thanks in advance,
Regards.
I would suggest taking a look at UIImagePickerControllerDelegate if you're wanting to access the camera.
Implement this and all of the permission alerts are handled for you

Saving username and password using UISwitch in Swift

Ive searched a lot of threads and this is my last resort because Ive seen this question asked different ways but not exactly for swift and for Username and password saving. I want my UISwitch when turned on to save my username and password info. I've been trying all day to get this UISwitch to save my username and password using NSUserDefaults. Please help me I'm at my whits end with trying it, I've searched almost every forum to find the answer but not many people show you exactly how to implement it. Below is my code. I know its bleak, as I am a beginner, but I have my "Login Button" saving my username and password, but i don't know how to get it to only save that information when I click the UISwitch and how to save it in the "view did load method". thanks for the help in advance!! I don't know what code to include into my UISwitch Method.
Here is the first part of my login button and then my view did load method. I don't have any code for the UISwitchMethod
override func viewDidLoad() {
super.viewDidLoad()
//Save username and password info if Save UISwitch is selected
switchState.on = NSUserDefaults.standardUserDefaults().boolForKey("switchState")
NSUserDefaults.standardUserDefaults().boolForKey("keepUsername")
NSUserDefaults.standardUserDefaults().boolForKey("keepPassword")
}
#IBAction func LoginButton(sender: AnyObject) {
var username = self.usernameTextField.text
var password = self.passwordTextField.text
var user = PFUser.currentUser()
NSUserDefaults.standardUserDefaults().setObject(username, forKey: "keepUsername")
NSUserDefaults.standardUserDefaults().setObject(password, forKey: "keepPassword")
if count(username) < 4 || count(password) < 5 {
var alert: UIAlertView = UIAlertView(title: "Sorry!", message: "Username Must be greater than 4 characters and the password greater that 5 characters", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}else {
self.actInd.startAnimating()
PFUser.logInWithUsernameInBackground(username, password: password, block: { (user, NSError) -> Void in
self.actInd.stopAnimating()
if ((user) != nil) {
println("Success \(user) logged in")
self.performSegueWithIdentifier("toHomeFromLogin", sender: self)
}else {
var alert: UIAlertView = UIAlertView(title: "error", message: "Please Sign up :)", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
#IBAction func switchStateChanged(sender: UISwitch) {
NSUserDefaults.standardUserDefaults().setBool(switchState.on, forKey: "switchState")
}
I will add some notes and edits I would do and I hope it can help you:
var switchState = Bool()
var userName = String()
var password = String()
override func viewDidLoad() {
super.viewDidLoad()
//Load all values
switchState = NSUserDefaults.standardUserDefaults().boolForKey("switchState")
userName = NSUserDefaults.standardUserDefaults().stringForKey("keepUsername")
password = NSUserDefaults.standardUserDefaults().stringForKey("keepPassword")
//Display values somewhere
}
#IBAction func LoginButton(sender: AnyObject) {
var enteredUser = self.usernameTextField.text
var enteredPassword = self.passwordTextField.text
var user = PFUser.currentUser()
NSUserDefaults.standardUserDefaults().setObject(enteredUser, forKey: "keepUsername")
NSUserDefaults.standardUserDefaults().setObject(enteredPassword, forKey: "keepPassword")
NSUserDefaults.standardUserDefaults().synchronize()
if count(username) < 4 || count(password) < 5 {
var alert: UIAlertView = UIAlertView(title: "Sorry!", message: "Username Must be greater than 4 characters and the password greater that 5 characters", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}else {
self.actInd.startAnimating()
PFUser.logInWithUsernameInBackground(username, password: password, block: { (user, NSError) -> Void in
self.actInd.stopAnimating(
if ((user) != nil) {
println("Success \(user) logged in")
self.performSegueWithIdentifier("toHomeFromLogin", sender: self)
}else {
var alert: UIAlertView = UIAlertView(title: "error", message: "Please Sign up :)", delegate: self, cancelButtonTitle: "Ok")
alert.show()
}
#IBAction func switchStateChanged(sender: UISwitch) {
//var readValueFromSwitch = something bolean
//NSUserDefaults.standardUserDefaults().setBool(readValueFromSwitch, forKey: "switchState")
//NSUserDefaults.standardUserDefaults().synchronize()
}
I send you the hole page so you can get and idea and also there is a way you can send alert messages for the Register page, look the //store data
import UIKit
class RegisterPageViewController: UIViewController {
#IBOutlet weak var userEmailTextField: UITextField!
#IBOutlet weak var userPasswordTextField: UITextField!
#IBOutlet weak var repeatPasswordTextField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func registerButtonTapped(sender: AnyObject) {
let userEmail = userEmailTextField.text;
let userPassword = userPasswordTextField.text;
let userRepeatPassword = repeatPasswordTextField.text;
// Check for empty fields
if (userEmail.isEmpty || userPassword.isEmpty || userRepeatPassword.isEmpty)
{
// Display alert message
displayMyAlertMessage("All fields are required");
return;
}
// Check if passwords match
if(userPassword != userRepeatPassword)
{
//Display an alert message
displayMyAlertMessage("Passwords do not match");
return;
}
// Store data
NSUserDefaults.standardUserDefaults().setObject(userEmail, forKey: "userEmail");
NSUserDefaults.standardUserDefaults().setObject(userPassword, forKey: "userPassword");
NSUserDefaults.standardUserDefaults().synchronize();
// Display alert message with confirmation.
var myAlert = UIAlertController(title: "Alert", message: "Registration successful, Thank you!", preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default){action in
self.dismissViewControllerAnimated(true, completion: nil);
}
myAlert.addAction(okAction);
self.presentViewController(myAlert, animated:true, completion:nil);
}
func displayMyAlertMessage(userMessage:String)
{
var myAlert = UIAlertController(title: "Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.Alert);
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil);
myAlert.addAction(okAction);
self.presentViewController(myAlert , animated: true, completion: nil)
}
}

performSegueWithIdentifier causes crash

I'm setting up a sign up/login page using framework PARSE on XCode 6.
When I try to perform a segue (it is spelled correcty), hover, the app crash, even though the segue is inside an if statement.
Here's the code:
import UIKit
import Parse
class ViewController: UIViewController, UINavigationControllerDelegate{
var signUpMode = false
func displayAlert(title:String, message:String){
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
//Outlet and actions
#IBOutlet var username: customTextField!
#IBOutlet var email: customTextField!
#IBOutlet var password: customTextField!
//Need the outlets for changes betweeen signUp and logIn modes!!!
#IBAction func signUp(sender: AnyObject) {
if signUpMode == true {
var user = PFUser()
user.username = username.text
user.password = password.text
user.email = email.text
// other fields can be set just like with PFObject
//user["phone"] = "415-392-0202"
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
// Hooray! Let them use the app now.
} else {
println("error")
self.displayAlert("Username already in use", message: "Please use another username")
}
}
}
else {
PFUser.logInWithUsernameInBackground(email.text, password:password.text) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
self.displayAlert("You're in", message: "And you'll be successful")
self.performSegueWithIdentifier("goToPost", sender: self)
} else {
self.displayAlert("Wrong username or password", message: "Please try again")
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(animated: Bool) {
if signUpMode == false {
self.username.hidden = true
self.email.placeholder = "username"
}
}
override func viewDidAppear(animated: Bool) {
if PFUser.currentUser() != nil {
performSegueWithIdentifier("goToPost", sender: self)
}
}
}
The segue is inside the viewWillAppear method.
PFUser().currentUser() stores information about the current logged in user, so it's nil if no user is logged in.
Can you find out why it crashes?
I tried to put the segue inside viewDidLoad, but nothing else, it didn't even crashed.
Try segueing in viewDidAppear: and check if your segue identifier matches the one on your storyboard.