PreparetoSegue Button Command to Another ViewController Swift - xcode

How do I preparetoSegue a button command to another ViewController? It seem my calculateButton is giving me an error code.
MainViewController
if (segue.identifier == "toCalculate") {
let destViewController : CalcualteViewController = segue.destinationViewController as CalcualteViewController
destViewController.calculateButton(sender: UIButton) {
let dataone = data1.text.toInt() ?? 0
let datatwo = data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
answer.text = "\(answercalculation)" + " psi"
}
CalculateViewController
class CalcualteViewController: UIViewController {
#IBOutlet weak var textlabel: UILabel!
#IBOutlet var answer: UITextField!
#IBOutlet var data1: UITextField!
#IBOutlet var data2: UITextField!
#IBAction func calculateButton(sender: AnyObject) {
}

destViewController.calculateButton is a method of CalculateViewController. You have a closure hanging off the end of it when it doesn't accept any arguments accept sender: AnyObject. Move your logic into the CalculateViewController.
#IBAction func calculateButton(sender: AnyObject) {
let dataone = data1.text.toInt() ?? 0
let datatwo = data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
answer.text = "\(answercalculation)" + " psi"
}
If you want to share the code across multiple controllers you could create an instance variable called var calculateButtonAction: ((UIButton) -> ())? and then set it in prepareForSegue:
destinationViewController.calculateButtonAction = { (sender) in
let dataone = destinationViewController.data1.text.toInt() ?? 0
let datatwo = destinationViewController.data2.text.toInt() ?? 0
let answercalculation = dataone * datatwo
destinationViewController.answer.text = "\(answercalculation)" + " psi"
}
And then call it from CalculatorViewController:
#IBAction func calculateButton(sender: AnyObject) {
if let action = calculateButtonAction {
action(sender)
}
}
Better yet, create a BaseCalculatorViewController and subclass it for your controllers so you can have your subclasses inherit calculateButton.

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)

How to calculate string in text field by Xcode 8.3.3

I want a solution in my problem.
I have text field in Xcode and I wanna Xcode calculate string thats user input as:
var x = 1
var y = 2
like this
I wanna if the user input xy inside text field, the Xcode calculate like: 1+2
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
#IBOutlet var label1: UILabel!
#IBOutlet var label2: UILabel!
#IBOutlet var label3: UILabel!
#IBOutlet var label4: UILabel!
#IBOutlet var tex1: UITextField!
#IBOutlet var tex2: UITextField!
override function viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tex1.delegate = self
tex2.delegate = self
}
override function didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
function textFieldShouldReturn(_ textField: UITextField) -> Bool{
tex1.resignFirstResponder()
tex2.resignFirstResponder()
return true
}
#IBAction function close(_ sender: UIButton) {
tex1.resignFirstResponder()
tex2.resignFirstResponder()
}
#IBAction function pushAction(_ sender: UIButton) {
label4.text = String(Int(tex1.text)+Int(tex2.text))
}
}
var temp = 0
var prevCount = -1
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
var txtAfterUpdate:NSString = textField.text! as NSString
txtAfterUpdate = txtAfterUpdate.replacingCharacters(in: range, with: string).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) as NSString
let newString:String! = String(txtAfterUpdate)
if(prevCount > newString.characters.count - 1){
if(newString.characters.count - 1 != -1){
self.enterAmount = self.enterAmount - Double(textField.text![(textField.text?.characters.count)! - 1])!
}else{
self.enterAmount = 0
}
}else{
self.enterAmount = Double(newString[newString.characters.count - 1])! + self.enterAmount
}
print("YOUR TOTAL \(self.enterAmount)")
prevCount = newString.characters.count - 1
return true
}
extension String{
subscript(i: Int) -> String {
guard i >= 0 && i < characters.count else { return "" }
return String(self[index(startIndex, offsetBy: i)])
}
subscript(range: Range<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound, limitedBy: endIndex) ?? endIndex))
}
subscript(range: ClosedRange<Int>) -> String {
let lowerIndex = index(startIndex, offsetBy: max(0,range.lowerBound), limitedBy: endIndex) ?? endIndex
return substring(with: lowerIndex..<(index(lowerIndex, offsetBy: range.upperBound - range.lowerBound + 1, limitedBy: endIndex) ?? endIndex))
}
}
you can use like this
label4.text = "\(((tex1.text?.characters.count)! + (tex2.text?.characters.count)!))"

GeoTag Images from image picker swift 3

I want to get geotag location from image which is selected from image picker. I am using this code
if picker.sourceType == UIImagePickerControllerSourceType.PhotoLibrary
{
if let currentLat = pickedLat as CLLocationDegrees?
{
self.latitude = pickedLat!
self.longitude = pickedLong!
}
else
{
var library = ALAssetsLibrary()
library.enumerateGroupsWithTypes(ALAssetsGroupAll, usingBlock: { (group, stop) -> Void in
if (group != nil) {
println("Group is not nil")
println(group.valueForProperty(ALAssetsGroupPropertyName))
group.enumerateAssetsUsingBlock { (asset, index, stop) in
if asset != nil
{
if let location: CLLocation = asset.valueForProperty(ALAssetPropertyLocation) as CLLocation!
{ let lat = location.coordinate.latitude
let long = location.coordinate.longitude
self.latitude = lat
self.longitude = lat
println(lat)
println(long)
}
}
}
} else
{
println("The group is empty!")
}
})
{ (error) -> Void in
println("problem loading albums: \(error)")
}
}
}
i want to know to covert this code in swift 3 .I am new in coding with swift 3 .It will be very helpful
After hours of searching i got my ans
import UIKit
import Photos
class ViewController: UIViewController,UIImagePickerControllerDelegate, UINavigationControllerDelegate {
#IBOutlet weak var imageView: UIImageView!
#IBOutlet weak var locationLabel: UILabel!
#IBOutlet weak var timeLabel: UILabel!
#IBOutlet weak var logi: UILabel!
#IBOutlet weak var lati: UILabel!
var lat = String()
var log = String()
var location = String()
var timeTaken = "Not Known"
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.
}
#IBAction func imagegeo(_ sender: Any) {
let imagePicker = UIImagePickerController()
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
var chosenImage:UIImage?
if let URL = info[UIImagePickerControllerReferenceURL] as? URL {
print("We got the URL as \(URL)")
let opts = PHFetchOptions()
opts.fetchLimit = 1
let assets = PHAsset.fetchAssets(withALAssetURLs: [URL], options: opts)
print(assets)
for assetIndex in 0..<assets.count {
let asset = assets[assetIndex]
location = String(describing: asset.location)
log = String(describing: asset.location?.coordinate.longitude)
lat = String(describing: asset.location?.coordinate.latitude)
timeTaken = (asset.creationDate?.description)!
print(log)
print(location)
print(lat)
}
}
if let editedImage = info[UIImagePickerControllerEditedImage] as? UIImage {
chosenImage = editedImage
} else if let selectedImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
chosenImage = selectedImage
}
dismiss(animated: true) {
DispatchQueue.main.async {
self.imageView.image = chosenImage
self.timeLabel.text = self.timeTaken
self.locationLabel.text = self.location
self.lati.text = self.lat
self.logi.text = self.log
}
}
}
}

Fatal error editing core data objects

I am newbie to programming. With CoreData, I am trying to create the function to edit the data in input text field to edit the data to be saved to core data. I am having fatal error:
unexpectedly found nil while unwrapping an Optional value
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forkey: "courseworkname")
attribute.setValue(dueDateLabel.text, forkey: "duedate")
attribute.setValue(level.text, forkey: "level")
attribute.setValue(mark.text, forkey: "mark")
attribute.setValue(modulename.text, forkey: "modulename")
attribute.setValue(notes.text, forkey: "notes")
attribute.setValue(progressbar.text, forkey: "progressbar")
attribute.setValue(reminder.text, forkey: "reminder")
attribute.setValue(value.text, forkey: "value")
try manageContext.save()
}catch let error as NSError {
}
}
Full code:
#IBOutlet weak var detailDescriptionLabel: UILabel!
#IBOutlet weak var dueDateLabel: UITextField!
#IBOutlet weak var value: UITextField!
#IBOutlet weak var courseworkname: UITextField!
#IBOutlet weak var modulename: UITextField!
#IBOutlet weak var level: UITextField!
#IBOutlet weak var mark: UITextField!
#IBOutlet weak var reminder: UITextField!
#IBOutlet weak var notes: UITextField!
#IBAction func edit(sender: AnyObject) {
modulename.userInteractionEnabled = true
modulename.enabled = true
dueDateLabel.userInteractionEnabled = true
value.userInteractionEnabled = true
modulename.userInteractionEnabled = true
level.userInteractionEnabled = true
mark.userInteractionEnabled = true
reminder.userInteractionEnabled = true
notes.userInteractionEnabled = true
//Interaction
value.enabled = true
dueDateLabel.enabled = true
courseworkname.enabled = true
modulename.enabled = true
level.enabled = true
mark.enabled = true
reminder.enabled = true
notes.enabled = true
}
#IBAction func update(sender: AnyObject) {
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let manageContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Coursework")
do {
let results = try manageContext.executeFetchRequest(fetchRequest)
let attribute = results[0] as! NSManagedObject
detailItem?.value = modulename.text
attribute.setValue(courseworkname.text, forKey: "courseworkname")
attribute.setValue(dueDateLabel.text, forKey: "duedate")
attribute.setValue(level.text, forKey: "level")
attribute.setValue(mark.text, forKey: "mark")
attribute.setValue(modulename.text, forKey: "modulename")
attribute.setValue(notes.text, forKey: "notes")
attribute.setValue(progressbar.text, forKey: "progressbar")
attribute.setValue(reminder.text, forKey: "reminder")
attribute.setValue(value.text, forKey: "value")
try manageContext.save()
}catch let error as NSError{
}
}
var detailItem: Coursework?
var detailItem2: Task?
{
didSet {
// Update the view.
self.configureView()
}
}
func configureView() {
// Update the user interface for the detail item.
if let detail = self.detailItem {
if let label = self.detailDescriptionLabel {
label.text = detail.courseworkname
}
if let label = self.dueDateLabel {
label.text = detail.duedate
}
if let label = self.value {
label.text = detail.value
}
if let label = self.courseworkname {
label.text = detail.courseworkname
}
if let label = self.modulename {
label.text = detail.modulename
}
if let label = self.level {
label.text = detail.level
}
if let label = self.mark {
label.text = detail.mark
}
if let label = self.reminder{
label.text = detail.reminder
}
if let label = self.notes{
label.text = detail.notes
}
}
Is it a new attribute? You have to uninstall and reinstall the app when you're changing your CoreData models.
Also just saw that you don't have an IBOutlet defined for progressbar, if you link it it should work.

Trying to multiply a variable from a slider to a NSTimer variable.

I made a timer and then I added a slider with a label that presented its value. What I want to do is have my last label (Moneyadded) show a multiplication of the slider value by the current amount of seconds with NStimer.
import UIKit
class ViewController: UIViewController {
var timercount = 0
var timerRunning = false
var timer = NSTimer()
var myVaribale: Int = 0
override func viewDidLoad() {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
// fired once a second
myVaribale += 258
}
#IBOutlet weak var timerlabel: UILabel!
func counting(){
timercount += 1
timerlabel.text = "\(timercount)"
var timerValue = timercount.value
}
#IBAction func Clockin(sender: UIButton) {
if timerRunning == false{
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: Selector("counting"), userInfo: nil, repeats: true)
timerRunning = true
}
}
#IBAction func Clockout(sender: UIButton) {
if timerRunning == true{
timer.invalidate()
timerRunning = false
}
}
#IBAction func Restart(sender: UIButton) {
timercount = 0
timerlabel.text = "0"
}
#IBOutlet weak var Slider: UISlider!
#IBOutlet weak var Label: UILabel!
#IBAction func valuechanged(sender: UISlider) {
var currentValue = Int(Slider.value)
Label.text = "\(currentValue)"
}
#IBOutlet weak var Moneyadded: UILabel!
\\this is for the label (text) that I want the NStimer to be multiplied by the slider value.
Change your counting function to the following:
/** Gets triggered once every second */
func counting(){
timercount += 1
timerlabel.text = "\(timercount)"
Moneyadded.text = "\(timercount * Int(Slider.value))"
}

Resources