A very brief introduction to date formatting in Swift and iOS

The book 'Beginning iPhone Development with Swift'As I wrote in an earlier article, I’ve been working my way through Apress’ Beginning iPhone Development with Swiftan iOS 8/Swift-flavored update of Beginning iOS 7 Development. The original book was released in March 2014, the iOS 8 and Swift betas came out that June, the GM versions came out in September, and the revised book was released in mid-November. In the eight-month span between the original book and the revision, the authors didn’t have much time to try out iOS 8 and Swift, never mind do the rewrite, and as a result, they ended up with a few errors in their text, as well as leaving out some useful material.

I also wrote in that earlier article that in spite of these problems, I still think it’s a good book (as do some other people; it’s got 5 stars on Amazon as of this writing), and where some may see errors and oversights, I see opportunities.

Here’s another opportunity that came up…

The date picker exercise

Chapter 7 of Beginning iPhone Development with Swift, Tab Bars and Pickers, has you build a multi-view app where you use all kinds of “picker” controls. The first view you work on is one with a date picker; here’s a screen shot:

iOS app showing a date picker and a button labelled 'Select'. The selected date in the date picker is 'Today, 4:20 PM'

In this simple view, you use the picker to select a date, tap the Select button, and you’re presented with an alert that looks like this:

iOS app with date picker and button, overlaid with an alert showing the selected date as '2015-01-14 21:20:13 +0000'

Note the format of the date displayed in the alert:

  • It’s not formatted in the most readable way.
  • It has too high a level of detail. The user didn’t enter the number of seconds or a time offset.
  • I entered the time in my time zone (4:20 p.m., Eastern Standard Time, or GMT-5), but the alert is displaying the time for GMT.

Here’s what the book had to say about this:

The date picker does not allow you to specify seconds or a time zone. The alert displays the time with seconds and in Greenwich Mean Time (GMT). We could have added some code to simplify the string displayed in the alert, but isn’t this chapter long enough already? If you’re interested in customizing the formatting of the date, take a look at the NSDateFormatter class.

I’d much rather have the alert look like this…

iOS app with date picker and button, overlaid with an alert showing the selected date as 'Wednesday, January 14, 2015 at 4:20 PM'

…but they’d left doing so as an exercise for the reader. Let’s go through this exercise, shall we?

The original code

Here’s what the view looks like in the Storyboard:

datepicker view

And here’s the code for buttonPressed in the corresponding view controller:

In this code, we’re simply taking the value from the date picker’s date property and using its string representation in the string constant message. In iOS, dates are represented by instances of the NSDate class, which is all about representing a single point in time. While it has the date property for access the date stored within, it doesn’t have any members for formatting that date.

Enter NSDateFormatter

iOS has a number of formatter classes, whose job is to take data and convert it into a text representation, typically for the benefit of the user. These classes have names that end with the word Formatter and are subclasses of the abstract class NSFormatter. You can find out more about these classes in NSHipster’s excellent overview.

The book pointed us towards NSDateFormatter, a class that serves two purposes:

  • Converting NSDate objects into string representations, and
  • Converting strings into NSDate objects.

NSDateFormatter has a class method called localizedStringFromDate that does what we want. Given the following:

  • An NSDate instance,
  • A style specifying how we want the date part of the NSDate instance formatted, and
  • A style specifying how we want the time part of the NSDate instance formatted

…it returns a string representing the NSDate instance in the format we specified.

We specify the styles for the date and time using values from the NSDateFormatterStyle enum, which has the following values:

  • NoStyle: Unstyled.
  • ShortStyle: Typically numeric-only, such as 1/14/15 and 4:20 PM.
  • MediumStyle: A medium-length style, using abbreviations. Examples are Jan 14, 2015 and 4:20:00 PM.
  • LongStyle: A longer style with full text. Examples are January 14, 2015 and 4:20:00 PM EST.
  • FullStyle: Full style with complete details. Examples are Wednesday, January 14, 2015 and 4:20:00 PM Eastern Standard Time.

For our code, we’ll use FullStyle for the date and ShortStyle for the time. Here’s what the revised code looks like — the highlighted lines show the new or modified code:

This code gives us the date in a more user-friendly format.

This example scratches the surface of what’s possible with NSDateFormatter. You should take a look at Date Formatters, which is part of a larger section of their documentation called Data Formatting Guide.

dates and times in swift - smallRelated articles

How to work with dates and times in Swift, part one: An introduction of Cocoa’s date and time classes, and how they work together. This article covers UTC (Coordinated Universal Time), and the key classes: NSDate, NSCalendar, NSDateComponents.

How to work with dates and times in Swift, part two: Calculations with dates: Now that we’ve got the basics, it’s time to do some date arithmetic: comparing two dates to see which one is the earlier and later one, finding out how far apart two dates are, and adding and subtracting from dates.

How to work with dates and times in Swift, part three: Making date arithmetic more Swift-like: Cocoa’s date and time classes have an Objective-C heritage, which in the Swift context, feel kind of clunky. In this article, I look at ways — and by ways, I mean helper functions and class extensions — to make date calculations feel more like Swift.

How to work with dates and times in Swift, part four: A more Swift-like way to get the time interval between two dates: This quick article shows you how to make an operator overload that makes getting the time interval between two dates more like subtraction.

You might also want to check out: How to program an iOS text field that takes only numeric input with a maximum length


Mobile pundit Tomi Ahonen’s predictions for smartphone vendors in 2015

tomi ahonen - mobile pundit

Tomi Ahonen, Nokia executive during its heyday, mobile consultant to Fortune 500 companies, prolific author, and all-round mobile curmudgeon, has published his predictions for the mobile handset industry in 2015 on his blog, Communities Dominate Brands. The title of his article, So the Smartphone ‘Bloodbath’ Annual Preview for Year 2015 – This is so boring, gives you a taste of his writing style: a little hyperbole, and a lot of stream of consciousness. It’s a big, monolithic block of text, chock-a-block with the asides that are his stock in trade, and it’s a lot to wade through.

We’ve taken Ahonen’s article and distilled it for what we think are the big take-aways from his 2015 predictions. As always, this sort of future-telling should always be taken with a grain of salt — while he often has brilliant insights into mobile tech (it’s why we read what he has to say), he’s been known to be oh-so-very-wrong from time to time (as everyone is).


Samsung’s sitting pretty as the world’s largest handset maker, at almost twice the size of the next runner-up, and larger than the 2nd- and 3rd-place vendors combined. They’re also the largest of the “major handset makers who genuinely cater to the global mass market” (as opposed to Apple, who are aimed at the higher-end customer, or BlackBerry, whose focus is the enterprise). Their “everywhere” status means that they’ll make good money and stable, but it also means that investors can’t count on them to be as “ridiculously profitable” as Apple.

samsung galaxy k zoom

Samsung’s weakness, according to Ahonen, is their sales management, which he describes as “a total disaster”. They produce a confusing array of all-too-similar models, and fail to highlight interesting and innovative devices like the Galaxy K Zoom, which reimagines the smartphone as a camera with a great lens and 10x optical zoom that just happens to have a phone rather than the other way around, priced 20% below the latest iPhone model. Given that:

  • most people’s phones are their cameras these days,
  • we can’t post enough photos on Facebook, Twitter, Instagram, and SnapChat, and
  • camera quality is a big factor in many people’s smartphone choices,

you’d think that this would be a heavily-marketed, big-selling Android phone. But just try to find it at your local store.

samsung tizen

Tizen, Samsung’s troubled, oftendelayed device operating system that they they hope will free them from dependency on Google and Android, is expected to debut at this year’s CES, where it’ll debut on its TV sets. While the Tizen Alliance — a rag-tag group of a dozen hardware manufacturers who’ve promised to release Tizen-powered devices — seens to have fizzled out, Ahonen still believes that Samsung’s market size and clout, combined with the sort of effort and execution Samsung can make when they’re doing things right, mean that Tizen could be a game-changer over the next couple of years.


apple and ios

Apple has historically been one of Ahonen’s blind spots. Back when Nokia, Motorola, RIM, and Palm were the ones to beat, he consistently downplayed Apple. Later, as Nokia was going down in flames, his thesis was that the iPhone didn’t kill Nokia, Nokia’s response to the iPhone did.

apple watch

Ahonen’s prediction that we should start to see the final transformation of Apple into a niche OS and out of the mass market as Android assumes the position for mobile devices that Windows had for desktop computers. As for the Apple Watch, he says that yes, the iFaithful will line up to buy it, but in the end, even they will reject it in the long run.



They did well for themselves in the laptop world by buying an internationally-recognized and respected brand — IBM’s ThinkPad — and turning it into a profitable business. It appears that they’re trying to repeat history now that they own the Motorola marque. Buying these brands are smart moves, says Ahonen, allowing them to sidestep the reputation of “cheap Chinese” that other vendors like Huawei and ZTE have to contend with, especially given the rave reviews their most recent phones have received. Moto, and not Xiaomi, is the biggest threat to Samsung, according to Ahonen.



Here’s the Ahonen take in a single sentence: They won, and the only way they can lose is if they themselves screw it up.

The “Next Five” (Coolpad, Huawei, TCL, Xiaomi, ZTE)

the next five

Here in the U.S., none of these brands — Coolpad, Huawei (“WAH-way”), TCL, Xiaome (“SHOW-mee”, the first syllable rhymes with “cow”), and ZTE — are household names, but in Ahonen’s list, they’re the next runners-up after the top three smartphone vendors (Xiaomi recently moved up to the number 3 position). Xiaomi is getting a lot of press right now, partly because of its dramatic growth, and partly because they’re hardcore Apple copycats.

If he had to bet on members of the “next five”, Ahonen would put his money on Huawei and ZTE, because selling phones requires more than product, but also relationships with carriers worldwide. Huawei and ZTE have been selling telecom equipment to the carriers for years, so they have an “in” that upstarts like Xiaomi don’t.

Legacy brands (such as HTC, LG, and Sony)


Ahonen doesn’t see these vendors — HTC, LG, and Sony — making much of a mark. He says that while they may see the occasional quarter where they see “record profits” (or have moments in the sun, as LG seems to be having with well-reviewed phones like their G3), these will be fleeting moments followed by “obsolescent models are overflowing in the showrooms then there are returns to the factory and suddenly huge losses generated”. “The brand and sales channel,” he argues, “is of far more value to one of the rising stars (mostly from China) who want to take over the world than to a legacy manufacturer who suddenly sees big losses.”



“One of the saddest stories in tech,” says Ahonen. He says that the Passport and Classic missed the mark, and that while they may find a home catering to the enterprise, either as a hardware vendor or as a pure software play, they’ll never return back to the top 10. They’re even slipping out of the top 20 right now.

Microsoft (the company formerly known as Nokia)


Just as he has a bit of a blind spot for Apple, Ahonen has a sore spot about Windows Phone. He can’t talk about it without seething with rage, and especially at the Microsoft exec-turned Nokia CEO-turned Microsoft exec Stephen Elop. We’ll condense his four paragraphs on this topic to:

  • They’re soooo dead. We still have no idea why 1/3 of Lumia phones haven’t been activated!
  • Microsoft can’t kill off their smartphone business now. The best thing they can do is fire the current Windows Phone executive VP of Devices and Services (Elop) and let some hapless, well-intentioned patsy run it into the ground.
  • Expect them to ditch the phone hardware division sometime in the next three years.

The other mobile OSs

firefox sailfish ubuntu

The short version: They don’t stand a chance.

The Company still known as Nokia

real nokia

Microsoft may have bought Nokia’s handset business, but they didn’t buy the entire company. There’s still a company called Nokia that makes networking equipment for carriers, mobile mapping and navigation technologies, and even mobile devices. Right now, they’re contractually forbidden from making smartphones under their own brand for another year or so, but they’ve put out a well-reviewed tablet. Ahonen believes that with their relationships with carriers and the right execution, Nokia could make an Android-powered comeback. As a bonus, he follows this with a (long, so very, very long) “Hollywood scenario” in which Nokia’s ability to turn dying businesses around (as they did with Siemens’ telecom and Motorola’s networking divisions) and the brand loyalty they’ve earned worldwide make it surpass Apple and become Samsung’s biggest rival. It reads like fan fiction, and even he admits that it’s a very unlikely scenario.

this article also appears in the GSG blog

Swift Kick

How to program an iOS text field that takes only numeric input with a maximum length [Updated]

Update (April 27, 2015)

updated article

Guess what — this article’s out of date. If you want the latest version of the code for programming constrained text fields in iOS with improved features, point your browser at the revised article, How to program an iOS text field that takes only numeric input or specific characters with a maximum length. It even comes with a sample app that you can download!

The original article

control fun app

One of my favorite ways to get a deeper understanding of programming in a given language or for a given platform is to pick up a highly-rated book for that language or platform and go through all the example tutorials and exercises, no matter how simple they seem. Although I often end up covering ground that I’ve gone over so many times before, I usually find that one or both of the following happen:

  • I end up learning something I didn’t know before, even in subject areas where I consider myself well-versed, or
  • I decide to see if I can improve the implementation or add a new feature, and in the process, learn about a feature new to me or figure out a new way to use a feature I’m already familiar with.

beginning ios development with swiftI got Apress’ Beginning iPhone Development with Swift for less than half price during their recent Cyber Monday sale, and I’ve been working through its tutorials during the holiday downtime. It’s a revision of a book released in late March 2014, Beginning iOS 7 Development (which I also own), updated to cover both a language and OS version whose first betas were released in June and whose 1.0 versions were made available in September. Given that the book was released in mid-November, they updated it in a hurry, which means that the book contains a few errors and oversights. In spite of this, I still recommend the book because:

  • The book is pretty much a straight “port” of an excellent book, Beginning iOS7 Development, for Swift and iOS 8, and
  • where some may see only errors and oversights, I also see learning opportunities.

The oversight

In chapter 4 of Beginning iPhone Development with Swift, whose title is More User Interface Fun, the exercise is to build an app that features a number of commonly-used user interface controls. The app you build starts with a couple of labels and text fields laid out so that they look like this:

name and number text fields

The user is supposed to be able to type in any kind of character into the Name text field, and only numeric characters into the Number field. The exercise in the chapter walks you through the process of setting the Keyboard Type of the Number field to Number Pad using the Storyboard and the Attributes Inspector:

setting keyboard type

While doing this goes a long way to preventing non-numeric input, it isn’t enough. On the iPhone, the Number Pad keyboard allows only digits to be entered…

ios 8 iphone number pad

…which works just fine if the user needs to enter positive whole numbers. If you want the user to enter negative numbers or use a decimal point, you’ll need to use the Numbers and Punctation keyboard, which features some additional characters. Here’s what it looks like on the iPhone:

ios 8 iphone numbes-punctuation keyboard

On the iPad, choosing either the Number Pad or Numbers and Punctuation keyboard gives you the same thing. It looks like this:

ipad number pad keyboard

These keyboards make it possible to enter some decidedly non-numeric input into the Number field.

copy and paste

If that weren’t enough, there’s also cut/copy and paste to contend with. The user can easily type an alphabetical string into the Name field, copy or cut it, and then paste it into the Number field. Clearly, you need to take more active measures if you want to ensure that a field meant for numeric input gets only numeric input.

Beginning iPhone Development with Swift points the way to a solution, but stops short. Here’s what the book says on page 110:

Tip    If you really want to stop the user typing anything other than numbers into a text field, you can do so by creating a class that implements the textView(_, shouldChangeTextInRange:, replacementText:) method of the UITextViewDelegate protocol and making it the text view’s delegate. The details are not too complex, but beyond the scope of this book.

This is wrong for two reasons:

  • I don’t think that disallowing unwanted characters from being input into a text field, which I think is a pretty basic UI feature in this day and age, is beyond the scope of the book, and
  • the method that should be used is part of the UITextFieldDelegate protocol, not the UITextViewDelegate protocol. As I said earlier, they rushed the production of this book.

In this article, I’m going to correct this oversight and show you how to do the following in iOS 8 and Swift:

  • Intercept the user’s input as s/he types or pastes into a text field
  • Allow only a specified set of characters to be entered into a given text field
  • Limit the number of characters that can be entered into a given text field
  • Confirm that the value entered into a text field is numeric

Intercepting the user’s input as s/he types or pastes into a text field


Creative Commons photo by Torsten Bolten, Click the photo to see the source.

Beginning iPhone Development with Swift was right: the way to really control what the user can enter into a text field is to implement this method in the UITextFieldDelegate protocol:

This method, called textField(_:shouldChangeCharactersInRange:replacementString:), is automatically called in view controllers that conform to the UITextFieldDelegate protocol whenever the user adds a new character to a text field or deletes an existing one. It gives you three parameters to work with:

  • textField: The text field whose contents are being changed
  • range: The range of characters to be replaced
  • string: The replacement string

If we want to accept the changes that the user made to the text field as-is, we have this method return true. If we don’t want to accept the changes, or if we want to alter them, we have this method return false.

In order to implement this method, we need to make the view controller conform to the UITextFieldDelegate protocol. We do this by adding UITextFieldDelegate the view controller’s declaration. In this example, the view controller is simply named ViewController, so we’ll added UITextFieldDelegate to its declaration like so:

In this example, the text field that we want to make “numbers only” is named numberField. We need to specify its delegate — the class containing the UITextFieldDelegate protocol methods that will be called whenever changes are made to its contents. We’ll specify that the view controller should be the delegate, and we’ll do it in the viewDidLoad() method:

Allowing only a specified set of characters to be entered into a given text field

Now that we have the view controller properly set up as a delegate for calls from the numberField text field whenever changes are made to its content, it’s time to implement textField(_:shouldChangeCharactersInRange:replacementString:). We want to implement it in such a way that the only characters that can be entered or pasted into numberField are the digits 0 through 9 and the . and characters.

Here’s the code:

The method starts off with the assumption that the user’s input is legal, and then applies the test to see if that’s actually the case. It then checks to see that the text field whose contents changed is numberField, the field whose content we want to restrict to numeric values. Next, it sees if the replacement string contains at least one character; if it doesn’t, there’s no point testing its content.

The method makes use of an NSCharacterSet instance to define the set of characters that we don’t want to allow inside numberField. Since the set of disallowed characters is much larger than the set of characters we want to allow in numberField,  we define the set by first creating an NSCharacterSet of allowed characters and use the invertedSet method.

Once we’ve defined a set of disallowed characters, we test the replacement string string to see if it contains any of them. If the replacement string string contains disallowed characters, string.rangeOfCharactersFromSet(disallowedCharacterSet) returns the range of the first disallowed character. If it doesn’t have any disallowed characters, it returns nil.

Limiting the number of characters that can be entered into a given text field

Now that we’ve restricted numberField to a small set of characters — the digits 0 through 9 and the . and characters — let’s set a maximum number of characters that numberField can contain; let’s make it 6.

Here’s what our code looks like with this new constraint:

First we determine the prospective text — that is, what the text field would contain if we allow the user’s changes. We do this by using the stringByReplacingCharactersInRange:withString: method, which accepts a range of characters to be replaced, and the string to replace that range of characters.

Note that we have to cast textField.text into an NSString first; that’s because Swift’s String class’ stringByReplacingCharactersInRange:withString: method expects a range in Range<String.Index> format, and we’re working with a range specified as an NSRange. Good ol’ NSString‘s stringByReplacingCharactersInRange:withString: method takes its range as an NSRange.

Once we have the prospective text, we simply check its length. If it’s greater than 6, we have the method return false, which means that the text field simply won’t accept any more than 6 characters.

Confirming that the value entered into a text field is numeric

Let’s add one more constraint to our text field: let’s make sure that only proper numeric values can be entered into the text field. Even though we’ve restricted the user to entering the digits 0 through 9 and the . and characters, it’s still possible to enter non-numeric values such as:

  • 1.2.3 (more than one decimal point), and
  • 4-5 (placing the unary minus anywhere other than at the start of the number).

Let’s add some code to disallow such entries:

What powers this constraint is NSScanner, which is a great tool for parsing string data. We’re using two of its methods:

  • scanDecimal(_:), which returns true if the scanner finds a valid NSDecimal representation in the string, and
  • atEnd, which returns true if the scanner has scanned the entirety of the string.

With the final code shown above, we’ve got a way to ensure that the user can enter only numeric values into a text field, and that those values no longer than a specified number of characters. Contrary to what was implied in Beginning iPhone Development with Swift, it wasn’t all that hard to do.


It’s 2015, the year when Windows Phone is supposed to take over!

Windows Phone floating in the sky over some trees: "I Want to Believe"
In 2012, I wrote an article about Pyramid Research’s predictions for the smartphone market in 2015.

Since then, I’ve been waiting for the first day of this magic year to write this blog post. That’s because back in 2011, mere days after leaving my roles in Microsoft Canada as a Developer Evangelist and Windows Phone Champ, Pyramid Research said that in 2015, Windows Phone would edge out Android to become the most-used mobile OS in the world, with nearly 40% of the market share:

smartphone market - pyramid research

Click the graph to read the article it was derived from.

Here’s what they wrote (with emphasis added by Yours Truly):

Now, a couple of words about the “controversial” projection itself. While we acknowledge the momentum that Android is experiencing and will continue to experience in 2011 and 2012, we believe that Nokia and Microsoft are a very powerful tandem, and that will show in its full force by the end of 2013. Some of the main obstacles to the growth of WP to date will be removed, as Nokia helps with bringing down the price of WP smartphones. Lower price of the devices will be the crucial prerequisite for the expansion of WP models.Nokia knows it and Microsoft knows it, and I am sure they will act on it quickly. It’s also worth mentioning that, apart from Nokia, quite a few other large handsets vendors in the world, such as Samsung, LG and Sony Ericsson are still placing their bets on WP. With the change in the price of WP devices, and the multivendor strategic approach of Microsoft, the main advantage of Android – scale – may be removed.

And although Nokia has suffered a significant loss from dragging out the Symbian story for too long, it’s Nokia we are talking about: They are big enough and strong enough to take on a couple of painful hits and come out of the struggle stronger than ever. They are in a good position to learn and adjust because they know what was bad about Symbian, what’s creating gains and what’s causing problems for Android, as well as what the upsides and downsides of a system such as that of Apple, where the OS only runs on hardware manufactured by the vendor.

Don’t forget that while being late to the party is rude, everybody gets to see you enter the room. When Nokia “enters the room” with new WP-based devices, there will likely be much traction about its new “clothes and shoes,” which will be a good jump start for the new era of WP devices.

IDC’s predictions for the 2015 mobile market weren’t quite so wacky. They predicted that Windows Phone wouldn’t claim the top spot, but be the runner-up OS, with 21% of the market:

smartphone market - idc

Gartner’s predictions were the least deluded. They predicted that Windows Phone and iOS would be roughly tied for second place, each with about a fifth of the mobile OS market:

smartphone market - gartner

Click the graph to read the press release it was derived from.

In case you weren’t sure how the mobile OS market share story turned out, here’s a graph made from data from IDC’s Smartphone OS Market Share, Q3 2014 report:

q3 2014 smartphone market - idc

Click the graph to read the report it was derived from.

It’s tough to make predictions, especially about the future, and let’s face it, I rely on data from analyst firms like Gartner and IDC in my line of work, but I do take everything they say with the appropriately-sized grain of salt. (I’m still a bit leery about Pyramid Research.) Over the past decade, the world of mobile has given us so many surprises and thrown us so many curve balls that it’s tough enough trying to predict what’ll come in the next year, never mind the next two or five.

And hey, there’s always a chance that Microsoft will rally and somehow grow Windows Phone’s share six over seven times over the next 364 days.