Handle

20th April, 2015 — Aral Balkan

Ring bell for service
Handle is an easy and expressive means to handle notifications using blocks.
Photo courtesy Martha T.

Notifications made easy

Handling notifications is something you do day in and day out in Cocoa. Handle is a Swift micro-library that gives you an easy and expressive means to handle notifications using blocks.

Code

Grab the code from our Git repository: source.small-tech.org/project/handle

Usage

Safety first: notification enums

To provide compile-time safety and literate code, we use a notification enum idiom to define our notification names:

Swift: // MARK: MyNotification
public enum MyNotification:String
{
  // MARK: .awesomeNotification
  case awesomeNotification = "AwesomeNotification"
    
  public static func named(notification: MyNotification) -> String
  {
    return notification.rawValue
  }
}

This allows us to refer to notifications using the following literate syntax:

Swift: MyNotification.named(.awesomeNotification)

(So much more readable than MyNotification.awesomeNotification.rawValue)

Posting notifications

Posting a notification couldn’t be easier:

Swift: post(MyNotification.named(.awesomeNotification), from: self)

You can, of course, also pass a userInfo dictionary:

Swift: post(MyNotification.named(.awesomeNotification), from: self, with:["someGnarly":"information"])

(For notification handling I’m using my own Handle library).

Handling notifications

The preferred method is to create a notification handler block:

Swift: var notificationHandler:NotificationHandler?

// …

func createNotificationHandlers()
{
  notificationHandler?.remove()
  notificationHandler = handle(MyNotification.named(.awesomeNotification))
  {
    /* as */ notification in  
  
    // Do something awesome.
  }
}

func removeNotificationHandlers()
{
  notificationHandler?.remove()
}

For ViewControllers, the idiom is to call createNotificationHandlers() on viewWillAppear() and removeNotificationHandlers() on viewWillDisappear(). However, since the methods can also be called at other times, we choose to code safety and call remove() on the optional notificationHandler property before actually defining it so as to guarantee that we won’t set up duplicate handlers.

Other forms

The Handle micro-library also includes NSNotificationCenter extensions as well as a selector-based API instead of the block-based one shown here.

For more information on the other APIs, please see the source code.