Introduction: How to Create a Simple Timer Application for IOS

Have you ever wanted to create an iOS application but didn't know where to start? Are you interested in making an application that can be used in your everyday life, rather then something that says ‘Hello World’? Well this set of instructions is for you!

This will take you through the steps of creating a basic timer application that allows you to set a timer, with functionality for pausing, resuming, and stopping that timer. The best part is, you can complete these steps with little to no knowledge of developing for iOS!

To complete this project you will only need 2 things:

  • A Mac computer
  • An internet connection if you don’t already have the Xcode IDE downloaded to your Mac.

And that’s it! You’ll be on your way to creating your very own application in no time.

Step 1: Downloading Xcode

Note: Xcode will be the development environment used to create iOS and Mac applications, and will be the application used in this guide. If you already have Xcode downloaded to your Mac, you can skip to step 2.

1A. Open the App Store application.

Note: To have the App Store application, you will need at least Mac OS X 10.6.8, however to download the latest version of Xcode you will need OS X 10.9.4.

1B. Search for ‘Xcode’ in the search bar at the top right.

1C. Select the first application that appears in the search results.

Note: This will be a free download, and can take some time to complete.

Step 2: Setting Up the Project

Note: In this step we will set up the initial project that we will be creating the timer application in.

2A. Open Xcode and select the ‘Create a new Xcode project’ option.

Note: On the next screen you will be given a variety of options on what type of application you would like to create.

2B. Select the ‘Single View Application’ option.

Note: There are a variety of initial templates that you can choose to create, however for the purposes of this project, we will want to select the Single View application.

2C. Name the project ‘Simple Timer’

Note: You can give the project any name you’d like. If you will eventually be publishing an application to the App Store, you will need to add an organization name and identifier. Publishing to the App Store will be outside the scope of what we are doing, so you can refer to Apple’s documentation for any other questions

2D. Click ‘Next’ to create the project.

Step 3: Creating the Interface

Note: In this step we will be creating the user interface for the timer. This will include the time picker, as well as the Start, Stop and Pause buttons.

3A. Click on the Main.storyboard file to open it up.

Note: In your project, you will be given files that are created automatically. The only file that we will be working with in this step is the Main.storyboard file. In short, this file allows us to drag-and-drop interface objects that can later be connected to our code.

3B. Drag-and-drop the ‘Date Picker’ interface object from the list of interface items in the bottom right corner of the Xcode to the storyboard window.

See the above images.

3C. Add the ‘Date Picker’ object to the top of the screen. Click on the icon at the bottom of the Xcode window that looks like a triangle between to vertical lines, then click on the ‘Add Missing Constraints’ option.

Note: You can position the ‘Date Picker’ object anywhere on the screen that you’d like. Constraints will make sure our Date Picker object fits correctly on different size iPhone screens.

3D. Click on the Date Picker object, then open the Attributes tab in the top right hand corner of the Xcode window.

Note: The Attributes tab will be the option directly to the left of the icon that looks like a ruler.

3E. Change the Mode option to Count Down Timer, and make sure the Interval option is set to 1 Minute.

3F. Drag the interface object labeled ‘Button’ onto your storyboard. Once it is added to your storyboard, change the Title option of the button to ‘Start’ from the Attributes tab.

Note: This button will also be our ‘Stop’ button, and we will code that feature later. The ‘Button’ object will be located in the same area as our Date Picker object. The Attributes tab will also be located in the same position as with our Date Picker object. You can change a variety of other settings for our button, including using your own custom button. However for the purposes of this project, we will be using the default System button.

3G. Drag another button to your storyboard, just as we did with the Start button. Change the Title of this button to Pause.

Note: We will later change this button to be the Resume button as well to resume the timer. Just as with the Start/Stop functionality, this will be done in code.

3H. Drag a Label object onto your storyboard, and make sure it is on top of the Date Picker object. Stretch the size of the Label so it is the same size as the Date Picker object.

Note: This label will contain the count down time. The Label object can be found where the Button and Date Picker objects are located.

3I. Add constraints to the Label object by clicking on the icon at the bottom that looks like a triangle between two vertical lines, then choose ‘Add Missing Constraints’.

3J. Change the ‘Text’ property from the Attributes tab to ’00:00’. Make sure the Font property is set to System, and the font size is set to 44.

3K. Set the Alignment property to center-aligned, and change the Background property to White Color.

3L. Set the Alpha property to 0.

Note: We will take a look at the reasoning for this properties once we start coding the application. The images above will show what your storyboard should resemble. You’ll notice the correct properties for the Label object are on the right hand side.

Step 4: Writing the Code

Note: In this step we will take a look at writing the actual code that will set and run the timer.

4A. Open the ViewController.h file on the right hand side of the Xcode window and add the following lines of code after the @interface ViewController : UIViewController section:

@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) IBOutlet UIButton *startStopButton;
@property (nonatomic, retain) IBOutlet UIButton *pauseButton;
@property (nonatomic, retain) IBOutlet UILabel *timeLabel;

Note: This code will set up the outlets that will connect to our interface objects, and allow our code to interact with our interface.

4B. Open the Main.storyboard file and right-click on where it says ‘View Controller’ on the left hand side under ‘View Controller Scene’.

4C. Click and drag the circle next to ‘datePicker’ to where it says ‘UIDatePicker’. Do the same thing for the corresponding pauseButton and startStopButton objects.

Note: For the timeLabel object, we will need to drag the circle to the name where it says ’00:00’, as shown in the above images.

4D. Click on the overlapping circles in the top right hand corner of the Xcode window to start creating methods for the Start/Stop buttons and Pause/Resume buttons.

Note: Our ViewController.h file should open. If it doesn’t open the ViewController.h file, see the pictures above to select ViewController.h.

4E. Hold down the Control key and click and drag from the Start button to any area between the @interface ViewController : UIViewController and @end tags. Change the Connection setting from Outlet to Action, and name this method startStopButton.

Note: You can give these methods any name. If you do give the method a different name, be sure to make note of that name, as we will need to reference it later in this project.

4F. Follow the same steps for our Pause button. Name the method pauseTimer.

Note: As with our Start/Stop button, you can give the method any name you’d like, however make note of the method name for later use.

4G. Replace where it says @implementation ViewController with the following code:

@implementation ViewController<br>
{
    BOOL isTimerRunning;
    BOOL isPaused;
    int hours;
    int minutes;
    int seconds;
    int secondsCount;
    NSTimer *timer;
}

Note: This code will create variables that we will use throughout this application.

4H. Add the following lines of code below where it says [super viewDidLoad]:

isTimerRunning = NO;<br>isPaused = NO; 
pauseButton.enabled = NO;

Note: This code will set our initial values for our booleans.

4I. Type the following code for the startStopButton method below the didReceiveMemoryWarning method:

- (IBAction)startStopButton:(id)sender {<br>
    NSTimeInterval duration = datePicker.countDownDuration;
    seconds = 0;
    hours = (int)(duration/3600.0f);
    minutes = ((int)duration - (hours * 3600))/60;
    secondsCount = ((hours * 3600) + (minutes * 60));
    timeLabel.text = [NSString stringWithFormat:@"%02i:%02i:%02i", hours, minutes, seconds];
    if (isTimerRunning == YES) {
        timeLabel.alpha = 0;
        [startStopButton setTitle:@"Start" forState:UIControlStateNormal];
        [pauseButton setTitle:@"Pause" forState:UIControlStateNormal];
        pauseButton.enabled = NO;
        [timer invalidate];
        timer = nil;
    } else {
        timeLabel.alpha = 1;
        [startStopButton setTitle:@"Stop" forState:UIControlStateNormal];
        pauseButton.enabled = YES;
        if (timer == nil) {
            timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self
                                               selector:@selector(updateTimer)
                                               userInfo:nil
                                                repeats:YES];
        }
    }  
    isTimerRunning = !isTimerRunning;    
}

4J. Type the following code below the startStopButton method. This will be the method that updates our timer:

- (void) updateTimer {<br>  
    secondsCount--;
    hours = secondsCount/3600;
    minutes = secondsCount/60;
    seconds = secondsCount - (minutes * 60);
    timeLabel.text = [NSString stringWithFormat:@"%02i:%02i:%02i", hours, minutes, seconds];
    if (secondsCount <= 0) {    
        [timer invalidate];
        timer = nil;
        timeLabel.alpha = 0;
        [startStopButton setTitle:@"Start" forState:UIControlStateNormal];
        pauseButton.enabled = NO;
    }
}

4K. Type the following code for the pauseTimer method:

- (IBAction)pauseTimer:(id)sender {<br>
    if (isPaused == NO) {
        [timer invalidate];
        timer = nil;
        [pauseButton setTitle:@"Resume" forState:UIControlStateNormal];
    } else {
        if (timer) {
            [timer invalidate];
            timer = nil;
        }
        timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                                 target:self
                                               selector:@selector(updateTimer)
                                               userInfo:nil
                                                repeats:YES];
        [pauseButton setTitle:@"Pause" forState:UIControlStateNormal];
    }
    isPaused = !isPaused;
}

Note: This method will be the code that both pauses our timer when it is running, and resumes the timer when it is paused.

Step 5: Project Complete!

And that’s it! If you build and run the application you will be able to set a timer up to 24 hours. You’ll be able to stop, pause and resume that timer as well.

Attached you'll find the source code for this project.

Comments

author
amberrayh (author)2015-03-27

Great tutorial! Thanks for sharing. I hope we see more from you in the future!

About This Instructable

9,448views

15favorites

License:

More by C_Faust:How to Create a Simple Timer Application for iOS
Add instructable to: