NSNotificationCenter in Swift 4: Intra-app communication, sending, receiving, listening, stop listening for messages

[Download Xcode 9 project with full Swift 4 source from GitHub.]

The topic today is how to communicate between objects within an app, specifically using iOS’s NSNotificationCenter. In the last post, “Tutorial: delegates and delegation in Swift 4,” I used delegation to communicate between two objects. In the code I wrote for the last article, the app’s main (and only) view controller waited to display an image. The image was not included in the app bundle, rather downloaded from a NASA website. I created a class that downloaded the image file. The view controller was informed that the image was finished downloading and ready to display using a technique called “delegation.” Here, we’ll modify the delegation tutorial code to work with NSNotificationCenter instead. The image downloading class will notify the view controller that the image has finished downloading by sending a notification (message).

I will show you: 1) a one-post-to-one-observer notification; and, 2) a broadcast, where one post is received by many observers. Download the project and follow along in Xcode. Here’s the app we’ll build:

Continue reading “NSNotificationCenter in Swift 4: Intra-app communication, sending, receiving, listening, stop listening for messages”

Swift 3 segues, unwind segues, storyboards, and view/navigation controllers

[Download Xcode 8.2.1 project with full Swift 3 source from GitHub.]

Today’s tutorial covers transitions — segues — from one source storyboard scene to another destination scene, and unwind segues leading back from destination to source… I created a project to help you follow along with this tutorial, written in Swift 3, against the iOS 10 SDK, and using the Xcode 8.2.1 IDE. Please download the project. The app produced by the project is shown in action in the following video. Please watch before continuing on:

Segues don’t exist in a vacuum. I’ve introduced a UINavigationController into the mix. Of course, you’ll see a few UIViewControllers. I’ve also used a UITableView and managed its complexity by breaking it into logical pieces by using Swift “extensions.” As you proceed, you’ll have to grasp concepts like Auto Layout and managing a table view’s data source.

Continue reading “Swift 3 segues, unwind segues, storyboards, and view/navigation controllers”