Improving on the iOS Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for iOS from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing or enters something other than numbers (such as a letter or other character)? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all. This is something known as data validation.

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

Sample code

Here is the new and improved code for the ViewController.cs file.

// need to add using System; line to access math functions
using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      //  Create a button touch event for the Convert to Celsius button
      cButton.TouchUpInside+= CButton_TouchUpInside;
      //  Create a button touch event for the Convert to Fahrenheit button
      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultLabel.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultLabel.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}