UISwitch saving values to use in a function - swift

When the user turns switch on, I would like a random value to display on a UILabel, then take that same random value, and use it to multiply and find another value. I think my problem is that I am trying to use a let statement to hold the value, then trying to call back to that let value from another function, but I don't know another way to to this.
I already can get the random value to appear on a UILabel after the switch is active. Then when the switch is not active, a value of 0 is left on the UILabel.
The IBOutlet for the switch:
#IBOutlet weak var tipSwitch: UISwitch!
This is the action for the switch:
#IBAction func switchChanged(_ sender: UISwitch) {
if sender.isOn{
sender.setOn(false, animated: true)
percentPlaceholder.text! = String(0) + "%"
}
else{
sender.setOn(true, animated: true)
let randomTip = Int.random(in: 1...100)
percentPlaceholder.text! = String(randomTip)
calculateTipSwitch()
}
}
This is the calculateTipSwitch function:
func calculateTipSwitch() {
var tipAmountSwitch = Float()
var totalCostSwitch = Float()
if let billAmountSwitch = Float(billCost.text!) {
tipAmountSwitch = billAmountSwitch * randomTip / 100
totalCostSwitch = tipAmountSwitch + billAmountSwitch
}
else {
tipAmountSwitch = 0
totalCostSwitch = 0
}
tipDollarAmt.text! = String(format: "%.2f", tipAmountSwitch)
totalBill.text! = String(format: "%.2f", totalCostSwitch)
}
Here is all of my code if you want a better understanding of what I'm trying to accomplish:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var billCost: UITextField!
#IBOutlet weak var percentPlaceholder: UILabel!
#IBOutlet weak var tipDollarAmt: UILabel!
#IBOutlet weak var totalBill: UILabel!
#IBOutlet weak var tipSlider: UISlider!
#IBOutlet weak var tipSegment: UISegmentedControl!
#IBOutlet weak var tipStepper: UIStepper!
#IBOutlet weak var tipSwitch: UISwitch!
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let allowed = CharacterSet(charactersIn: ".1234567890")
return string.rangeOfCharacter(from: allowed) != nil
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
billCost.resignFirstResponder()
return true
}
override func viewDidLoad() {
super.viewDidLoad()
percentPlaceholder.text = ""
tipDollarAmt.text = ""
totalBill.text = ""
}
#IBAction func sliderChanged(_ sender: UISlider) {
percentPlaceholder.text! = String(Int(sender.value)) + "%"
tipStepper.value = Double(Int(tipSlider.value))
calculateTip()
}
#IBAction func selectorChanged(_ sender: UISegmentedControl) {
}
#IBAction func stepperChanged(_ sender: UIStepper) {
percentPlaceholder.text! = String(sender.value) + "%"
tipSlider.value = Float(tipStepper.value)
calculateTipStep()
}
#IBAction func switchChanged(_ sender: UISwitch) {
if sender.isOn{
sender.setOn(false, animated: true)
percentPlaceholder.text! = String(0) + "%"
}
else{
sender.setOn(true, animated: true)
let randomTip = Int.random(in: 1...100)
percentPlaceholder.text! = String(randomTip)
}
}
func calculateTip()
{
var tipAmount = Float()
var totalCost = Float()
if let billAmount = Float(billCost.text!) {
tipAmount = billAmount * tipSlider.value / 100
totalCost = tipAmount + billAmount
}
else {
tipAmount = 0
totalCost = 0
}
tipDollarAmt.text! = String(format: "%.2f", tipAmount)
totalBill.text! = String(format: "%.2f", totalCost)
}
func calculateTipStep() {
var tipAmountStep = Float()
var totalCostStep = Float()
if let billAmountStep = Float(billCost.text!) {
tipAmountStep = billAmountStep * Float(tipStepper.value) / 100
totalCostStep = tipAmountStep + billAmountStep
}
else {
tipAmountStep = 0
totalCostStep = 0
}
tipDollarAmt.text! = String(format: "%.2f", tipAmountStep)
totalBill.text! = String(format: "%.2f", totalCostStep)
}
func calculateTipSwitch() {
var tipAmountSwitch = Float()
var totalCostSwitch = Float()
if let billAmountSwitch = Float(billCost.text!) {
tipAmountSwitch = billAmountSwitch * randomTip / 100
totalCostSwitch = tipAmountSwitch + billAmountSwitch
}
else {
tipAmountSwitch = 0
totalCostSwitch = 0
}
tipDollarAmt.text! = String(format: "%.2f", tipAmountSwitch)
totalBill.text! = String(format: "%.2f", totalCostSwitch)
}
}
Basically my problem is that I can't use that random number in another function, so I just need help on how to call back to that randomTip.

You can add a parameter to calculateTipSwitch, and pass the random number as an argument to the calculateTipSwitch method. Change calculateTipSwitch to:
func calculateTipSwitch(tipPercentage: Int) {
var tipAmountSwitch = Float()
var totalCostSwitch = Float()
if let billAmountSwitch = Float(billCost.text!) {
tipAmountSwitch = billAmountSwitch * tipPercentage / 100.0
totalCostSwitch = tipAmountSwitch + billAmountSwitch
}
else {
tipAmountSwitch = 0
totalCostSwitch = 0
}
tipDollarAmt.text! = String(format: "%.2f", tipAmountSwitch)
totalBill.text! = String(format: "%.2f", totalCostSwitch)
}
Then, in switchChanged:
let randomTip = Int.random(in: 1...100)
percentPlaceholder.text! = String(randomTip)
calculateTipSwitch(tipPercentage: randomTip)

In the switchChanged() function , you set the randomTip to percentPlaceholder.text , so in the other functions , you could just call for it.
let randomTip = percentPlaceholder.text
Or another way to do this, is to declare the randomTip variable outside the function, as a property of the class.
class ViewController : UIViewController {
//IBOutlets here
var randomTip : String?
//functions here
}
Then when you set a value to it in switchChanged(), it can be called in the other functions.

Related

How to save user preference of dark or light mode

I have these buttons in my app so user can switch from light to dark mode in the app, how can I save this preference so whichever mode the user selected will still be active the next time they open the app?
I'm on Xcode 14.2
Code example please.
#IBAction func darkButton(_ sender: Any) {
overrideUserInterfaceStyle = .dark
}
#IBAction func lightButton(_ sender: Any) {
overrideUserInterfaceStyle = .light
}
Full code below
import UIKit
class ViewController: UIViewController {
// All Input Texts
#IBOutlet weak var machineODInputText: UITextField!
#IBOutlet weak var pipeODInputText: UITextField!
#IBOutlet weak var pipeLengthInputText: UITextField!
#IBOutlet weak var driveLengthInputText: UITextField!
#IBOutlet weak var muckUpInputText: UITextField!
#IBOutlet weak var jackingSpeedInputText: UITextField!
#IBOutlet weak var weightOfBenoBagInputText: UITextField!
#IBOutlet weak var noOfBenoBagsInputText: UITextField!
#IBOutlet weak var benoQtyForTanksInputText: UITextField!
#IBOutlet weak var noOfBenoBagsPerPalletInputText: UITextField!
// All Result Texts
#IBOutlet weak var lubricationPumpSpeedResult: UILabel!
#IBOutlet weak var volumePerMeterResult: UILabel!
#IBOutlet weak var volumePerPipeResult: UILabel!
#IBOutlet weak var volumeForDriveResult: UILabel!
#IBOutlet weak var benoQtyForLubricationResult: UILabel!
#IBOutlet weak var benoQtyForDriveResult: UILabel!
#IBOutlet weak var noOfPalletsForDriveResult: UILabel!
// All Buttons
#IBAction func lightButton(_ sender: Any) {
overrideUserInterfaceStyle = .light
UserDefaults.standard.set("light", forKey: "mode")
}
#IBAction func darkButton(_ sender: Any) {
overrideUserInterfaceStyle = .dark
UserDefaults.standard.set("dark", forKey: "mode")
}
#IBAction func calculateButton(_ sender: Any) {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.maximumFractionDigits = 0
let formatter2 = NumberFormatter()
formatter2.numberStyle = .decimal
formatter2.maximumFractionDigits = 2
let pi = Double.pi / 4
let TBMOD = (Double(machineODInputText.text!) ?? 1) / 1000.0
let pipeOD = (Double(pipeODInputText.text!) ?? 1) / 1000.0
let muckup = (Double(muckUpInputText.text!) ?? 2.5)
let advanceSpeed = (Double(jackingSpeedInputText.text!) ?? 1)
let volPerPipe = (Double(pipeLengthInputText.text!) ?? 1)
let volForDrive = (Double(driveLengthInputText.text!) ?? 1)
let noOfBenoBagsForLub = (Double(noOfBenoBagsInputText.text!) ?? 1)
let weightOfEachBenoBag = (Double(weightOfBenoBagInputText.text!) ?? 1)
let amountOfBenoBagsInTamks = (Double(benoQtyForTanksInputText.text!) ?? 1)
let noOfBenoBagsPerPallet = (Double(noOfBenoBagsPerPalletInputText.text!) ?? 1)
// Calculate Volume per Meter (Ltr per meter)
let volPerMtrResults1 = ((pi * (TBMOD) * (TBMOD)) - (pi * (pipeOD) * (pipeOD))) * muckup * 1000
let volPerMtrResult = formatter.string (from: NSNumber(value: volPerMtrResults1))
volumePerMeterResult.text = volPerMtrResult
// Calculate Lubrication Pump Capacity (Ltr per min)
let pumpCapacityResults1 = (advanceSpeed / 1000) * volPerMtrResults1
let lubPerMtrResult = formatter.string(from: NSNumber(value: pumpCapacityResults1))
lubricationPumpSpeedResult.text = lubPerMtrResult
// Calculate Volume per pipe (M³ per pipe)
let volPerPipeResults1 = (volPerMtrResults1 / 1000) * volPerPipe
let volPerPipeResult = formatter2.string(from: NSNumber(value: volPerPipeResults1))
volumePerPipeResult.text = volPerPipeResult
// Calculate Volume for drive (M³ for drive)
let volPerDriveResults1 = (volPerMtrResults1 / 1000) * volForDrive
let volPerDriveResult = formatter.string(from: NSNumber(value: volPerDriveResults1))
volumeForDriveResult.text = volPerDriveResult
// Calculate Amount of beno for lubrication
let ammountOfBenoForLubResults1 = noOfBenoBagsForLub * volPerDriveResults1 * weightOfEachBenoBag
let ammountOfBenoForLubResult = formatter.string(from: NSNumber(value: ammountOfBenoForLubResults1))
benoQtyForLubricationResult.text = ammountOfBenoForLubResult
// Calculate beno quantity for drive
let amountOfBenoForDriveResults1 = ammountOfBenoForLubResults1 + (amountOfBenoBagsInTamks * 1000)
let amountOfBenoForDriveResult = formatter.string(from: NSNumber(value: amountOfBenoForDriveResults1))
benoQtyForDriveResult.text = amountOfBenoForDriveResult
// Calculate number of pallets for drive
let ammountOfBenoPerPalletResults1 = amountOfBenoForDriveResults1 / weightOfEachBenoBag / noOfBenoBagsPerPallet
let ammountOfBenoPerPalletResult = formatter2.string(from: NSNumber(value: ammountOfBenoPerPalletResults1))
noOfPalletsForDriveResult.text = ammountOfBenoPerPalletResult
UserDefaults.standard.set(machineODInputText.text, forKey: "TBMOD")
UserDefaults.standard.set(pipeODInputText.text, forKey: "pipeOD")
UserDefaults.standard.set(muckUpInputText.text, forKey: "muckUp")
UserDefaults.standard.set(jackingSpeedInputText.text, forKey: "speed")
UserDefaults.standard.set(pipeLengthInputText.text, forKey: "pipeLength")
UserDefaults.standard.set(driveLengthInputText.text, forKey: "driveLength")
UserDefaults.standard.set(noOfBenoBagsInputText.text, forKey: "noOfBenoBags")
UserDefaults.standard.set(weightOfBenoBagInputText.text, forKey: "weightOfBenoBag")
UserDefaults.standard.set(benoQtyForTanksInputText.text, forKey: "benoQtyForTanks")
UserDefaults.standard.set(noOfBenoBagsPerPalletInputText.text, forKey: "benoBagsPerPallet")
}
// Adding toolbar to top of keyboard with "Done" button (toolbar.swift file)
override func viewDidLoad() {
super.viewDidLoad()
machineODInputText.inputAccessoryView = toolBar()
pipeODInputText.inputAccessoryView = toolBar()
pipeLengthInputText.inputAccessoryView = toolBar()
driveLengthInputText.inputAccessoryView = toolBar()
muckUpInputText.inputAccessoryView = toolBar()
jackingSpeedInputText.inputAccessoryView = toolBar()
weightOfBenoBagInputText.inputAccessoryView = toolBar()
noOfBenoBagsInputText.inputAccessoryView = toolBar()
benoQtyForTanksInputText.inputAccessoryView = toolBar()
noOfBenoBagsPerPalletInputText.inputAccessoryView = toolBar()
}
// load old data into input feilds
override func viewDidAppear(_ animated: Bool) {
if let a = UserDefaults.standard.object(forKey: "TBMOD") as? String {
machineODInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "pipeOD") as? String {
pipeODInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "muckUp") as? String {
muckUpInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "speed") as? String {
jackingSpeedInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "pipeLength") as? String {
pipeLengthInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "driveLength") as? String {
driveLengthInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "noOfBenoBags") as? String {
noOfBenoBagsInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "weightOfBenoBag") as? String {
weightOfBenoBagInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "benoQtyForTanks") as? String {
benoQtyForTanksInputText.text = a
}
if let a = UserDefaults.standard.object(forKey: "benoBagsPerPallet") as? String {
noOfBenoBagsPerPalletInputText.text = a
}
// load dark/light mode last selected by user
let mode = UserDefaults.standard.string(forKey: "mode")
if mode == "dark" {
overrideUserInterfaceStyle = .dark
} else {
overrideUserInterfaceStyle = .light
}
machineODInputText.clearsOnBeginEditing = true
pipeODInputText.clearsOnBeginEditing = true
pipeLengthInputText.clearsOnBeginEditing = true
driveLengthInputText.clearsOnBeginEditing = true
muckUpInputText.clearsOnBeginEditing = true
jackingSpeedInputText.clearsOnBeginEditing = true
weightOfBenoBagInputText.clearsOnBeginEditing = true
noOfBenoBagsInputText.clearsOnBeginEditing = true
benoQtyForTanksInputText.clearsOnBeginEditing = true
noOfBenoBagsPerPalletInputText.clearsOnBeginEditing = true
}
}
you can save it in UserDefaults as follows.
#IBAction func darkButton(_ sender: Any) {
overrideUserInterfaceStyle = .dark
UserDefaults.standard.set("dark", forKey: "mode")
}
#IBAction func lightButton(_ sender: Any) {
overrideUserInterfaceStyle = .light
UserDefaults.standard.set("light", forKey: "mode")
}
When reopening the application do as follow.
let mode = UserDefaults.standard.string(forKey: "mode")
if mode == "dark" {
overrideUserInterfaceStyle = .dark
} else {
overrideUserInterfaceStyle = .light
}
Where you need to add the above code depends on your scenario. I suggest to add it inside AppDelegate -> didFinishLaunchingWithOptions.

Saving HighScore in Swift 4

This code has all my labels Im trying to use. I can't save the High score and implement it into the game. Now its saying I need to type more so i'm just going to keep typing until it tells me i'm good. It still hasn't told me i'm goo i'm actually very surprised wow.
import UIKit
import CoreData
import SpriteKit
var timer:Timer?
var seconds:Int = 5
var maxSeconds: Int = 5
var totalPoints:Int = 0
var high:Int = 0
let userDefaults = UserDefaults.standard
let defaults = UserDefaults.standard
class ViewController: UIViewController {
#IBOutlet weak var menu: UIButton!
var i = 0
var point = 0
#IBOutlet weak var highScore: UILabel!
#IBOutlet weak var timeLabel:UILabel?
#IBOutlet weak var points:UILabel?
#IBOutlet weak var totalPoint: UILabel!
#objc func tapped(){
i += 1
switch i {
case 1:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.error)
case 2:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.success)
case 3:
let generator = UINotificationFeedbackGenerator()
generator.notificationOccurred(.warning)
case 4:
let generator = UIImpactFeedbackGenerator(style: .light)
generator.impactOccurred()
case 5:
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.impactOccurred()
case 6:
let generator = UIImpactFeedbackGenerator(style: .heavy)
generator.impactOccurred()
default:
let generator = UISelectionFeedbackGenerator()
generator.selectionChanged()
i = 0
}
}
func updateTimeLabel()
{
if(timeLabel != nil)
{
let sec:Int = seconds % 30
let sec_p:String = String(format: "%02d", sec)
timeLabel!.text = "\(sec_p)"
}
}
#objc func onUpdateTimer() -> Void
{
if(seconds > 0 && seconds <= maxSeconds)
{
seconds -= 1
updateTimeLabel()
}
else if(seconds == 0)
{
if(timer != nil)
{
timer!.invalidate()
timer = nil
userDefaults.set(totalPoints, forKey: "totalPoints")
let alertController = UIAlertController(title: "Time Up!", message: "Your time is up! You got a score of \(point) points and your total coins now is \(totalPoints). You Can Do Better", preferredStyle: .alert)
let restartAction = UIAlertAction(title: "Play Again!", style: .default, handler: nil)
alertController.addAction(restartAction)
let FirstSubview = alertController.view.subviews.first
let AlertContentView = FirstSubview?.subviews.first
for subview in (AlertContentView?.subviews)! {
subview.backgroundColor = UIColor(red: 226/255.0, green: 158/255.0, blue: 152/255.0, alpha: 5.0)
subview.layer.cornerRadius = 1
subview.alpha = 1
}
self.present(alertController, animated: true, completion: nil)
point = 0
seconds = maxSeconds
updateTimeLabel()
menu.isHidden = false
defaults.set(high, forKey: "high")
}
}
}
#IBAction func Restart(_ sender: Any) {
}
#IBAction func adder(_ sender: Any)
{
point += 1
points?.text = "\(point)"
if point % 10 == 0 {
totalPoints = 10 + totalPoints
totalPoint?.text = String(totalPoints)
}
if(timer == nil)
{
timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector:#selector(onUpdateTimer), userInfo:nil, repeats:true)
}
tapped()
menu.isHidden = true
}
override func viewDidLoad() {
points?.text = "\(point)"
let total = userDefaults.integer(forKey: "totalPoints")
if total != 0 {
totalPoints = total
} else {
totalPoints = 0
}
let score = defaults.integer(forKey: "high")
if high < point {
high = score
} else {
high = 0
}
totalPoint?.text = String(totalPoints)
updateTimeLabel()
highScore.text = String(high)
}
}
Do I need to put something at the end? Well it looks like that didn't work either!
#for example
func saveHighScore() {
UserDefaults.standard.set(score, forKey: "HIGHSCORE")
}

Swift ViewController Crashes on Load

I'm making a multi conversion tool in iOS to build up my portfolio. However, the distance tab will not load the view. It instantly crashes and gives me two errors.
The second one appears when I try to continue. Below are the errors and my Swift class tied to the controller as well as what the app looks like.
errors
import UIKit
class DistanceViewController: UIViewController, UITextFieldDelegate{
#IBOutlet var userDistance: UITextField!
#IBOutlet var resultLabel: UILabel!
var fromKilometerValue: Measurement<UnitLength>?{
didSet{
milesConversion()
}
}
var fromMileValue: Measurement<UnitLength>?{
didSet{
kilometerConversion()
}
}
override func viewDidLoad() {
super.viewDidLoad()
milesConversion()
kilometerConversion()
}
//Dont forget to drag a gesture recognizer
#IBAction func dismissKeyboard(_sender: UITapGestureRecognizer){
userDistance.resignFirstResponder()
}
let numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.numberStyle = .decimal
nf.minimumFractionDigits = 1
nf.maximumFractionDigits = 1
return nf
}()
func textField(_ userDistance: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String) -> Bool {
let existingTextHasDecimalSeparator = userDistance.text?.range(of: ".")
let replacementTextHasDecimalSeparator = string.range(of: ".")
if existingTextHasDecimalSeparator != nil,
replacementTextHasDecimalSeparator != nil {
return false
} else {
return true
}
}
var toMileValue: Measurement<UnitLength>?{
if let fromKilometerValue = fromKilometerValue{
return fromKilometerValue.converted(to: .miles)
}
else{
return nil
}
}
var toKilometerValue: Measurement<UnitLength>?{
if let fromMileValue = fromMileValue{
return fromMileValue.converted(to: .kilometers)
}
else{
return nil
}
}
func milesConversion(){
if let toMileValue = toMileValue {
resultLabel.text = numberFormatter.string(from: NSNumber(value: Double(userDistance.text!)!))! + " km" + " is " + numberFormatter.string(from: NSNumber(value: toMileValue.value))! + " miles"
}
}
func kilometerConversion(){
if let toKilometerValue = toKilometerValue{
resultLabel.text = numberFormatter.string(from: NSNumber(value: Double(userDistance.text!)!))! + " miles" + " is " + numberFormatter.string(from: NSNumber(value: toKilometerValue.value))! + " km"
}
}
#IBAction func convertKilometers(_ sender: Any) {
if let input = userDistance.text, let value = Double(input) {
fromKilometerValue = Measurement(value: value, unit: .kilometers)
} else {
fromKilometerValue = nil
}
if(toMileValue == nil){
resultLabel.text = "Unable to Convert " + userDistance.text!
}
}
#IBAction func convertMiles(_ sender: Any) {
if let input = userDistance.text, let value = Double(input) {
fromMileValue = Measurement(value: value, unit: .miles)
} else {
fromMileValue = nil
}
if(toKilometerValue == nil){
resultLabel.text = "Unable to Convert " + userDistance.text!
}
}
}
The class and view are mapped properly from what I see. Anybody have any idea?
EDIT: i had old connections that didnt exist in Main.storyboard, i removed them and the view loads just fine!
Check all of your outlet connections. And read stackoverflow.com/questions/32170456/… – rmaddy

App Only Crashes for Iphone 6 and IPad in IOS 11 using Vision & Machine Learning API

I made a live translation app that identifies an object and translates it using the user's camera. It works just fine on my iPhone 6s and doesn't crash in any of the simulators, but when I run it on an iPhone 6, it crashes as soon I try to segue to the camera feed. Apple also says it crashes on the iPad as well.
Do certain devices just not support Vision API or is something wrong with my code?
import UIKit
import AVKit
import Vision
var lang = ""
var lang2 = ""
class ViewController: UIViewController, AVCaptureVideoDataOutputSampleBufferDelegate, AVCapturePhotoCaptureDelegate {
#IBAction func screenshotB(_ sender: Any) {
//screenshot camera screen view
}
#IBOutlet weak var screenshotBOutlet: UIButton!
#IBOutlet weak var swirlyGuy: UIActivityIndicatorView!
#IBOutlet weak var title1: UILabel!
#IBOutlet weak var settingsButtonOutlet: UIButton!
#IBOutlet weak var launchScreen: UIViewX!
#IBOutlet weak var launchScreenLogo: UIImageView!
func stopSwirlyGuy(){
swirlyGuy.stopAnimating()
}
let identifierLabel: UILabel = {
let label = UILabel()
label.backgroundColor = UIColor(red: 0, green: 0, blue:0, alpha: 0.4)
label.textColor = .white
label.textAlignment = .center
label.translatesAutoresizingMaskIntoConstraints = false
return label
}()
#IBAction func prepareForUnwind (segue:UIStoryboardSegue) {
}
override func viewDidLoad() {
super.viewDidLoad()
launchScreen.alpha = 1
launchScreenLogo.alpha = 1
swirlyGuy.startAnimating()
// start up the camera
let captureSession = AVCaptureSession()
captureSession.sessionPreset = .hd4K3840x2160
guard let captureDevice = AVCaptureDevice.default(for: .video) else { return }
guard let input = try? AVCaptureDeviceInput(device: captureDevice) else { return }
captureSession.addInput(input)
captureSession.startRunning()
let previewLayer = AVCaptureVideoPreviewLayer(session: captureSession)
view.layer.addSublayer(previewLayer)
previewLayer.frame = view.frame
let dataOutput = AVCaptureVideoDataOutput()
dataOutput.setSampleBufferDelegate(self, queue: DispatchQueue(label: "videoQueue"))
captureSession.addOutput(dataOutput)
setupIdentifierConfidenceLabel()
setupSettingsButton()
setupTitle()
setupSwirlyGuy()
setupScreenshot()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5) {
self.launchScreen.alpha = 0
self.launchScreenLogo.alpha = 0
}
}
fileprivate func setupSettingsButton() {
view.addSubview(settingsButtonOutlet)
}
fileprivate func setupScreenshot() {
view.addSubview(screenshotBOutlet)
}
fileprivate func setupSwirlyGuy() {
view.addSubview(swirlyGuy)
}
fileprivate func setupTitle() {
view.addSubview(title1)
}
fileprivate func setupIdentifierConfidenceLabel() {
view.addSubview(identifierLabel)
identifierLabel.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
identifierLabel.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
identifierLabel.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
identifierLabel.heightAnchor.constraint(equalToConstant: 100).isActive = true
identifierLabel.numberOfLines = 0
}
func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
// print("Camera was able to capture a frame:", Date())
guard let pixelBuffer: CVPixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
// model
guard let model = try? VNCoreMLModel(for: Resnet50().model) else { return }
let request = VNCoreMLRequest(model: model) { (finishedReq, err) in
//perhaps check the err
// print(finishedReq.results)
guard let results = finishedReq.results as? [VNClassificationObservation] else { return }
guard let firstObservation = results.first else { return }
print(firstObservation.identifier, firstObservation.confidence)
let x = (firstObservation.confidence)
let y = (x * 10000).rounded() / 10000
let z = (firstObservation.identifier)
let s = (self.translateSpanish(object1: firstObservation.identifier))
let f = (self.translateFrench(object1: firstObservation.identifier))
// var lang = ""
// var lang2 = ""
if language == "English" {
lang = z
}
else if language == "Spanish" {
lang = s
}
else {
lang = f
}
if language2 == "Spanish" {
lang2 = s
}
else if language2 == "English" {
lang2 = z
}
else {
lang2 = f
}
DispatchQueue.main.async {
self.identifierLabel.text = "\(lang)" + " = " + "\(lang2) \n \(y * 100)% accuracy"
self.stopSwirlyGuy()
}
}
try? VNImageRequestHandler(cvPixelBuffer: pixelBuffer, options: [:]).perform([request])
}
//Translation fucntions omitted for brevity
This is the code for the view controller that segues into the main screen where the camera feed and Vision processing take place.
import UIKit
class FirstLaunchViewController: UIViewController {
#IBOutlet weak var title1: UILabelX!
#IBOutlet weak var logo1: UIImageView!
#IBOutlet weak var description1: UILabel!
#IBOutlet weak var buttonOutlet: UIButtonX!
#IBOutlet weak var initialBackground: UIViewX!
#IBOutlet weak var initialLogo: UIImageView!
#IBAction func toVC(_ sender: Any) {
UserDefaults.standard.set(false, forKey: "name")
performSegue(withIdentifier: "toMain", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
initialLogo.alpha = 1
initialBackground.alpha = 1
title1.alpha = 0
logo1.alpha = 0
description1.alpha = 0
buttonOutlet.alpha = 0
// Do any additional setup after loading the view.
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
UIView.animate(withDuration: 1.5, animations: {
self.initialLogo.alpha = 0
self.initialBackground.alpha = 0
}) { (true) in
self.initialBackgroundGone()
}
}
func initialBackgroundGone() {
UIView.animate(withDuration: 1.5, animations: {
self.title1.alpha = 1
}) { (true) in
self.showBackgroundAgain()
}
}
func showBackgroundAgain() {
UIView.animate(withDuration: 1.3, animations: {
self.logo1.alpha = 1
}) { (true) in
self.showTitle()
}
}
func showTitle() {
UIView.animate(withDuration: 1.5, animations: {
self.description1.alpha = 1
}) { (true) in
self.showEverythingElse()
}
}
func showEverythingElse() {
UIView.animate(withDuration: 3.5) {
self.buttonOutlet.alpha = 1
}
}
}
This is a lot of code but I think your issue comes from the video preset your are using as iPhone 6 doesn't have support for 4K video recording.
When setting the session preset you should test that it is supported by all the targeted devices:
if captureSession.canSetSessionPreset(.hd4K3840x2160) {
captureSession.sessionPreset = .hd4K3840x2160
} else {
captureSession.sessionPreset = .high // or any other preset that suits your needs
}

Image appear when timer is at 1

im making a reaction time app, and I have a label set to count with Seconds. I want to make my image appear when the label is at 1 second, but it doesn't appear. The timer works fine, just the image. Help me in swift please.
import UIKit
class timerViewController: UIViewController {
var go = NSTimeInterval()
var timer = NSTimer()
#IBOutlet weak var tapStop: UIImageView!
#IBOutlet weak var displayTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
if displayTimer.text == "00:01:00"{
tapStop.image = UIImage(named: "carcrash")
}
}
#IBAction func stop(sender: UIButton) {
timer.invalidate()
}
#IBAction func start(sender: UIButton) {
if (!timer.valid) {
let test:Selector = "updateTime"
timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: test, userInfo: nil, repeats: true)
go = NSDate.timeIntervalSinceReferenceDate()
}
}
func updateTime(){
var timeNow = NSDate.timeIntervalSinceReferenceDate()
var pass: NSTimeInterval = timeNow - go
let minutes1 = UInt8(pass / 60.0)
pass -= (NSTimeInterval(minutes1) * 60)
let seconds1 = UInt8(pass)
pass -= NSTimeInterval(seconds1)
let milli1 = UInt8(pass * 100)
let minutes2 = String(format: "%02d", minutes1)
let seconds2 = String(format: "%02d", seconds1)
let milli2 = String(format: "%02d", milli1)
displayTimer!.text = "\(minutes2):\(seconds2):\(milli2)"
}
}
You should put this:
if displayTimer.text == "00:01:00"{
tapStop.image = UIImage(named: "carcrash")
}
in your func updateTime() instead of viewDidLoad(), and put them into main thread, so that your image will be updated on the UI. Your func updateTime() will look like this:
func updateTime(){
var timeNow = NSDate.timeIntervalSinceReferenceDate()
var pass: NSTimeInterval = timeNow - go
let minutes1 = UInt8(pass / 60.0)
pass -= (NSTimeInterval(minutes1) * 60)
let seconds1 = UInt8(pass)
pass -= NSTimeInterval(seconds1)
let milli1 = UInt8(pass * 100)
let minutes2 = String(format: "%02d", minutes1)
let seconds2 = String(format: "%02d", seconds1)
let milli2 = String(format: "%02d", milli1)
displayTimer!.text = "\(minutes2):\(seconds2):\(milli2)"
if displayTimer.text == "00:01:00"{
dispatch_async(dispatch_get_main_queue(),{
tapStop.image = UIImage(named: "carcrash")
})
}
}