Category Archives: This Old App

This Old App: Hooking up the Model

A few months ago, Apple removed my app Interval RunCalc from the App Store for being too old and not updated. In this series of articles I’ll document what I did on rebuilding and improving the app. In the last installment, I hooked up my picker view interface to my app, and built the first round of user interfaces, along the way finding I’ve painted myself into a corner a few times and made several really silly mistakes.  In this installment, I hook up the model so the app actually calculates something – and get a pleasant surprise.

Hook up the Model

Up to now I’ve been setting the initial data to the picker as a literal. For example in the time entry

@IBAction func timerEntry(_ sender: UIButton) {

    if runStats.locked != .time{

      let vc = storyboard?.instantiateViewController(withIdentifier:>"InputController") as! PickerViewController

      vc.delegate = self

      vc.units = .hoursMinutesSecond

      vc.value = 4283.0// in seconds 3600 + 600 + 60 + 20 + 3 = 1 hr 11min 23sec

      vc.modalTransitionStyle = .crossDissolve

      present(vc, animated: true, completion:nil)

    }

  }

I set the picker to always get a 1:11:23 time. I’m going to change this to the RunStats model.

Before I do this, I notice an error I missed up to now. I have timerEntry instead of timeEntry. It’s a little thing, but it affects documentation, so I’ll fix it. Since this is an action, I unconnected the action, changed the spelling, cleaned with Command-Shift-K and then re-connect it.

Once I do that, I change the value to the runStats value for time, based on the model I created a few installments ago.

vc.units = .hoursMinutesSecond

vc.value = runStats.time.seconds()

I’ll do this next for distance, which is a bit more complicated. Each of my stats in the model has a value, which has a getter for the correct units(Kilometer or mile), and a enum for the correct units for display. The picker does too, but the enum is a different type, and the value is a generic Double, getting all the unit information from the enum. I create a switch statement to convert from the model to the picker.

      switch runStats.distance.displayUnits{

      case .kilometers:

        vc.units = .kilometers

        vc.value = runStats.distance.kilometers()

      case .miles:

        vc.units = .miles

        vc.value = runStats.distance.miles()

      }

For pace I should have the same thing, but there a wrinkle. The picker requires a Double for all measurements. In the model I have a string for minutesSecondsPerMile. The picker is looking for a double of seconds per mile, which I don’t have in PaceStat.  In the PaceStat class, I defined that string like this:

  public func minutesSecondsPerMile() -> String{

    let secondsPerMile = 1609.344 / paceStat

    let minutes = Int(secondsPerMile) / 60

    let seconds = Int(secondsPerMile) % 60

    return String(format:"%02i:%02i",minutes,seconds)

  }

Since seconds per mile was a necessary calculation to create the string, this is an easy fix. I can break that method into two methods:

func secondsPerMile()->Double{

    return 1609.344 / paceStat

  }

   

func minutesSecondsPerMile() -> String{

    let minutes = Int(secondsPerMile()) / 60

    let seconds = Int(secondsPerMile()) % 60

    return String(format:"%02i:%02i",minutes,seconds)

  }

Then add to the paceEntry action in my view controller this switch to convert units and values for the picker.

switch runStats.pace.displayUnits{

case .kilometersPerHour:

  vc.units = .kilometersPerHour

  vc.value = runStats.pace.kilometersPerHour()

case .milesPerHour:

  vc.units = .milesPerHour

  vc.value = runStats.pace.milesPerHour()

case .minutesSecondsPerMile:

  vc.units = .minutesSecondsPerMile

  vc.value = runStats.pace.secondsPerMile()

}

The Locked Value

Next I’ll add calculations for the locked value. This was the big surprise. I’ll add this to the RunStats model:

func recalculate() {

    switch locked{

    case .distance:

      self.distance = distance(pace: pace, time: time)

    case .pace:

      self.pace = pace(time: time, distance: distance)

    case .time:

      self.time = time(pace: pace, distance: distance)

    }

  }

 

There are times when one over-analyzes a situation, and leads to a complex solution. I did that in version 1.0 with the calculations above. Because I planned out the model so carefully for V 2.0, this ends up incredibly easy to deal with. In the V1.0 model, I was basing things on what changed, not what was locked. Locked is my solution, not just a locked variable. It the difference between “Pace just changed! What do I do?” to “Solve for time given pace and distance” The second is a lot simpler to think about and code.

Initialization

I’ll make sure I have some starting data in view did load

override func viewDidLoad() {

  super.viewDidLoad()

  runStats.pace = PaceStat(minutes: 10, seconds: 00)

  runStats.pace.displayUnits = .minutesSecondsPerMile

  runStats.distance = DistanceStat(miles: 26.2)

  runStats.distance.displayUnits = .miles

  runStats.locked = .time

  runStats.time = runStats.time(pace: runStats.pace, distance: runStats.distance)

  updateDisplay()

}

I’m ready to build and run. I’m pleasantly surprised that the first run works perfectly. The initial value loads from the model.

This is my ultimate goal for a marathon: a 4:22 finish. That’s way in the future – I’ve never run more than a half marathon. I try my last 5K run to find pace, changing the distance units, and solving for pace.

Yeah, I got a lot of training (and weight loss) ahead of me. My last long run used a slower combination of run/walk so it looks like this:

I have a ten Mile race coming up based on those paces, I can calculate My time between 2:24:50 and 2:16:50.

All of these match data calculated by other apps, so it looks like the app is working. For a change, I don’t have a lot of work to do in a development stage. I just plugged things in and they worked. I know it is supposed to work when I plan things out carefully, but it still amazes me when it does. I’ve done too much debugging to believe something actually works right the first time. In the next installment, I’ll start adding another level of complexity and that might change. I’ll start adding the interval table. First part of that phase is making a custom table view cell.

This Old App: Why I Hate PickerViews, but Learned To Love Them.

A few months ago, Apple removed my app Interval RunCalc from the App Store for being too old. In this series of articles I’ll document what I did on rebuilding and improving the app. In the last installment, I placed my new model into the old app, fixed a lot of errors from taking 2013 Objective-C code in 2017’s Xcode and make a quick, temporary view and controller to test it. Next, I’ll replace text fields I used for input. My best choice for this bothers me. UIPickerView is one of my biggest love/hate relationship in all of iOS development.

The app from my last installment looks something like this:

While this is okay for testing the model, it is not something I’d want for users. There’s a principle I’d like to introduce: Get Good, Get Fast. When working with user interfaces, get the data from your user as quickly as possible. The more time it takes a user to input data, the less likely he or she will use the app. They will get frustrated. What they enter must be good data. Data must makes sense to the application. We refer to this as valid data.

The current user interface is fast since I can type on the keyboard, but fails miserably in the validation arena. Because I’m using a keyboard and my values from the keyboard are strings, there’s a lot of data validation code I need to be sure I’m getting good data from the user.

In the version 1.0 of Interval RunCalc, I used keyboards. I tried controlling data validation by breaking up numbers into parts. For example, time used a special controller that broke up time into three integers were easier to input but restricted themselves to certain values

I did this for HH:MM:SS, MM:SS and decimal values. Problem was I had those values everywhere in the application, so my storyboard ended up a huge mess of segues.

My rationale at the time was simple: I didn’t want to use a UIPickerView for input. I hated UIPickerViews. There’s two reasons I hate them. Picker views break the Get Fast Get Good principle on the get fast side. They are effective for no more than ideally ten to twenty items. The classic picker view was one like this with 100 components.

It takes forever to get to higher numbers, breaking get fast. I get frustrated with these in other apps, and did not want to subject my users to such a thing.

The other objection separates new developers from seasoned ones. New developers, upon learning about picker views want to abuse them. They’ll put everything in picker views, and several on the same view. They’ll throw insane amounts of data in the most confusing ways, often making the UI unusable. For example here’s six components and two picker views. You can only read it in landscape

This would take forever to input data and gets very confusing fast. I get more weird questions about bizarre uses for picker views than any other control. Most of these developers do not think like users. Users hate picker views because they are confusing and take forever to use.

There is one strength for UIPickerView: Validation. UIPickerViews constrain input. Apple uses this for the date picker, taking four elements and combining them to get a Date value.

This is how picker views are supposed to be used. But even here I hate anything over 20 rows, like the date.

The date picker gives us the clue of how to use them right: Separate components into discrete elements than can have only constrained values. Make those elements with as few elements as possible. I set a limit of twenty rows. The keyboard input was a horrible mess in version 1.0. It never worked right. Despite my objections to them, I decided to use a picker view for my input to avoid all the data validation. I want one class of UIPickerView controllers. It will adapt to the different scenarios I need: HH:MM:SS, HH:MM:SS, and two digit decimal. I’ll make this a modal view instead of the navigation view I used in the original application to get rid of all those segues. I wrote my storyboard for it, which I placed on my Main.Storyboard:

This looks like a navigation controller, but it is an independent view controller on my storyboard, which will be a modal controller. I set a storyboardID of InputController. I made an illusion of a toolbar from two buttons, a label, and a UIView behind them, arranged with some auto layout.

This is a very flexible input system, giving the user the units I’m using and giving me power over all the buttons and labels. I’ll make a view controller PickerViewController for it, and I’ll add the following outlets and actions to that view controller:

@IBOutlet weak var backButton: UIButton!
@IBOutlet weak var doneButton: UIButton!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var toolBar: UIView!
@IBOutlet weak var unitsOfMeasureLabel: UILabel!
@IBOutlet weak var picker: UIPickerView!

@IBAction func didPressDone<span class="hljs-params">(_ sender: UIButton) {

}

@IBAction func didPressBack<span class="hljs-params">(_ sender: UIButton) {

}


Adding the Picker View 

In this article I’m more interested in the application than the implementation of a picker view. I’ll be leaving out steps. If you need to understand picker views and picker components, I’ve written out the whole process in detail which you can find here. I’ll be making a variation of that code, but understanding the way I did that will help you here.

My picker view is based on digits. No component will have more than 10 rows, speeding up the input process. Looking at the types of components I have:

  • Decimal digit – values of 0,1,2,3,4,5,6,7,8,9
  • Tens of minutes and seconds – values of 0,1,2,3,4,5
  • Time separator – a colon(:)
  • Decimal separator – a period(.)

I could add constants for this to my code, making four types of component wheels to add to my code and making some string arrays to do this.

let decimalDigit = ["0","1","2","3","4","5","6","7","8","9"]
let timeDigit = ["0","1","2","3","4","5"]
let timeSeperator = [":"]
let decimalSeperator = ["."]

That’s what I did in the article I mentioned above. There is another way to do this based on the row number and a bit of control logic. Instead of constants, I’ll use an enumeration.

enum ComponentType {

&nbsp;&nbsp;&nbsp;&nbsp;case ten,six,colon,decimal

&nbsp;&nbsp;}

I’ll make an array of this enum.

private var components = [ComponentType]()

This way I can describe any set of wheels quickly. MM:SS is [.six,.ten,.colon,.six.ten].The number of components are the size of this array

func numberOfComponents(in pickerView: UIPickerView) -&gt; Int {

&nbsp;&nbsp;&nbsp;&nbsp;return components.count

&nbsp;&nbsp;}

For HH:MM, this would return 5. I’ll set the number of components in my datasource, based on the component type:

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
    switch components[component]{
        case .ten: return 10
&nbsp;&nbsp;&nbsp;&nbsp;    case .six: return 6
&nbsp;&nbsp;&nbsp;&nbsp;    case .colon,.decimal: return 1
&nbsp;&nbsp;  }
}

Since I’m not using a string array to give me the title for a row in a component, I use the row number. The digit I want to display is equal to its row number. Make a formatted string of the row number. The exceptions are colons and decimal points, which I’ll explicitly return. I display the correct digit like this:

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
&nbsp;&nbsp;&nbsp;&nbsp;switch components[component]{
&nbsp;&nbsp;&nbsp;&nbsp;    case .ten: return String(format: "%01i", row)
    &nbsp;&nbsp;&nbsp;&nbsp;case .six: return String(format: "%01i", row)
    &nbsp;&nbsp;&nbsp;&nbsp;case .colon: return ":"
    &nbsp;&nbsp;&nbsp;&nbsp;case .decimal: return "."
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}&nbsp;&nbsp;

This all depends on the correct values in the components array. I’ll add another enum, listing input formats. I have three formats for that enumeration: a double with two dight decimal, MM:SS and HH:MM:SS.

enum PickerType {

&nbsp;&nbsp;&nbsp;&nbsp;case twoDecimal,minuteSecond,hourMinuteSecond

&nbsp;&nbsp;}

I’ll write a function to set the components.

&nbsp;func setPickerComponents(for pickerType:PickerType){
&nbsp;&nbsp;&nbsp;&nbsp;self.pickerType = pickerType

&nbsp;&nbsp;&nbsp;&nbsp;switch pickerType{
&nbsp;&nbsp;&nbsp;&nbsp;    case .twoDecimal:<span class="hljs-comment">//999.99 max value
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     components = [.ten,.ten,.ten,.decimal,.ten,.ten]&nbsp;&nbsp;&nbsp;&nbsp;
        case .minuteSecond: <span class="hljs-comment">//59:59 max value
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;     components = [.six,.ten,.colon,.six,.ten]
&nbsp;&nbsp;&nbsp;&nbsp;    case .hourMinuteSecond: <span class="hljs-comment">//99:59:59 max value
     &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;components = [.ten,.ten,.colon,.six,.ten,.colon,.six,.ten] &nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;}

&nbsp;&nbsp;}

The class has two data properties. When I present the view controller, I’ll set these two properties.

var units = Units.meters

&nbsp;var value = 0.0&nbsp;&nbsp;

One is the units of measure and the current value. Units is another enumeration which lists all the app’s units of measure:

enum Units {
&nbsp;&nbsp;&nbsp;&nbsp;case 
       meters,kilometers,miles,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;milesPerHour,minutesSecondsPerMile,kilometersPerHour,
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;hoursMinutesSecond
&nbsp;&nbsp;}

There’s a lot of cosmetic changes I’ll make depending on the units, such as displaying the units and if this is a speed, distance or time variable. I wrote a method configure to handle all this, leaving some methods to do a lot of the repetitive configuration.

func configure<(for units:Units){

&nbsp;&nbsp;&nbsp;&nbsp;switch units{
&nbsp;&nbsp;&nbsp;&nbsp;case Units.meters:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Meters"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.kilometers:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Kilometers"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.miles:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Miles"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;distance()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.milesPerHour:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Miles per Hour"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.minutesSecondsPerMile:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setMinutesSeconds()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Minutes per Mile"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.kilometersPerHour:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setTwoDecimal()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Kilometers per Hour "
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;paceOrSpeed()
&nbsp;&nbsp;&nbsp;&nbsp;case Units.hoursMinutesSecond:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;setHoursMinutesSeconds()
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;unitsOfMeasureLabel.text = "Time"
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;time()
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}

I’ll add three methods for configuring the types.

func setTwoDecimal<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .twoDecimal)
}

func setHoursMinutesSeconds<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .hourMinuteSecond)&nbsp;&nbsp;
} &nbsp;

func setMinutesSeconds<span class="hljs-params">(){
&nbsp;&nbsp;setPickerComponents(for: .minuteSecond)
}


For the user interface side of things, I set the background color and title depending on the units so users have visual cues:

func distance(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Distance"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.cyan
&nbsp;&nbsp;}

&nbsp;&nbsp;func paceOrSpeed(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Pace / Speed"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.yellow
&nbsp;&nbsp;}

&nbsp;&nbsp;func time(){
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "Time"
&nbsp;&nbsp;&nbsp;&nbsp;backgroundColor = UIColor.green
&nbsp;&nbsp;}&nbsp;&nbsp;

The First Test

I have enough code to test the picker now. I’ll set up a button on my test storyboard and add some code to configure the picker. I’ll add a button Picker.

I’ll make an action for this button in RootViewController.swift. This input controller is intended for modal controllers. Modals launching for a storyboard identifier makes sense in this context. I use it multiple times. It clears all that segue spaghetti I had in version 1.0. I’ll launch the controller in a modal view using the default values.

@IBAction func pickerButton<span class="hljs-params">(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: <span class="hljs-literal">true, completion: <span class="hljs-literal">nil)
&nbsp;&nbsp;}

I’ll go back to the PickerViewController.swift file and add dismissal code in my actions.

@IBAction func didPressDone(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;self.dismiss(animated: true, completion: nil)
&nbsp;&nbsp;}

@IBAction func didPressBack(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;self.dismiss(animated: true, completion: nil)
&nbsp;&nbsp;}

One thing I forgot – to call configure. I’ll do that on the viewDidLoad of PickerViewController.swift

override func viewDidLoad() {
&nbsp;&nbsp;&nbsp;&nbsp;super.viewDidLoad()
&nbsp;&nbsp;&nbsp;&nbsp;picker.dataSource = self
&nbsp;&nbsp;&nbsp;&nbsp;picker.delegate = self
&nbsp;&nbsp;&nbsp;&nbsp;configure(for: self.units)
&nbsp;&nbsp;}

I’m ready to run. When I build and run, then press the picker button, I get a beautiful interface, where I can roll the individual digits.

I notice a potential bug. I ran a quarter of a marathon or 10.56 Km last weekend. That’s 10557.30 meters, which I could not enter into the app since I don’t have enough digits. I could add another two digits for 99999.99 for meters, but before I do, I’ll ask myself the question: will the user enter anything in meters?

This app is for distance runners. Distances are in kilometers or miles, never meters. That would be a change that has no use. I only care about what the user wants here, not my internal measurement system of meters. I’ll skip that change.

I do another test. I add the unit of measure in the action in RootViewController for a pace.

@IBAction func pickerButton(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = .minutesSecondsPerMile
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: true, completion: >nil)
&nbsp;&nbsp;}

Building and running again, I can spin the wheels there too.

Setting Values

I want to set the picker to an initial value. Inside the picker’s code I‘ll change value to a series of row indices representing the number, one digit per component. I’ll convert value to a string, then use the characters to represent rows.

If I had a 11:23 minute/mile setting, I set the string to "11:23" The code looks at a character from the left to the right as the row index for the component. The functions Int(String(character)) get me this index used in a for loop. I use the selectRow method to select the row with that number.

picker.selectRow(row, inComponent: component, animated: animated)

The Int constructor produces a nil value for any character that isn’t a digit. Those are my separators, and they always have a row value of 0. The code looks like this:

func setComponentValues(from str:String){&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;var component = 0
&nbsp;&nbsp;&nbsp;&nbsp;for character in str.characters{
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;if let row = Int(String(character)){
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectRow(row, inComponent: component, animated: animated)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;} else {
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectRow(0, inComponent: component, animated: animated)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;component += 1
&nbsp;&nbsp;&nbsp;&nbsp;}
&nbsp;&nbsp;}

I made three functions to set the value depending on the PickerType. If their sparse code didn’t make sense before, they will now. Each converts the value to a string for that PickerType, then converts that string to the correct rows in the picker components

func setTwoDecimal(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .twoDecimal)
&nbsp;&nbsp;&nbsp;&nbsp;let str = String(format:"%06.2f",value)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;func setHoursMinutesSeconds(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .hourMinuteSecond)
&nbsp;&nbsp;&nbsp;&nbsp;let hours = Int(value + 0.5) / 3600
&nbsp;&nbsp;&nbsp;&nbsp;let hoursRemainder = Int(value + 0.5) % 3600
&nbsp;&nbsp;&nbsp;&nbsp;let minutes = hoursRemainder / 60
&nbsp;&nbsp;&nbsp;&nbsp;let seconds = hoursRemainder % 60
&nbsp;&nbsp;&nbsp;&nbsp;let str =&nbsp;String(format:"%02i:%02i:%02i",hours,minutes,seconds)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;func setMinutesSeconds(){
&nbsp;&nbsp;&nbsp;&nbsp;setPickerComponents(for: .minuteSecond)
&nbsp;&nbsp;&nbsp;&nbsp;let minutes = Int(value) / 60
&nbsp;&nbsp;&nbsp;&nbsp;let seconds = Int(value) % 60
&nbsp;&nbsp;&nbsp;&nbsp;let str = String(format:"%02i:%02i",minutes,seconds)
&nbsp;&nbsp;&nbsp;&nbsp;setComponentValues(from: str)
&nbsp;&nbsp;}

&nbsp;&nbsp;

To save myself some time I copied and pasted some code from my model to make the time strings.

In RootViewController, Add a value to the action:

@IBAction func pickerButton(_ sender: UIButton) {
&nbsp;&nbsp;&nbsp;&nbsp;let vc = storyboard?.instantiateViewController(withIdentifier: "InputController") as! PickerViewController
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = .minutesSecondsPerMile
&nbsp;&nbsp;&nbsp;&nbsp;vc.units = 683.0 // in seconds 600 + 60 + 20 + 3 = 11min 23sec
&nbsp;&nbsp;&nbsp;&nbsp;present(vc, animated: <span class="hljs-literal">true, completion: <span class="hljs-literal">nil)
&nbsp;&nbsp;}

I’ll test this and see 11:23

Getting Values

The purpose of a input picker is the get a value from the user. To do that I’ll update value every time the picker changes. I’ll set up the picker’s delegate function to update the value in a function

&nbsp;func pickerView<span class="hljs-params">(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
&nbsp;&nbsp;&nbsp;&nbsp;updatePickerValue()
&nbsp;&nbsp;&nbsp;&nbsp;titleLabel.text = "<span class="hljs-subst">\(value)" //for testing only
&nbsp;&nbsp;}

I added a extra line for testing the value, sending the value to the title. In the app we’ll use a delegate, but that’s for the next phase, so I’ll display it here for now.

The the updatePickerValue function converts the components into a value. I built this into another switch pickerType control structure. This is the opposite of the setting the value. Take the row and convert it to a value. If it is part of a bigger number, add it with the other digits of the number. For example, for the .twoDecimal, I did this:

case .twoDecimal:
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;picker.selectedRow(inComponent: 5)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let hundredth = Double(picker.selectedRow(inComponent: 5))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let tenth = Double(picker.selectedRow(inComponent: 4))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let fraction = tenth * 0.1 + hundredth * 0.01
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let ones = Double(picker.selectedRow(inComponent: 2))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let tens = Double(picker.selectedRow(inComponent: 1))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let hundreds = Double(picker.selectedRow(inComponent: 0))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let wholeNumber = hundreds * 100 + tens * 10 + ones
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value = wholeNumber + fraction

I did this explicitly since it is easier to debug than an algorithm for it. I do the same for the time-based picker types, grabbing a digit and adding it all together.

&nbsp;case .minuteSecond: //00:00 returning seconds
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var tens = Double(picker.selectedRow(inComponent: 0))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var ones = Double(picker.selectedRow(inComponent: 1))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let minutes = (tens * 10 + ones) * 60
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;tens = Double(picker.selectedRow(inComponent: 3))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;ones = Double(picker.selectedRow(inComponent: 4))
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;let seconds = (tens * 10 + ones)
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;value = minutes + seconds&nbsp;&nbsp;&nbsp;

Run again and I’ll change the pace to 10:23. As expected, 623.0 is in the title.

 

I’ve built a decent picker that follows Get Good, Get Fast. All data in and out of the picker is a single value of double. What that value represents is a unit of measure. My unit of measure configures my picker for the only legitimate values. I call the picker from a modal view programmatically without a lot of confusion in the storyboard. My next step is the user interface, and hooking this up to it. In the next installment, I’ll build that UI and find I made a few bad assumptions with the picker and find some other interesting dilemmas.

This Old App: 2013 Code, Meet Xcode 8

A few months ago my app Interval RunCalc was removed from the App Store for being too old and not updated. In this series of articles I’ll document what I did on rebuilding and improving the app. In our first article I analyzed the changes necessary. In the second, I built the model in a Swift playground. Now it is time to place that model into the old app, and make a temporary view and controller to test it.

Open the App in Xcode

I made a copy of the original app development files, then opened them in Xcode. The issue navigator started complaining right away:

Clicking on the issue, I find several updates Xcode wanted to make.

I select Perform Changes resolving the issues. I find in the target settings for the project, there’s more issues: provisioning profiles for debug and release.

>

Above the issue, I’ll find a checkbox Automatically Manage Signing. I check that and enable the automatic signing.

I find provisioning one of the most irritating parts of working with Xcode. Anything to get me away from it is a good thing.

Of course that’s not the end of the issues. I get another error message.

If I manage singing automatically, I have to pick the team. I only have me so I pick myself from the drop down. The target is set up, and Xcode is happy again.

Configuring the New Version

This is a major version update for the app. I want to change the version number to version 2.0. Originally I wanted the app to be called runner’s calc, but that name was taken. I settled on the mouthful Interval RunCalc. That’s too long for an icon, I want to change the Display Name to a shorter name, Run Calc to show better on an icon.

The next change I’ll make is the deployment info. Currently, the deployment is iOS 8.0 and only on iPhone in portrait.

Which iOS version to set to is a good question. In most cases, you want to deploy a version or two back for compatibility. Here’s where getting user data comes in handy. I’ll use iTunes Connect’s analytics, and look at the analytics for 2016.

Two active devices per month means there’s almost no one but me using this. Usage data strongly hints me that the biggest user is me. The large peaks occur at races I either ran or was a spectator (marathons are my 2018 goal). While a second user might be at the same races, I find it unlikely.

I’m looking at a sample that’s less than a third of total apps out there. Still, upping the version to 10.3 is not tragic since it looks like nobody but me uses this. I’ll bump it up all the way for the revision. I’m also going to make this a Universal app instead of a iPhone app. My new settings look like this:

Later, I’ll set the iPad and iPhone interface to the same initial storyboard.

The Old Structure

Opening the project navigator, You can see how I put together this app:

You’ll see the root files are the RunnersCalc files. The top level contains the initial view controller and the help controller. There was a help controller, though no one knows how to get to it — I unfortunately hid it too well. If you got to it, it was just written instructions, and very badly written. It’s another thing to go on the list of changes.

The folders under this root level has one folder for the model, and three folders for the view controllers: Intervals, Input controls and Splits.

For those from a completely Swift background, those .h and .m files are Objective-C files. The .h files contain a header which indicates what properties and methods are sharable to the rest of the app. Your code is in the .m files.

Opening up the Model folder and clicking the PCPace.h file, I find the declarations for the model, the properties of the model were:

//properties of the object

@property NSTimeInterval pace; // seconds per mile

@property float speed; // miles per hour

@property float distance; //miles

@property NSTimeInterval time; //seconds of the run or split

@property NSTimeInterval splitPace; //seconds per mile or km

@property int splitCount; //total number of splits

@property int splitNumber; //current split -- necessary?

@property int fullSplitCount; //number of splits for the full mile/kilometer

@property NSTimeInterval elapsedTime; //elapsed time in a split

@property float totalDistance; //totalDistance to this point

enum PCVariable {

  kcPCSpeed,kcPCDistance,kcPCPace,kcPCTime

};

@property enum PCVariable finding;


Add the Playground Code to the App

I’m not too worried about any of this code, since I’m about to replace it all. I open up the RunStats playground so I can copy my code. I have the code stored in four files:

In the App project, I’ll make four new files in the model folder. I’ll select the Model Folder first to keep the group correct as I add files. I’ll hit Command-N to make a new file. There’s several ways I can make these files, since I’m cutting and pasting everything into the file. I’ll select Swift File for the template, though I could have just as easily picked a Cocoa Touch Class subclassing NSObject.

I’ll be asked to save with a file name. I’ll call this one RunStats.

On the bottom, I’ll make sure the target is correct and the Group is Model

We click Create, and get a new Message:

I usually create the bridging header. As the message says the bridging header opens up the classes, methods and properties in the Objective-C code to the the newer Swift code if you want to use it. In this application I won’t use it. However, it is not a lot of overhead. I’m planning to scrap all the Objective-C, but I never know in an intermediate step if I’ll need it, so I’ll create it anyway.

I’ll repeat this three more times for the classes DistanceStat, PaceStat and TimeStat. I have two classes in the RunStats playground page. I’ll add one more for RunStatsIntervals, so every class has its own file.

I’ll organize this a little better. I’ll select my Objective-C files PCPace.h, PCPace.m, and the bridging header. I’ll right click and make New Group From Selection, naming the group Objective-C. I’ll do the same for the Swift code, selecting it all and making a Swift group for it.

I’ll select RunStats, and see this:

//

// RunStats.swift

// RunnersCalc

//

// Created by Steven Lipton on 4/6/17.

// Copyright © 2017 Steven Lipton. All rights reserved.

//



import Foundation


I’ll delete the import foundation, and then copy and paste my RunStats class from the playground to the App, leaving the intervals class and the test data in the playground. I’ll make sure I copy the import UIKit when I do. It will of course have lots of errors for the moment. We have the three classes it refers to yet to add. I’ll do the same copy and paste to the other four files, adding the classes and import UIKit in each case.

Once I’m done with this there are seven issues to solve. When transferring a playground, you’ll probably get these errors.

If you click on the first error, it will show you this in the editor:

The time.seconds() and the distance.meters() lines Xcode wants to assign to something. I used them to get a quicklook for debugging the playground. All the errors are like this. The simple solution is delete that code. The fatal error is the same thing. it’s on the line

 self.pace

It was to get a quicklook for the object in the playground. I deleted it to clear the error.

A New View and Controller

The new model is in the app, and I’d like to test it. Right now, this code is ignored by the app. What I’ll do is set up a new storyboard to check the model. In the Storyboards group, I have a blank iPad storyboard and the Main_iPhone.storyboard file, which has the current storyboard for the app:

This is a big mess. This is one of those times when doing an update project like this you just shake your head and wonder what you were thinking back then. With a little investigation, you’ll find some of those answers. I iterated this model with a inadequate model to start, and I needed a lot of UI to cover up my mistakes. The major reason this app never had an iPad version was I’d have to replicate this storyboard on an iPad.

The new app had a completly new Storyboard. I’m using auto layout to need one storyboard for all devices. I Press Command-N, selecting a Storyboard object and name it Main, making sure my Group is Storyboards.

The storyboard I get is completely blank. I’ll drag a view controller onto the storyboard

I’ll change the attribute to give this a name and set this view controller to Is Initial view controller.

I’ll need a ViewController file for this scene. I’ll press Command-N again, click a Cocoa Touch Class for the template and make the Class RootViewController, subclassing UIViewController and Swift as the language.

When I save the file I’ll save it to the RunnersCalc root folder, where the root and help view controllers are. Going back to the main storyboard, I’ll set the Custom Class to RootViewController. Now I’m ready to add some controls.

This first layout is only for testing purposes. No auto layout just yet, just drag and drop. I’ll add a label for a result and a button to calculate the result. I’ll use text fields for input, so I’ll need room for the keyboard.  I’ll set the button at the center of the iPhone screen, giving the keyboard I hope plenty of room, and the result at the top. I’ll make the label read Result and the button Calculate

I Drop two text fields between the label and the button, which I’ll call variable 1 and 2. That will be for decimal values. For time values I’ll add three textfields under those two text fields. The layout looks like this, using placeholder text for titles.

Next, I’ll wire up my view controller. I’ll open the assistant editor. All but the button are outlets, So I’ll do those first, control dragging into the view controller.

@IBOutlet weak var result: UILabel!

  @IBOutlet weak var variable1: UITextField!

  @IBOutlet weak var variable2: UITextField!

  @IBOutlet weak var hours: UITextField!

  @IBOutlet weak var minutes: UITextField!

  @IBOutlet weak var seconds: UITextField!

I’m keeping this very generic for a reason. This is a test bed. I’ll use these same fields to check different parts of the model. I’ll calculate the values in code in the calculate button, which I now wire up as an action.

@IBAction func calculate(_ sender: UIButton) { 

  }

There’s a function I’ll need in the view controller. It will take a TextField and convert the text in it to a Double. I can close up the storyboard and assistant editor, and then add the function to RootViewController

  func double(textField:UITextField!)->Double{

    guard let textField = textField 

       else {return 0.0} //uwrap textfield

    guard let value = Double(textField.text!) 

       else {return 0.0} //find double

    return value

  }

This will give me a value of 0 for anything that isn’t a true Double, and return a Double if it is. There’s three optionals, and I deal with all the unwrapping here giving me a value or a zero. This is not something I’ll need in the finished code. The input system (which we cover next time) will restrict the user to only valid values.

With the structure of the test bed done, I’ll add the model to the code.

 let runStats = RunStats()

I’ll test the function the IBAction calculate. I’ll start with a simple test to make sure everything works, converting kilometers to miles.

@IBAction func calculate(_ sender: UIButton) {

    let distance = double(textField: variable1)

    runStats.distance.distance(kilometers: distance)

    let resultText = String(format: "%02.2d", runStats.distance.miles())

    result.text = resultText

  }


I use the double function to turn the variable1 text field into a double, then add it to the model with a kilometer measure. I change the distance to miles in a string, placing the result in result.

I’m almost ready to run this code, but there’s one more thing I need to do: Change the initial storyboard. In the General tab of the Target Properties, you’ll find this:

When run, the app goes to the old Main_iPHone storyboard, not the new Main. I also restricted the layout to portrait in the old version, and I’ll use all orientations for the new version. I set both the iPad and iPhone to the same storyboard Main:

Setting my simulator to an iPhone 7 I run the app. Two things happen. I get 44 warnings, but the app runs. I try putting in a value. I find I didn’t leave enough room for the keyboard

I’ll stop the app and move the calculate button up. I try running again. I’ll type in 5 when the calculator appears, and get rewarded with a value of…Zero instead of 3.11.

I first check to see if the model is working right with a few print statements

@IBAction func calculate(_ sender: UIButton) {

    let distance = double(textField: variable1)

    print("distance in km \(distance)")

    runStats.distance.distance(kilometers: distance)

    print("distance in km \(runStats.distance.kilometers())")

    print("distance in km \(runStats.distance.miles())")

    let resultText = String(format: "%02.2d", runStats.distance.miles())

    result.text = resultText

  }

When run, I get output on the console:

distance in km 5.0

distance in km 5.0

distance in km 3.10685596118667

The model is working fine. My bug is a silly one of setting the format wrong in the string. I change the format to this:

let resultText = String(format: "%6.2f", runStats.distance.miles())

When I run again, the test works.

I go back to the storyboard. That alphanumeric keyboard is annoying. For all the TextFields, I set the keyboard type to decimal pad.

I’m ready to try another test. Let’s take distance in miles and a speed in miles per hour and calculate time. I’ll convert distance and speed to Doubles, then set them to the runstats model. I’ll try this code.

@IBAction func calculate(_ sender: UIButton) {

    let distance = double(textField: variable1)

    let speed = double(textField: variable2)

    runStats.distance.distance(miles: distance)

    let pace = PaceStat(milesPerHour: speed)

    runStats.time(changedBy: pace)

    result.text = runStats.time.hoursMinutesSeconds()

  }  

I try a simple case where I run five miles at five miles an hour, And yes, I get the expected one hour.

I try a function with a time variable using the three textfields on the bottom. I’ll compute the pace in minutes per mile for a given distance.

@IBAction func calculate(_ sender: UIButton) {

    runStats.distance = DistanceStat(miles: double(textField: variable1))

    let seconds = Int(double(textField: self.seconds))

    let minutes = Int(double(textField: self.minutes))

    let hours = Int(double(textField: self.hours))

    let time = TimeStat(hours: hours, minutes: minutes, seconds: seconds)

    runStats.pace(changedBy: time)

    result.text = runStats.pace.minutesSecondsPerMile()

  }

I build and run this. A simple test is a one hour run of five miles, which should give us a twelve minute mile.

And my target time for my first marathon of five hours 45 minutes ( yeah, I’m a bit slow)

As expected, I get the 13:10 pace. I’d do a lot of tests like this to make sure the components work with the model.

A Model Change

During the testing, I get the feel for using the code in the model. There’s one thing I don’t like. Consider these two statements

runStats.distance.distance(miles: 5.0)

print(runStats.distance.miles())

I use different identifiers for the setter and getter. I like this better:

runStats.distance.miles(5.0)

print(runStats.distance.miles())

It is easer to read and shorter to type. It is not a huge change in the model code, and it works better. I can change the setters to this:

//set distance from miles

  public func meters(_ meters:Double){

    distanceStat = meters

  }

  public func miles(_ miles:Double){

    distanceStat = miles * 1609.344

  }

  public func kilometers(_ kilometers:Double){

    distanceStat = kilometers * 1000.0

  }


I change the resulting code using these functions in the rest of the model. I’ll do the same for the other stat types. The current code only requires changes to the stat types DistanceStat, PaceStat and TimeStat. Pace and time add one wrinkle in two and three parameter setters. The first parameter becomes the name of the setter, and the rest are parameters like this:

public func hours(_ hours:Int,minutes:Int,seconds:Int) {

    timeStat = Double(seconds + minutes * 60 + hours * 3600)

  }

I didn’t do it intially, but some uses of these functions in initializers will need to specify self to work properly.

public init(minutes:Int,seconds:Int){

    self.hours(0, minutes: minutes, seconds: seconds)

  }

Running the code as written I get the same results, and no problems.

The 44 Warnings 

There’s one last thing to address: those 44 warnings. Closing the folders they are in, I find they fall into the following categories:

Those warnings are why Apple wants me to change this code, and threw me out of the app store to do it. This is all old stuff that needs updating. Sometimes living in the Swift world, I forget the Objective-C is improving over time too. The deprecations for example are all the same issue: there’s no more UIActionSheets in iOS.  Many of the others are number conversions which changed in newer versions of iOS in Objective-C

I have choices here: I can fix this code and remove the errors, I can ignore the errors for now, or I can delete the code now. While the errors are annoying, they are not affecting the code. I go for the last one. I will delete all of the Objective-C code before shipping, replacing it with the new Swift code. It doesn’t need to be there, but I use it as documentation for the old version until I don’t need it anymore.

So I got the new model into the old code. I started replacing components, and got the old code to actually function in the latest Xcode. My next steps are to get the views and controllers working properly. I”ll start that process not at the root, but by replacing those text views with UIPickers in the next installment.

I’m a LinkedIn Learning author, with five courses up in the LinkedInLearning library.  My latest is a trilogy for iOS notifications: Learning iOS NotificationsiOS App Development: Notifications, and watchOS App Development: Notifications If you a re interested in Notifications, I’d Check them out.