Categories
Florida Swift Kick

Swift programming tip: How to execute a block of code after a specified delay

burning fuse
swift kick

Sometimes, you want some code to execute after a specified delay. For me, this happens often in user interfaces; there are many cases where I want some notification or other interface element to appear and then disappear after a couple of seconds. I used to use an NSTimer to make it happen, but nowadays, I call on a simple method called delay().

Consider the simple “Magic 8-Ball” app design shown below:

magic 8-ball app

The two functional interface items are the Tap me button and a label that displays a random “yes/no/maybe” answer in response to a button tap. The button should be disabled and the answer should remain onscreen for three seconds, after which the app should revert to its initial state, with the button enabled and the answer label blank.

Here’s the action method that responds to the Touch Up Inside event on the “Tap me” button:

@IBAction func buttonClicked(sender: UIButton) { 
  tapMeButton.enabled = false
  predictionLabel.text = randomAnswer()
  delay(3.0) {
    self.tapMeButton.enabled = true
    self.predictionLabel.text = ""
  }
}

Don’t worry too much about the randomAnswer() method; it simply returns a randomly-selected string from an array of possible answers. The really interesting method is delay(), which takes two parameters:

  • A number of seconds that the system should wait before executing a block of code. In this particular case, we want a 3-second delay.
  • The block of code to be executed after the delay. In our block, we want to blank the label and enable the button.

The block of code that we’re passing to delay() is a closure, which means it will be executed outside the current ViewController object, which in turns means that we’ve got to be explicit when capturing variables in the current scope. We can’t just refer to the button and label as tapMeButton and predictionLabel, but by their fully-qualified names, self.tapMeButton and self.predictionLabel.

Here’s the code for delay():

func delay(delay: Double, closure: ()->()) { 
  dispatch_after(
    dispatch_time(
      DISPATCH_TIME_NOW,
      Int64(delay * Double(NSEC_PER_SEC))
    ),
    dispatch_get_main_queue(),
    closure
  )
}

delay() is just a wrapper for dispatch_after(), one of the functions in Grand Central Dispatch, Apple’s library for running concurrent code on multicore processors on iOS and OS X. dispatch_after() takes three parameters:

  • How long the delay should be before executing the block of code should be,
  • the queue on which the block of code should be run, and
  • the block of code to run.

We could’ve simply used dispatch_after(), but it exposes a lot of complexity that we don’t need to deal with. Matt Neuburg, the author of the O’Reilly book iOS 9 Programming Fundamentals with Swift, found that he was using dispatch_after() so often that he wrote delay() as a wrapper to simplify his code. Which would you rather read — this…

dispatch_after(
  dispatch_time(
    DISPATCH_TIME_NOW,
    Int64(3.0 * Double(NSEC_PER_SEC))
  ),
  dispatch_get_main_queue(),
  {
    self.tapMeButton.enabled = true
    self.predictionLabel.text = ""
  }
)

…or this?

delay(3.0) {
  self.tapMeButton.enabled = true
  self.predictionLabel.text = ""
}

Here’s the code for the example “Magic 8-Ball” app, which I’ve put entirely in the view controller for simplicity’s sake:

//
// ViewController.swift
//

import UIKit


class ViewController: UIViewController {

  @IBOutlet weak var tapMeButton: UIButton!
  @IBOutlet weak var predictionLabel: UILabel!
  
  let predictions = [
    "Yes.",
    "Sure thing.",
    "But of course!",
    "I'd bet on it.",
    "AWWW YISSS!",
    "No.",
    "Nuh-uh.",
    "Absolutely not!",
    "I wouldn't bet on it.",
    "HELL NO.",
    "Maybe.",
    "Possibly...",
    "Ask again later.",
    "I can't be certain.",
    "Reply hazy. Try again later."
  ]
  
  override func viewDidLoad() {
    super.viewDidLoad()
    predictionLabel.text = ""
  }

  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }

  @IBAction func buttonClicked(sender: UIButton) {
    
    // When the "Tap me" button tapped,
    // we want to:
    // 1. Disable the button
    // 2. Display a random magic 8-ball answer
    // 3. Wait 3 seconds, and then:
    //    a) Enable the button
    //    b) Clear the displayed answer
    
    tapMeButton.enabled = false
    predictionLabel.text = randomAnswer()
    delay(3.0) {
      self.tapMeButton.enabled = true
      self.predictionLabel.text = ""
    }
  }
  
  func randomAnswer() -> String {
    return predictions[randomIntUpToButNotIncluding(predictions.count)]
  }
  
}


// MARK: Utility functions

func delay(delay: Double, closure: ()->()) {
  
  // A handy bit of code created by Matt Neuburg, author of a lot of books including
  // iOS Programming Fundamentals with Swift (O'Reilly 2015).
  // See his reply in Stack Overflow for details:
  // http://stackoverflow.com/questions/24034544/dispatch-after-gcd-in-swift/24318861#24318861
  //
  // The secret sauce is Grand Central Dispatch's (GCD) dispatch_after() function.
  // Ray Wenderlich has a good tutorial on GCD at:
  // http://www.raywenderlich.com/79149/grand-central-dispatch-tutorial-swift-part-1
  
  dispatch_after(
    dispatch_time(
      DISPATCH_TIME_NOW,
      Int64(delay * Double(NSEC_PER_SEC))
    ),
    dispatch_get_main_queue(),
    closure
  )
}

func randomIntUpToButNotIncluding(count: Int) -> Int {
  return Int(arc4random_uniform(UInt32(count)))
}

Resources

zip file iconYou can see this code in action by downloading the zipped project files for the demo project, DelayDemo [220K Xcode 7 / Swift 2 project and associated files, zipped].

If you’d like to learn more about coding for concurrency with Grand Central Dispatch, a good starting place is the tutorial on Ray Wenderlich’s site. It’s a two parter; here’s part 1, and here’s part 2.

I found Matt Neuburg’s delay() method in his answer to this Stack Overflow question.

Categories
Uncategorized

BlackBerry CEO John Chen’s awkward demo of the BlackBerry Priv

BlackBerry CEO John Chen’s demo of the Priv to BNN’s Amber Kanwar, their new Android-based QWERTY phone, should’ve been the bright spot in a bad news-filled day (they’d missed their 2Q15 target, for which the bar was already pretty low). Unfortunately, he was unprepared, improvising, and working with a device that hadn’t yet been fully set up and whose OS was unfamiliar to him.

The Android OS that the Priv runs on was so new to him that he had trouble launching Chrome, which meant that he couldn’t do a proper demo of the keyboard’s capacitive-touch scrolling, and the swiping motions he was using had no effect because they were BlackBerry 10 gestures. The most telling thing, however, was his saying that the Priv “runs Google“.

The “priv [rhymes with give] stands for privacy” line was also painful, and it telegraphs Chen’s general unpreparedness for Amber Kanwar’s questions in the rest of the video. I understand that he’s got a lot on his plate, but maybe it’s time for someone else to do these demos, and let Chen focus on his reputed turnaround magic.

blackberry priv

If you take away just one lesson from this video, let it be this: if you’re expected to demo something that’s new to you (like a new product that uses an operating system you normally don’t use), you need to practice, practice, and practice again. If you want to take away an additional lesson, it’s that you should try to anticipate the questions you’ll be asked, and try to have some answers — or be ready to change the topic.

Categories
Uncategorized

Catch our free “Dark Mobile” webinar tomorrow at 1:00 p.m. eastern!

dark mobile

Tomorrow — Tuesday, September 29th — at 1:00 p.m. eastern (10:00 a.m. Pacific), GSG and Enterprise Mobile will host a webinar titled The Secrets Nobody Tells You About Dark Mobile. It’s free to attend, and you can register here.

In this webinar, GSG’s Platform Evangelist Joey deVilla will talk about that area of an organization’s mobile telecom environment that goes, unobserved, unknown, or unmanaged — the terra incognita that we call “Dark Mobile”. We look at the negative effects it has on a company’s…

  • spending,
  • management,
  • security, and
  • efficiency

Join us in this quick webinar (it’ll be about half an hour) as we look at the four kinds of Dark Mobile and how we can shed some light into this crucial area of your IT environment.

this article also appears in the GSG blog

Categories
Uncategorized

VarageSale is looking for a community manager based in Central Florida

varagesale - community manager

My friend Sarah Baird is the COO of the Toronto-based startup VarageSale, an online, local-focused marketplace that competes with Craigslist by focusing on mobile platforms. VarageSale has expanded to cover all of Canada and most states in the U.S., and now they’ve got their eyes on Florida. In order to establish a presence here, they need a community manager, and they’re looking for one based in Central Florida.

varagesale app

VarageSale — that’s short for “Virtual Garage Sale” — is the brainchild of Tami Zuckerman, who came up with the idea out of frustration while trying to clear out her house by selling stuff through Craigslist and similar marketplace sites. She and her husband developed an app that helped her sell her excess stuff with her smartphone, and while they didn’t start out intending to create a business, the idea grew into one.

VarageSale connects people through their Facebook profiles, and uses volunteer moderators to approve new members. You post items for sale and an asking price, and the app lets prospective buyers comment, haggle over price, or say “sold”! The service has grown in popularity, the Canadian tech news site TechVibes named them Canadian Startup of the Year for 2014, and in March, they raised $34 million in venture money from Sequoia Capital and Lightspeed Venture Partners. So to answer a question you might have already asked: yes, it looks like they’ve got a future.

I’ll personally vouch for VarageSale’s Chief Operating Officer, Sarah Baird, as someone who knows how to get things done. I know her through my developer evangelism work in Toronto with Tucows, Microsoft, and Shopify, and through her work at Interactive Ontario (a not-for-profit industry trade organization that encourages the growth of the interactive digital content industry in the province of Ontario), the social game development shop Social Game Universe, and at various industry events in Toronto’s thriving tech scene. She gets stuff done, and my feeling is that so will any company that where she’s COO.

florida - toronto

If you get the job, you’ll be working remotely from Florida and in regular communication with the team at the head office in Toronto, Canada, which you’ll have to visit from time to time (it’s a great city). You’ll be part of the Growth Team and the “face” of VarageSale in the Sunshine State, get people hooked up with VarageSale and building up the community of Floridians who use it to buy and sell things. You’ll be part of their global expansion effort and working closely with their Launch, Marketing, and Happiness Teams to kick off their push in Florida and building and nurturing Florida’s VarageSale communities on an ongoing basis.

Some things about the community manager job (these are distilled from their job posting):

  • You’ll need to be able to communicate your passion and care for the community not just in person, but, more importantly, online.
  • You have to be comfortable being the celebrity in the grocery store and the go-to online resource for all VarageSale communities. This is a job for someone who can get in front of a crowd, “shake hands and kiss babies”, and get them to take action — namely, using VarageSale and getting them to get other people to use it as well.
  • Your job will be to grow VarageSale communities in Florida. This means building bases of users all over the state, finding and cultivating influencers to help get the word out, and organizing and hosting VarageSale events. That means showing up, which in turn means you’ll have to do some traveling.
  • You should be comfortable working remotely in a startup culture, and you should have some marketing and/or community management experience. If you’ve ever had to be the “face” of a product or service, that’s even better. And you’ll need to know how to work a community.

If this sounds like your kind of gig, go to their Florida Community Manager job page and apply now! Tell them Joey sent you.

Links you might find usefulvaragesale icon

This article also appears in The Adventures of Accordion Guy in the 21st Century.

Categories
Uncategorized

Thoughts on Apple, Microsoft, and tablets from an ex-Microsoftie

A disturbance in the Force

Because I had Star Wars on the brain at that moment, when I saw the announcement that the iPad Pro would feature keyboard cover and stylus accessories, this twist on a famous Obi-Wan Kenobi quote came to mind:

disturbance in the tablet market

…and if you Google (or Bing, if you must) around, you’ll hear these cries of annoyance. Hey, I’m expecting a few myself, just for that “hundreds of Surface users” jab. I kid because I care.

Sometimes, the future predicted in jest comes true

five blades

Click the image to see it at full size.

When it comes to predictions made in jest that came true, The Onion can claim the throne. Back in 2004, when four blades was considered to be a wacky maximum, they ran an op-ed that purported to have the CEO of Gillette up the ante by announcing a five-blade razor. If you’ve been to the drugstore lately, you know it’s no longer a joke.

(I don’t want to wade too deep into political waters in this article, but they were even more bang-on with their January 2001 joke prediction titled Bush: ‘Our Long National Nightmare Of Peace And Prosperity Is Finally Over’.)

The now-defunct webcomic Hijinks Ensue seems to have had an equally eerily prescient moment in this comic from back in June 2012:

hijinks ensue comic

The strangely prophetic Hijinks Ensure comic from 2012.
Click the comic to see it at full size.

Before you go all “rabid Apple fan” and compose an angry reply on his site, you may want to look at the notes that went along with the comic. Here are some excerpts:

As an unapologetic Apple fanboy, I am probably not the most expected source for seemingly anti-Apple sentiment. But a fact is a fact, and chief among Apple’s key strategies is waiting for years after a new service, feature or function is adopted and implemented by EVERY other competitive platform before putting their own spin on it and taking all the credit as if it were their own invention. They are almost always the last to the party, but they are always the best dressed, the most interesting, the sexiest and the only one everyone remembers the next day.

I don’t fault Apple for this type of behavior because all they are really doing is letting the other guys take the risks and make the mistakes and gauging public response based on other products before taking all of that knowledge and refining the hell out of their own product before launching it (2 or 3 years after the first one came out). Then WE, not Apple, create the notion that Apple did something new, different and spectacular. Apple is the only tech company not frothing at the mouth to be the first to a milestone. They have the foresight to know that in 5 -10 years, no one will remember who did it first. They will only remember who did it best. No one will ever say, “Did you see Apple’s new Diamond Rio Mp3 Player? It’s called an iPod.”

There will be whining…

…and highly-placed whining, too! Here’s Steve Sinofsky, former President of the Windows division  and Microsoftie since 1989 on Twitter:

That’s pretty rich coming from a guy whose fortune in the industry comes from helping build the company that popularized the acronym “FUD”, whose internal mantra was “Embrace, extend, and extinguish”, and for whom this editorial cartoon is rather apt: windows 95

Pioneers get the arrows, settlers get the land…

…and if anyone should have internalized that lesson, it’s Microsoft. When IBM was looking for an operating system, Microsoft saw an opportunity, bought and re-jiggered an operating system, and packaged it as theirs. When an opportunity arose to put a Mac-like GUI on commodity computers 20 years ago, they capitalized on it, and pointing and clicking is now an everyday skill. When Microsoft saw the twin threats of Java and Netscape, they took the internet tidal wave head-on, countered with .NET and Internet Explorer, and helped put the latter out of business.

Microsoft may not have been original, but that doesn’t mean they weren’t creative (people often confuse the two), and they could execute.

tablet pc It should be noted that Microsoft was into tablets and wearables long before the iPad and Apple Watch were even announced. Microsoft’s Tablet PC, SPOT watches, and Pocket PC devices were all available in the early aughts, but they failed to define their spaces in the same way that Windows did. Just as Microsoft out-IBM’d and Apple’d IBM and Apple on the desktop, Apple and Google would end up out-Microsofting Microsoft in the online and mobile worlds.

Presentation matters

For the people who invented a piece of software is practically synonymous with the word “presentation”, Microsoft have a lot to learn about giving them. Compare and contrast the original iPad “Stevenote”…

…with the original Surface keynote:

While not as polished as the Apple keynote, it was passable right up to that point where the device locked up during Sinofsky’s demo:

You can almost see the PIP being issued in his eyes.

“That was years ago!” a friend of mine who still works at Microsoft retorted when I recently brought it up, but if the recent Windows 10 keynote at IFA is any indication, they still have to clean up their presentation game. The reception for Windows 10 has been quite good so far, and they had an opportunity to get people even more excited about it. However, they dropped the ball so badly that even Windows super-fan Paul Thurrott was disappointed:

If you have about 45 minutes to spare and nothing — and I mean nothing — better to do, here’s their IFA keynote, where they show a lot of computers to the tech press that they’ve already seen before:

If Microsoft needs a new slogan, they can take the full candor approach and go with “We never miss an opportunity to miss an opportunity”.

It’s a shame: they’ve got a decent device in the Surface Pro, a decent OS in Windows 10, and some decent “develop with our platform, deploy anywhere” potential with their latest development tools; they just need better ways to get their points across.

Categories
Uncategorized

Hey, developers! Want a free Apple TV developer kit?

apple tv

To me, the most interesting product announcement at today’s Apple event was the all-new fourth-generation Apple TV. With support for apps and an all-new controller with touch and motion sensors, along with support for a number of game controllers, it’s the living room opportunity that iOS developers have been waiting for. It’s got the familiar iOS underpinnings, it gets hooked to the biggest screen in the house and is located in the most social room, it gives us a real  shot at programming apps that incorporate Wii-like motions, and it comes with a market of customers reader to buy your wares. All we need is the chance to get our hands on one.

Luckily for us, Apple’s providing that opportunity. If you sign up at the Apple TV Developer Kit registration site before Friday, September 11 at 12:00 p.m. Pacific (3:00 p.m. Eastern /19:00 UTC), you could get sent a free Apple TV Developer Kit that includes the new Apple TVApple TV Remote, Power cord, Lightning to USB Cable, USB-A to USB-C Cable, and documentation.

There’s a limited number of these kits, so they’re giving priority to people who have apps in the store. This program is open to developers who have a valid Apple Developer Program membership as of this morning and who are based in one of the following countries:

  • Australia
  • Austria
  • Belgium
  • Canada
  • Czech Republic
  • Denmark
  • Finland
  • France
  • Germany
  • Hungary
  • Ireland
  • Italy
  • Japan
  • Luxembourg
  • Netherlands
  • New Zealand
  • Poland
  • Portugal
  • Spain
  • Sweden
  • United Kingdom
  • United States

Hey, a free toy to play with! What are you waiting for? Register now!

Categories
Uncategorized

How to catch Apple’s September 2015 “Hey Siri” event, and what they might announce

Stylized Apple logo with the text  "Hey Siri, give us a hint."

It’s September, which means it’s time for Apple to hold a big event. This one, which they’ve named “Hey Siri, give us a hint” in the promotional material, takes place today in San Francisco at 10:00 a.m. Pacific Time (1:00 p.m. Eastern, or 17:00 UTC). In this article, I’ll show you how you can watch it online as it happens if you have an Apple device, how to get live updates if you don’t have an Apple device, and what Apple watchers think will be announced today.

How to watch it online (if you have an Apple device)

Apple CEO Tim Cook delivering a keynote presentation, with the Apple logo projected on the screen behind him

Apple CEO Tim Cook delivering a keynote presentation.

Apple will livestream the event at apple.com/live, but you won’t be able to access it on just any old system that you may have lying around. It may be Apple snobbery, a way to make the Apple faithful feel special, a way to keep the broadband bandwidth and costs for what’s likely to be an insanely popular event down, or some combination of all three, but the most — but not all — of the ways you can watch the livestream involve an Apple device.

In order to watch the livestream, you’ll need one of the following:

  • An iOS device — that is, an iPhone, iPad, or iPod Touch running iOS 7.0 or later. If you’re like most iOS users, you’ve kept your device reasonably up-to-date and should be fine. To double-check which version of iOS you have, go to Settings, then select General (you may have to scroll down), then select About; then look for the Version item.
  • A Mac — Macbook, Mac Mini, iMac, or Mac Pro running:
    • OS X 10.8.5 (OS X 10.8 is also known as “Mountain Lion”) or later. To double-check which version of Mac OS you’re running, click on the Apple menu and select About This Mac. The version number should appear just below the headline for the window that appears.
    • Safari 6.0.5 or later. It has to be Safari: Apple is a jealous and angry god, and they won’t let you view their event on anyone else’s browser.
  • An Apple TV. It’ll need to be a second- or third-generation one running software 6.2 or later. To see which version of software your Apple TV is running, go to Settings, then General, then About.
  • A device running Windows 10 and the Microsoft Edge browser.

How to get live updates

Members of the press liveblogging at an Apple keynote

There are always a number of “liveblogs” of any given Apple announcement.

If you don’t have an Apple device or don’t want the full-on distraction of a live video stream, there are a number of people who’ll be “liveblogging” the event with short, quick, rapid-fire updates of text and photos. Here’s out list of media outlets who’ll be liveblogging today; just click on their link to see their liveblog:

What to expect today — the pundits’ guesses

Tim Cook and a slide showing a pocket watch, Stonehenge, a Casio digital watch, and a turkey leg.

Sometimes Apple surprises us at their keynotes.
Photo by Adam Lisagor. Click to see the source.

Here’s our list of articles that attempt to predict what’ll be announced today. Take them with the appropriately-sized grain of salt:

this article also appears in the GSG blog