Observer Pattern & NSNotificationCenter in Swift 2.2

Recently while learning Swift, I ran into a scenario where a lot of functionality relies on my app knowing an OAuth2 access token, this means until the app acquires the access token, I don’t want to make any other network requests.
One solution to this problem is to use the Observer pattern. In a nutshell, you add observers which will only come into action when they receive a particular notification. To do this, we use NSNotificationCenter.
Observers are registered using the following:
The Selector is the name of the function you wish to call. Name is the name of the notification. It helps to declare the notification’s name as a constant, as it cuts down on lines of code and reduces the risk of mistyping the notification’s name elsewhere. The Object is used to filter notifications, in this instance, I don’t care what sends the notification, so we pass nil.
In my example I add the observer to ViewController’s viewDidLoad() function which sets the selector as another function within the same controller:
In my OAuthClient class, I declare the constant to use as the name in the observers and for posting the notification:
I then create a function to post the notification:

Once I set the access token, I call the OAuthClient.accessTokenSetNotification to notify the observer I added earlier. Once notified, the actOnAccessToken function is called.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s