Go to next screen after save data xcode? - xcode

I'm trying to go next screen after the save button is pushed, i tried to write code perform segue and i get buch of errors. Below is my code currently, i didn't finish the save part. I wanted to go back to that later time.
I'm new to coding in xcode, so any advice on where to put this code would be nice.
import UIKit
import CoreData
class SignupVC: UIViewController {
#IBOutlet var txtfirstname: UITextField!
#IBOutlet var txtlastname: UITextField!
#IBOutlet var txtUsername: UITextField!
#IBOutlet var txtPassword: UITextField!
#IBOutlet var txtConfirmpassword: UITextField!
#IBOutlet var txtEmail: UITextField!
var context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
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 signupTapped(_ sender: Any) {
_ = txtUsername.text;
_ = txtPassword.text;
_ = txtConfirmpassword.text;
_ = txtEmail.text;
//check empty fields
if((txtPassword.text?.isEmpty)! || (txtConfirmpassword.text?.isEmpty)! || (txtEmail.text?.isEmpty)!)
{
//Display alert
displayMyAlertMessage(userMessage: "All fields are required")
return;
}
//check if passwords match
if (txtPassword.text != txtConfirmpassword.text)
{
//Display in alert message
displayMyAlertMessage(userMessage: "Passwords don't match");
return;
}
//store Data
// Display alert message with Confirmation
}
func displayMyAlertMessage(userMessage:String)
{
let myAlert = UIAlertController(title:"Alert", message: userMessage, preferredStyle: UIAlertControllerStyle.alert);
let okAction = UIAlertAction(title:"ok", style: UIAlertActionStyle.default, handler:nil);
myAlert.addAction(okAction);
self.present(myAlert, animated:true, completion:nil);
}
/*

just go into storyboard and hold control key on the button and let it go on the ViewController you want to go to. Then select the kind. For Example "Show"
then it should work. If you have questions ask.

Related

UISwitch Status to Firestore

I am currently building a user creation mechanism where I have 8 UI switches to determine if someone has a food allergy or not. I have created an #IBOutlet for each switch and now have them contained in the document. I'm having no issue adding text fields:
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "username":username, ]
What I'd like to do is extend that syntax to add the status of the 8 UISwitch's on user creation.
New to Firebase and app development, but tried Googling everything I could think of. Thanks in advance for your help!
UPDATE
OK, so I must still be doing something wrong here, but I think I'm getting close:
import UIKit
import FirebaseAuth
import Firebase
class SignUpViewController: UIViewController {
#IBOutlet weak var firstNameTextField: UITextField!
#IBOutlet weak var lastNameTextField: UITextField!
#IBOutlet weak var usernameTextField: UITextField!
#IBOutlet weak var emailTextField: UITextField!
#IBOutlet weak var passwordTextField: UITextField!
#IBOutlet weak var milkSwitch: UISwitch!
#IBOutlet weak var peanutSwitch: UISwitch!
#IBOutlet weak var wheatSwitch: UISwitch!
#IBOutlet weak var treeNutSwitch: UISwitch!
#IBOutlet weak var fishSwitch: UISwitch!
#IBOutlet weak var shellFishSwitch: UISwitch!
#IBOutlet weak var eggSwitch: UISwitch!
#IBOutlet weak var soySwitch: UISwitch!
#IBOutlet weak var addAFamilyButton: UIButton!
#IBOutlet weak var signUpButton: UIButton!
#IBOutlet weak var errorLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setUpElements()
}
func setUpElements (){
errorLabel.alpha = 0
}
func showError(_ message:String) {
errorLabel.text = message
errorLabel.alpha = 1
}
//Check the fields and validate that data is correct.
func validateFields() -> String? {
//Check that all fields are filled in
if firstNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
lastNameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
emailTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" ||
passwordTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines) == "" {
return "Please fill in all fields."
}
//Check if password is secure
let cleanedPassword = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
if Utilities.isPasswordValid(cleanedPassword) == false {
// Password isn't secure enough
return "Please make sure your password is at least 8 characters, contains a special character and a number"
}
return nil
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
#IBAction func signUpTapped(_ sender: Any) {
// Validate the fields
let error = validateFields()
if error != nil {
// There's something wrong with the fields, show error message
showError(error!)
}
else {
// Cleaned Versions of the data
let firstname = firstNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let lastname = lastNameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let email = emailTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let password = passwordTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let username = usernameTextField.text!.trimmingCharacters(in: .whitespacesAndNewlines)
let milk = milkSwitch
let peanut = peanutSwitch
let wheat = wheatSwitch
let treenut = treeNutSwitch
let fish = fishSwitch
let shellfish = shellFishSwitch
let egg = eggSwitch
let soy = soySwitch
// Create the user
Auth.auth().createUser(withEmail: email, password: password) { (result, err) in
// Check for errors
if err != nil {
//There was an error creating the user
self.showError("Error creating user")
}
else {
// User was created successfully
let db = Firestore.firestore()
db.collection("users").addDocument(data: ["firstname":firstname, "lastname":lastname, "username":username, "uid": result!.user.uid, "milk":milkSwitch.isOn, "peanut":peanutSwitch.isOn, "wheat":wheatSwitch.isOn, "treenut":treeNutSwitch.isOn, "fish":fishSwitch.isOn, "shellfish":shellFishSwitch.isOn, "egg":eggSwitch.isOn, "soy":soySwitch.isOn ]) { (error) in
if error != nil {
//Show error message
self.showError("Your allergies have not been saved. Please login to your account")
}
}
// Transiition to the home screen
}
}
}
}
You can use isOn to get the status of a UISwitch
let peanutAllergySwitch = UISwitch()
let db = Firestore.firestore()
let data = [
"firstname":firstname,
"lastname":lastname,
"username":username,
"allergicToPeanuts": peanutAllergySwitch.isOn
]
db.collection("users").addDocument(data: data)

swift 4- Save the last data of a text field in a label so that they are displayed when the app is restarted

I have a problem, I want to create a small app in which data in a formula can be charged.
Currently the data from three ViewControllers and one PickerViewController will be given back to the first ViewController.
That works very well too.
Now I want that the data at the start not on "nil" set but have a certain value.
Thereafter, the data entered last should reappear when the app is restarted.
I would like to apologize for my english, it is not my preferred language ...
Here is a part of my code how I wrote it
Main ViewController:
import UIKit
class RecivingViewController: UIViewController, SendDataBack, SendDataBack2, SendDataBack3, SendDataBack4 {
#IBOutlet weak var recivingData: UILabel!
#IBOutlet weak var recivingData2: UILabel!
#IBOutlet weak var recivingData3: UILabel!
#IBOutlet weak var recivingData4: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
func userData(data: String) {
recivingData.text = data
}
func userData2(data: String) {
recivingData2.text = data
}
func userData3(data: String) {
recivingData3.text = data
}
func PickerData(data: String){
recivingData4.text = data
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "view1" {
let SendingVC: SendingViewController = segue.destination as! SendingViewController
SendingVC.delegate = self
}
if segue.identifier == "view2" {
let SendingVC2: Sending2ViewController = segue.destination as! Sending2ViewController
SendingVC2.delegate = self
}
if segue.identifier == "view3" {
let SendingVC3: Sending3ViewController = segue.destination as! Sending3ViewController
SendingVC3.delegate = self
}
if segue.identifier == "picker" {
let SendingVC4: PickerViewController = segue.destination as! PickerViewController
SendingVC4.delegate = self
}
}
}
one of the other ViewControllers:
import UIKit
protocol SendDataBack {
func userData(data: String)
}
class SendingViewController: UIViewController {
#IBOutlet weak var DataTxt: UITextField!
var delegate: SendDataBack? = nil
#IBAction func done(_ sender: Any) {
if delegate != nil {
if DataTxt.text != nil {
let data = DataTxt.text
delegate?.userData(data: data!)
dismiss(animated: true, completion: nil)
}
}
}
In order to see data after app is restarted you should use user defaults.
For saving data
UserDefaults.standard.set(newValue, forKey: "data")
For loading data in your view controller, if it's first load, when data is nil
UserDefaults.standard.string(forKey: "data")

Expression resolves to an unused function

So I have been messing around with saving and calling from NSUserDefaults and I have made progress but I keep on getting this error.
"Expression resolves to an unused function"
The program is supposed to save a string from a textfield so that if you close the program and open it the string will still be their. Unless, you press save again and then the string (Label) will change.
The problem prevents me from running the program so I have not been able to test the new code that I wrote.
Here is the source code feel free to try it. All of this is written in swift.
//
// ViewController.swift
// Help
//
// Created by Lucas on 9/30/15.
// Copyright (c) 2015 Lucas. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
#IBOutlet var Savedlbl: UILabel!
#IBOutlet var Textfield: UITextField!
#IBOutlet var Label: UILabel!
var current = ""
var Saved = ""
override func viewDidLoad() {
super.viewDidLoad()
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
// Do any additional setup after loading the view, typically from a nib.
}
#IBAction func Set(sender: AnyObject) {
setall()
}
func setall()
{
current = Textfield.text!
Label.text = Textfield.text!
Savedlbl.text = Textfield.text!
let currentDefault = NSUserDefaults.standardUserDefaults()
Savedlbl.text = currentDefault.valueForKey("saved") as? String
currentDefault.setValue(Saved, forKey: "saved")
currentDefault.synchronize
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
The line:
currentDefault.synchronize
should be:
currentDefault.synchronize()

Swift Adding Image to a Button

I want to add an image to a button, and when it is clicked, i want it to change. I'm very new to Swift so I know very little.
I have it like this:
//
// ViewController.swift
// Tip Calculator
//
// Created by ios4 on 10/16/15.
// Copyright (c) 2015 ios4. All rights reserved.
//
import UIKit
class ViewController: UIViewController
{
#IBOutlet weak var tipAmount: UILabel!
#IBOutlet weak var userBillTextField: UITextField!
#IBOutlet weak var tenOutlet: UIButton!
override func viewDidLoad()
{
tipAmount.text = " "
// var billDouble = (userBillTextField.text as NSString).doubleValue
super.viewDidLoad()
}
#IBAction func calculateButton(sender: UIButton)
{
var billDouble = NSString(string: userBillTextField.text).doubleValue
tipAmount.text = String( stringInterpolationSegment: billDouble * 0.15)
}
#IBAction func tenButton(sender: UIButton)
{
}
and I want the outlet called ten outlet to change to a different image called 10_selected_image from 10_unselected_image.
Any help?
Here are my instructions for this : https://s3.amazonaws.com/mmhighschool/MasterDocs/TipCalculator/TipCalculatorAppDirections.pdf
I'm currently working on stretch 3
You should be able to use set image for control state in your button action
button.setImage(image: UIImage(named: <image name>), forState: UIControlState.Normal)
If you need more info about how to make a "toggle button" this thread has a good answer to that
How to use a UIButton as a toggle switch
For me in Swift 5 is working like:
boton1.setBackgroundImage(UIImage(named: "image Name"), for: UIControl.State.normal)

How do I fix this crash? Xcode 6 Swift

I am only coding in two features. MailComposer and WebView. But when I run my app and go to the email interface tab it crashes "fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)". When I go to the tab that displays the webview, it works fine. The Webview.loadRequest(request) is messing something up with the mail coding. But I don't know where I can put it to make both features work.
If anyone has any clue how to fix this, please let me know. Thanks.
Here is the coding for the View.Controller.Swift file...
import UIKit
import MessageUI
class ViewController: UIViewController, MFMailComposeViewControllerDelegate {
#IBOutlet weak var Webview: UIWebView!
#IBOutlet weak var Subject: UITextField!
#IBOutlet weak var Body: UITextView!
var URLPath = "http://google.com"
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
loadAddressURL()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func SendEmail(sender: AnyObject) {
var SubjectText = "Inquiry:"
SubjectText += Subject.text
var MessageBody = Body
var toRecipients = ["phillip.lebsack1#gmail.com"]
var mc: MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(SubjectText)
mc.setMessageBody(MessageBody.text, isHTML: false)
mc.setToRecipients(toRecipients)
self.presentViewController(mc, animated: true, completion: nil)
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
switch result.value{
case MFMailComposeResultCancelled.value:
NSLog("Mail Cancelled")
case MFMailComposeResultSaved.value:
NSLog("Mail Saved")
case MFMailComposeResultSent.value:
NSLog("Mail Sent")
case MFMailComposeResultFailed.value:
NSLog("Mail Sent Failure: %#",[error.localizedDescription])
default:
break
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func loadAddressURL(){
let requestURL = NSURL(string:URLPath)
let request = NSURLRequest(URL: requestURL!)
Webview.loadRequest(request)
}
}
Make sure no warning message and bind all #IBOutlet in your ViewController.

Resources