Categories
Swift Kick

How to dismiss the iOS keyboard when the user taps the background in Swift

tapping iphone

A quick recap

A couple of weeks ago, I posted an article that showed how to program an iOS text field that takes only numeric input or specific characters with a maximum length in Swift.

While that article focused on constraining what the user could enter into a text field, its example app has a couple of UI features that you’ll find in many apps:

  • It dismisses the keyboard when the user taps the Return key, and
  • it dismisses the keyboard when the user taps on the background.

Last week, I covered implementing the first of these two features in the article titled How to dismiss the iOS keyboard when the user taps the “Return” key in Swift. The one major takeaway from that article was that the way to dismiss the iOS keyboard after the user is editing a text field is to make the text field resign its role as first responder.

In that article, we dismissed the keyboard when the user tapped the Return key by doing the following:

  • We made the view controller adopt the UITextFieldDelegate protocol,
  • We made that same view controller the delegate for all text fields contained within its view, and
  • We implemented the delegate method textFieldShouldReturn(textField: UITextField), which is called when the Return key is tapped, and provides us a reference to the text field that was being edited when user tapped it:
// Dismiss the keyboard when the user taps the "Return" key or its equivalent
// while editing a text field.
func textFieldShouldReturn(textField: UITextField) -> Bool {
  textField.resignFirstResponder()
  return true;
}

In this article, we’ll look at how to dismiss the keyboard when the user touches the view in the background while editing a text field.

Dismissing the keyboard when you don’t know which text field is the first responder, but know which view the text field is in

The textFieldShouldReturn(textField: UITextField) method can be implemented to resign the first responder for a specific text field because a reference to that specific text field is passed to it. Unfortunately, we don’t get that information when the user taps on the view, and there’s no method or property in UIView that tells us which of the text field contained within it is the first responder.

In the Apress book Beginning iPhone Development with Swift, they take the “brute force” approach and implement a method that looks like this:

@IBAction func userTappedBackground(sender: AnyObject) {
  firstTextField.resignFirstResponder()
  secondTextField.resignFirstResponder()

  // ...more of the same...

  lastTextField.resignFirstResponder()
}

It works, but you need to update the method whenever you add a text field to or remove a text field from the view.

A more flexible approach is to loop through the contents of the view’s subviews property (an array of AnyObject), calling the resignFirstResponder() method for any text fields encountered along the way. I’ve seen code similar to this:

@IBAction func userTappedBackground(sender: AnyObject) {
  for view in self.view.subviews as! [UIView] {
    if let textField = view as? UITextField {
      textField.resignFirstResponder()
    }
  }
}

It works — as long as all the text fields in your view are immediate subviews of the view. If your view hierarchy runs deeper, you’ll have to write more code to deal with subviews or subviews. I’ll leave that as an exercise for the reader.

It turns out that there’s a simple and effective way to dismiss the keyboard for a view without knowing which text field is the first responder: call the view’s endEditing(_:) method. This method scours the view’s subview hierarchy, find the text field that is currently the first responder and asks it to resign that status. If its parameter is set to true, it forgoes the pleasantry of asking the text field to resign as first responder and simply makes it resign. If we use this method, our userTappedBackground method becomes very short and sweet:

@IBAction func userTappedBackground(sender: AnyObject) {
  view.endEditing(true)
}

Now that we have a method that dismisses the keyboard no matter which text field is the first responder, we need to hook it up to an event that gets fired whenever the user taps on the view.

Responding to taps on the view

These next steps will show you how to use Interface Builder to change a view so that it can respond to events, and then connect that view to the userTappedBackground method we just created.

01

1. Go to the storyboard and select the view.

2. Switch to the Identity Inspector. You can do this by either:

  • Clicking on the Identity Inspector icon (shown beside the number 2 in the screenshot above; I think the icon is meant to look like photo ID) in the Inspector Bar at the top of Xcode’s Utilities Area, or
  • Pressing command-option-3 on your keyboard.

3. In the Identity Inspector’s Custom Class section, you’ll find the Class drop-down menu. It indicates the underlying class of any object in the storyboard, and it also lets you change it. If you have the view selected, the Class drop-down menu will display UIView. We’ll change this in a moment, but let’s take a quick detour first.

02

4. With the view still selected, switch to the Connections Inspector. You can do this by either:

  • Clicking on the Connections Inspector icon (indicated by the number 4 in the screenshot above) in the Inspector Bar at the top of Xcode’s Utilities Area, or
  • Pressing command-option-6 on your keyboard.

5. Take a look at the available connections for the view. You can make a couple of different of kinds of connections, but none of them are for events. We need to make event connections available to the view, which we’ll do in the next few steps.

03

6. Switch back to the Identity Inspector.

7. Make sure that the view is still selected.

8. Change the value in the Class drop-down from UIView to UIControl. This changes the view’s underlying class, as you may have guessed, from UIView to UIControl. We’ll see the effect of this change in a moment…

04

9. With the view still selected, switch to the Connections Inspector.

10. Make a note of the available connections for the view. Since the underlying class for the view is now UIControl, it has UIControl‘s connections available to it, which include events.

We want to dismiss the keyboard as soon as the view gets a Touch Down event. We use this event rather than Touch Up Inside (the one we typically use for buttons) because we want to dismiss the keyboard as soon as the user taps the view without first waiting for him/her to release or move his/her finger.

5

11. Drag from the Touch Down event to the View Controller icon above the view.

12. A list of action methods in the view controller (any method prefaced with @IBAction is an action method) will appear. Select userTappedBackground:.

6

13. If you look at the Identity Inspector now, you’ll see that the Touch Down event is now connected to the view controller’s userTappedBackground method, and when you run the app, tapping on the view dismisses the keyboard.

Bonus: Dismissing the keyboard when you don’t even know which view the text field is in

There may come a time when you need to dismiss the keyboard from code that:

  • doesn’t have a reference to the text field that’s currently the first responder and
  • doesn’t even have a reference to the view that contains that text field.

In such a case, use this line of code:

UIApplication.sharedApplication().sendAction(
  "resignFirstResponder", to:nil, from:nil, forEvent:nil)

Here’s what happens in this line:

  • UIApplication.sharedApplication() gets a reference to the instance of the app itself.
  • sendAction(_:to:from:forEvent:) sends an action message to a target object within the app. If the target (the to: parameter) is nil, the message — resignFirstResponder in this case — gets sent to whatever object in the app is currently the first responder.

My guess is that this approach is more computationally heavy that calling a view’s endEditing(_:) method, so use that if you have a reference to the view, and use the approach above when you don’t.

Resources

zip file iconYou can see this code in action by downloading the zipped project files for the demo project, ConstrainedTextFieldDemo [83K Xcode project and associated files, zipped].

Categories
Uncategorized

Cramming, and how you might be eligible for a refund from Sprint and Verizon

What’s cramming?

cramming

Cramming is the very apt name for a form of fraud where third parties unauthorized charges are added to your wireline, wireless, or bundled services telecom bills. Crammers rely on the combination of telecom bills being so confusing and making sure that the charges they add — often with vague, yet plausible-sounding names — are small enough not to raise suspicion. The FCC (Federal Communications Commission) says that cramming affects tens of millions of household in the U.S., and a Senate Commerce Committee investigation released a report in 2011 that said that cramming costs U.S. consumers $2 billion a year.

The FCC’s web page on cramming provides examples of what these unapproved charges can look like:

  • Charges for services that are explained on your telephone bill in general terms such as “service fee,”  “service charge,” “other fees,” “voicemail,” “mail server,” “calling plan” and “membership.”
  • Charges that are added to your telephone bill every month without a clear explanation of the services provided – such as a “monthly fee” or “minimum monthly usage fee.”
  • Charges for specific services or products you may not have authorized, like ringtones, cell phone wallpaper, or “premium” text messages about sports scores, celebrity gossip, flirting tips or daily horoscopes.

Cramming came about when telecom carriers saw an opportunity to increase their profits by acting like credit cards. They now allow third parties to charge customers through their telecom bills, treating their phone numbers like credit card numbers, and they collect a small percentage of the transaction. While convenient for customers and lucrative for carriers, this introduces a number of opportunities for fraud. While credit card numbers are treated as confidential, phone numbers are published openly; some crammers have made money simply by charging phone numbers obtained from directories while others incentivize people into divulging their phone numbers through fake contests and offers.

The key to protecting yourself from cramming is to pay close attention to your phone bill. Review it as closely as you’d review your credit card statement, and ask yourself these questions:

  • Are there any names of companies on your phone bill that you don’t recognize?
  • Does your bill include charges that can’t be accounted for — calls you didn’t make or services you didn’t sign up for?
  • Are there small “mystery charges”, typically less than $10, and often as little as $1, with non-descriptive names that don’t seem to be tied to any service that you’ve signed up for?
  • Are the rates and line items that appear on your bill consistent with the rates and line items that you were quoted?

If you’re thinking about signing up for a service that charges you through your phone bill, be sure to read the fine print. If you’re thinking of signing up for a service that texts you things like “love tips”, “fun facts” and “celebrity gossip”, think again: last year, a crammer by the name of Andrew Bachman was found to be cramming users at $9.99 a month for these services without their approval.

You should also keep a record of all services that you subscribe to that charge via your phone bill.

A settlement for Sprint and Verizon customers

hands holding smartphones

The FCC, along with the CFPB (Consumer Financial Protection Bureau) and state attorneys general have been pursuing cramming activity in telecom bills, charging the third parties involved in cramming and issuing over $350 million in penalties to the “Big Four” carriers, more than $250 million of which was returned to affected customers.

On May 12, 2015, it was announced that…

  • Sprint Corporation will pay $68 million and
  • Verizon will pay $90 million

to settle investigations that showed that they were party to third parties billing customers hundreds of millions of dollars in unauthorized third-party premium text-messaging services, a.k.a. cramming. $120 million of the sum of their payments will be repaid to customers, and you may be due for some of that payback! If you’ve been a customer of Sprint, Sprint’s prepaid subsidiaries (Virgin Mobile, Boost Mobile, Sprint prepaid, and Assurance Wireless) or Verizon in the past five years, you may be eligible:

  • If you might be an eligible Sprint (or subsidiary) customer, visit their site at sprintrefundpsms.com or call the Sprint settlement hotline 1- 877-389-8787. Sprint customers should use the claims form in the FAQ section, and subscribers to Sprint’s prepaid subsidiaries (once again, Virgin Mobile, Boost Mobile, Sprint prepaid, and Assurance Wireless) can file for a one-time $7 refund.
  • If you might be an eligible Verizon customer, visit their site at CFPBSettlementVerizon.com or call the Verizon settlement hotline at 1-888-726-7063.

this article also appears in the GSG blog

Categories
Swift Kick

How to dismiss the iOS keyboard when the user taps the “Return” key in Swift

dismissing ios keyboard with return key

A quick recap

A couple of weeks ago, I posted an article that showed how to program an iOS text field that takes only numeric input or specific characters with a maximum length in Swift.

It covered the Delegate pattern (something you’ll use often in iOS development), introduced the UITextFieldDelegate protocol, and showed you how to use one of its methods, textField(_:shouldChangeCharactersInRange: replacementString:), to intercept the characters that the user inputs into text fields.

zip file iconThe article included the Xcode project files for the featured app, ConstrainedTextFieldDemo. You can download it here [83K Xcode project and associated files, zipped]. When you run it, you’ll the screen pictured above, with text fields constrained so that they’d accept only characters from a specified set, or reject characters from a specified set.

Undocumented feature : Dismissing the keyboard when the user taps the “Return” key

One of the features that was included in the app but discussed only in passing was the dismissal of the keyboard when the user tapped the Return key. While this is convenient for the user, it’s not iOS’ default behavior. You have to watch for the event where the user taps the Return key, and then respond accordingly.

The UITextFieldDelegate protocol’s textFieldShouldReturn(textField: UITextField) method is called whenever the user taps the Return key while editing a text field. It accepts a single parameter, textField, which is a reference to the text field the user was editing when s/he tapped the Return key. It returns a bool — true if the text field should implement its default behavior for the Return key; otherwise, false otherwise. It’s where you should place code to intercept the Return key event.

What should that code be? If you remember only one thing from this article, let it be this:

The way to dismiss the iOS keyboard after the user is editing a text field is to make the text field resign its role as first responder.

What’s the first responder, you ask?

  • The short answer is that the UI object that currently has the first responder role in iOS is roughly analogous to the UI object that currently has the focus in other systems (such as Android, HTML, and .NET).
  • The long answer is that the first responder is the first view in the responder chain to receive many events. Most of the time, it’s the view in a window that an app deems best suited for handling an event. You can find out more by reading these Apple documents: Event Delivery: The Responder Chain and their Responder object documentation.

Take a look at code in the example app in my earlier article, particularly ViewController.swift.

Combining the textFieldShouldReturn(textField: UITextField) method and The One Thing You Should Remember From This Article, we get this method definition:

// Dismiss the keyboard when the user taps the "Return" key or its equivalent
// while editing a text field.
func textFieldShouldReturn(textField: UITextField) -> Bool {
  textField.resignFirstResponder()
  return true;
}

After all that preamble, the method itself seems pretty short and anticlimactic. This method lives in the ViewController class, which has adopted the UITextViewDelegate protocol…

class ViewController: UIViewController, UITextFieldDelegate {

…and in its viewDidLoad() method, it declared itself as the delegate of every text field in the corresponding view:

// Designate this class as the text fields' delegate
// and set their keyboards while we're at it.
func initializeTextFields() {
  vowelsOnlyTextField.delegate = self
  vowelsOnlyTextField.keyboardType = UIKeyboardType.ASCIICapable

  noVowelsTextField.delegate = self
  noVowelsTextField.keyboardType = UIKeyboardType.ASCIICapable
  
  digitsOnlyTextField.delegate = self
  digitsOnlyTextField.keyboardType = UIKeyboardType.NumberPad
  
  numericOnlyTextField.delegate = self
  numericOnlyTextField.keyboardType = UIKeyboardType.NumbersAndPunctuation
  
  positiveIntegersOnlyTextField.delegate = self
  positiveIntegersOnlyTextField.keyboardType = UIKeyboardType.DecimalPad
}

All this setup means that whenever the user edits any of the text fields in the view — whether it’s vowelsOnlyTextFieldnoVowelsTextFielddigitsOnlyTextFieldnumericOnlyTextField, or positiveIntegersOnlyTextField — and then hits the Return key, the textFieldShouldReturn(textField: UITextField) method gets called.

And when the textFieldShouldReturn(textField: UITextField) method, it does just two things:

  • It tells the text field to resign its first responder role (by invoking its resignFirstResponder() method). In this application, we want the keyboard to disappear when the user taps the Return key regardless of the text field, so we don’t bother trying to identify the text field; we simple call textField.resignFirstResponder().
  • Aside from dismissing the keyboard, we want the Return key to function as it normally would, so we have the method return true, which states that text field should implement its default behavior.

Resources

zip file iconOnce again, here are the zipped project files for the demo project, ConstrainedTextFieldDemo [83K Xcode project and associated files, zipped].

 

 

Categories
Uncategorized

Remote wipes and why you need a BYOD policy

The case of
Rajaee v. Design Tech Homes, Ltd.

smartphone - eraser on screen

In 2012, Saman Rajaee started work as a Houston-area salesman for Design Tech Homes, a Texas-based house-building firm. Design Tech didn’t provide mobile phones for their workers, and asked them to use their personal devices instead.

Rajaee used his iPhone 4 not only for work-related voice calls, but for work-related email as well. That meant connecting his iPhone to Design Tech’s Microsoft Exchange Server. Doing so requires an exchange (if you’ll forgive the pun) of privileges; in exchange for access to company resources from your mobile device, the server is granted the ability to enforce security policies on that device. One of those policies is remote wipe, which allows the server to completely erase the contents of a mobile device connected to it, and restoring it to its original factory “fresh out of the box” settings.

At the start of February 2013, Rajaee gave Design Tech his two weeks’ notice, and Design Tech immediately terminated him. A few days later, Design Tech’s system administrator issued the remote wipe command to Rajaee’s iPhone, which erased everything on it, both work-related and personal.

keep calm and i'll see you in court

Rajaee sued Design Tech, claiming that what they did caused him to lose contact information for hundreds of business contacts and family (much of whom lived overseas), business information, passwords, and irreplaceable personal data, including family photos and videos. He said in performing the remote wipe, Design Tech violated the Electronic Communications Privacy Act, the Computer Fraud and Abuse Act and Texas Theft Liability Act. In response, Design Tech filed a motion requesting a summary judgement.

The case was decided in Texas Federal Court, and Design Tech was able to get the case dismissed in November 2014. Their victory was based on these points:

  • A holding from the 5th U.S. Circuit Court of Appeals says that information that an individual stores on a hard drive or mobile device isn’t considered to be in electronic storage according to the definition of the term in the Electronic Communications Privacy Act (ECPA). The court determined that the personal data stored on Rajaee’s iPhone was not legally protected and hence his claim under the ECPA was dismissed.
  • To be considered a violation of the Computer Fraud and Abuse Act (CFAA), Rajaee needed to prove that the remote wipe caused him a loss of at least $5,000. Rajaee said that the personal photos, videos, and messages were worth more than that, but Design Tech’s lawyers were able to establish that Rajaee just couldn’t demonstrate that the loss of that data was worth $5,000 or more, nor was he able to show any evidence of costs incurred to investigate or respond to the remote wipe, which led to his claim under the CFAA also being dismissed.
  • The last leg of Rajaee’s case, the Texas Theft Liability Act, vanished since the court was a federal one and the law is a state law. The court declined to, in legalese, “declined to exercise supplemental jurisdiction over the remaining state law claims.”

lawyer showered in money

The only people who walked away happy from the case were the lawyers. Rajaee lost irreplaceable data and mementoes, not to mention time doing whatever re-setting up he had to do on his iPhone, and both parties spent time and money on the case, with Design Tech spending a lot of money on a big-name law firm.

What both sides did wrong

iphone 4

Rajaee’s biggest mistake is one that a lot of us make: failing to back up his phone. Even in those long-ago days of 2013 — that’s almost 10 internet years ago! — backing up an iPhone was pretty much an automatic process, either via services like iCloud, or plugging into your computer and backing it up through software like iTunes, which can be set up to do so automatically as soon as you hook up the USB cable. In a world where precious memories like personal photos and videos are digital and hard drive and cloud storage space is cheap and plentiful, you’re a fool if the one and only place they live is your phone.

remote wipe

Design Tech made a couple of mistakes. The first one was performing the remote wipe. Remote wipes are the nuclear option of mobile security. They’re meant to be used if and only if the phone is believed to be irretrievably lost, in which case it’s a security risk since it has access to corporate resources. Design Tech’s system administrator could’ve simply revoked Rajaee’s iPhone’s access to the Exchange server, which would simply make the Design Tech email messages, contacts, and calendar access disappear, without affecting or altering any of the phone’s other settings. Given that Design Tech’s response to Rajaee giving them two weeks’ notice was to terminate him immediately, it’s not hard to imagine them giving their sysadmin the order to issue the remote wipe command out of spite.

Design Tech’s second mistake was not having a mobile policy that its employees and contractors could agree to and sign.

Having a BYOD (Bring Your Own Device) policy is the best policy

signed policy

If your organization is going to allow employees to use personal mobile devices for work — that’s smartphones, tablets, and any other portable device that runs what’s considered to be a mobile operation system (Android, iOS, or Windows Phone, to cite a few examples) — you’ll need to:

  • First consider how you’d want employees to use their personal devices for work. Will they simply be taking voice calls? Accessing corporate email, contacts, calendar, or some combination of the three?
  • Write down those ways you’d want employees to use their personal devices at work in a BYOD policy. Spell out what is and isn’t acceptable use. State that when an employee connects his/her device to the corporate network and/or using it for company business, that s/he is granting access to the device to the organization.
  • Spell out the conditions that would necessitate revoking the device’s access to the corporate network. Spell out the conditions that would necessitate a remote wipe. If you don’t want to be a jerk, make it so that the conditions for a remote wipe are something akin to the device being irretrievably lost.
  • Educate employees about the BYOD policy, and make those who want to use their personal devices at work sign it.
  • Document everything: the policy itself, the processes and technology that enforces it, and the education process. Keep the signed policies in your records.

By having a BYOD policy, you can avoid the risk of a Rajaee v. Design tech Homes, Ltd. situation and save a lot of money, headaches, and your reputation.

If you need more convincing, take a look at our white paper titled No More Excuses: Why Your Business Needs a Mobile Policy. It looks at the most common excuses for not having one, which run the gamut from “I don’t know what to include in a policy” to “It’s an HR thing” to “We have BYOD”, and explains why they don’t let you off the hook. You’ll also get some first steps that you should take once you’ve said “no more excuses!”

this article also appears in the GSG blog

Categories
Uncategorized

My Marc Andreessen regret and his profile in The New Yorker

marc andreessen in the new yorker

Click the photo to read Marc’s profile in The New Yorker.

My Marc Andreessen regret

I have only a few regrets in my colorful career, and one of them not figuring out a way to turn the time Marc Andreessen reached out to me into something bigger.

In the fall of 2005, when I was just about to get married for the first time, I received an email from a “pmarca” from a domain I’d never heard of before. In the body, some guy claiming to be Marc Andreessen said that he was looking for a developer evangelist for a new company that was still in stealth mode. I initially dismissed it as a prank, but then thought better of it, and soon discovered that yes, it was the Marc Andreessen, and that company turned out to be Ning. A few email back-and-forths turned into a fantastic and fun phone interview with Gina Bianchini (Ning’s co-founder, and now entrepreneur in residence at Andreessen Horowitz) about becoming their North American developer relations guy, which included the possibility of moving to California to help them out with their venture.

A couple of weeks later, the possibility of that job had diminished greatly, as Marc and Gina had to get their burn rate under control. Marc suggested that I could take on the task of writing some example Ning apps, but I had so much going on between my job at Tucows and being newly-married to a wife who’d just moved to town and knew almost nobody. I figured that I didn’t have the bandwidth for the extra work — at least not without compromising the then-current job or the marriage. Those of you who know me know that the Tucows position is several jobs ago, and I’m now married to someone else, and every now and again, I kick myself for not finding a way to stay in the back of Marc’s mind for his later efforts.

Takeaways from Marc’s profile in The New Yorker, Tomorrow’s Advance Man

marc andreessen - vision and hallucination

Found at OnePowerfulWord.com. Click the picture to see the source.

The May 18, 2015 edition of The New Yorker features Tomorrow’s Advance Man, a profile of Marc Andreessen that also provides a look into his venture capitalist firm Andreessen Horowitz, VCs in general, and the money that stokes the machinery of Silicon Valley.

A quick cut/paste/save/wc says that it weighs in at a hefty 13,442 words and 67 minutes’ reading according to Read-O-Meter. Don’t let the tl;dr demon scare you away; it’s a worthwhile read. Spread it out over a couple of lunches or coffee sessions if you need to, because there are some insights that you’ll find useful if you’re the tech industry (as most of this blog’s readers are).

My top takeaways from the article are:

  1. Don’t take it from me, take it from Kevin Kelly: “If you are going to deal with VCs, this profile of Marc Andreessen with fill in the blanks. Long but worth it.”
  2. I knew about Andreessen Horowitz’ short name for itself — a16z — derived from the fact that there are 16 letters between the starting “A” and the closing “z”. It borrows from the term i18n, which shortens the word internationalization in the same manner. What I didn’t know was the short name that A16z’s competitors preferred: AHo, as in “a-hole”.
  3. Want to get media attention? Be noisy on Twitter. Marc tweets more than 100 times a day because “Reporters are obsessed with it. It’s a like a tube and I have loudspeakers installed in every reporting cubicle around the world.” If you’d like to see examples, see A16z’s list of Marc’s top tweetstorms of 2014.
  4. Reading between the lines — a strength that many technically-oriented people lack, and even the most-people savvy forget how to do so in stressful situations — is doubly important when dealing with VCs. They speak euphemistically, often using understatement as a weapon, writes the article’s author, Tad Friend. “You’re definitely going to get funded!” means “But not by us.” “Who else is in?” means “Besides not us.” And “I’m not sure I would ever use your product myself” means “So long!”
  5. Marc grew up far from any major tech center, growing up in Wisconsin in an atmosphere of “antiquity, superstition, frustration, and penury”. Tad Friend writes that his vision of the future came from television, with Star Trek and the decidedly less cerebral (but still inspiring) Knight Rider. Even today, he still seems to get some inspiration from TV, as the references to the TV series Halt and Catch Fire, which Marc and Tad watched together, indicate.
  6. He’s an optimist who thinks big, and in order to get his attention, you’d better be ready to do the same: “We’re not funding Mother Teresa. We’re funding imperial, will-to-power people who want to crush their competition. Companies can only have a big impact on the world if they get big.”
  7. The real problems are never the technical ones. The people issues are always waaaay more complex.
Categories
Uncategorized

Some days, it feels like this…

welcome to my world

…and I think I’m gonna need a bigger shovel.

Adapted from Pete Cheslock’s graphic, which I found I found via Leigh Honeywell.

Categories
Swift Kick

My “How to work with dates and times in Swift” articles (so far)

dates and times in swift

My articles on working with dates and times in Swift have steadily been getting more readers, so I thought I’d gather all the links to them in one place and make them easier to find. I’m also in the process of gathering the content of these articles and pulling them together into a date/time utility module, which I’ll post on GitHub. I’ll let you know when that happens!

In the meantime, my “How to work with dates and times in Swift” articles (so far):

A very brief introduction to date formatting in Swift and iOS: The oversight in a mostly-good book on Swift programming led me down the path of writing articles about dates and times in Swift, starting with this one, where I look at NSDateFormatter.

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.

Click the chart to see it at full size.