Show Menu

Looking to hire an app developer?

Submit your 30 day Job Listing for FREE

swift tutorial today extension

In this Advanced Swift 2 Tutorial I am going to show you how to utilize some of the features that were added in iOS 8. This tutorial will cover how to create a Today Extension or Widget in Swift. I will show you how to create a ‘boilerplate’ application, how to add the Today Extension and how to obtain and display data.

Throughout this tutorial it is assumed that you have a basic understanding of the Swift Programming language and that you are familiar with Xcode and creating a New Single View Application.

The Today Widget

This tutorial is going to show you how to create a Today Extension that will display a random quote to the user. Everybody loves empowering quotes so we will display a random quote per day.

What is the Today Extension?

The Today Extension is like a mini application that is added to your Today Screen on the iOS Device and displays information. They are distributed as part of an iOS Application and are not their own separate application.

If you want some more information on the Today Extensions check out the Apple documentation Today Widget

Ok, so lets start making magic…

Create Today Extension

Create a new Single View Application. You can call it anything you want, I have called mine quoteWidget. Now lets add the application Extension. Go to File -> New -> Target. This will open a dialogue window titled: Chose a template for your new target. On the left hand side under the heading iOS, Select Application Extension, and then select Today Extension

today extension tutorial new

Click Next. It will ask you to give your extension a name. I called mine: randomQuote. Xcode will then ask you if you would like to Activate randomQuote Scheme. Click Activate.

Now, Go to your storyboard and create a UILabeloutlet, link it up which ever way you want and call it: quoteText.

Next, in the Project Navigation Pane select TodayViewController.Swift you should see your IBOutlet. Change the code so that it now reads:


@IBOutlet weak var quoteText: UILabel!
 override func viewDidLoad() {
 super.viewDidLoad()
 var service = QuoteService()
 quoteText.text = service.randomQuote()
 }

What we have just done there is created a new instance variable called service that will access/reference a class we will create later: var service = QuoteService(). Then we access a function inside that called randomQuote() that will output the quote and we will assign that output to the UILabel we just created. Changing the text to whatever the quote is: quoteText.text = service.randomQuote().

Now, we need to create a new swift file and call it: QuoteService.Swift. Inside that new file we need to create our class as mentioned earlier:


class QuoteService {
    // ...
}

Great. Now the variable we defined earlier: var service = QuoteService() has something to link up to. Next we are going to make the quotes array. After all we do want something to display. Inside the class you just created, create an array of quotes:



var quotes = [
   "Chin up chap!",
   "God is Good",
   "Don't fight evil, Deny it battle.",
   "A smile a day..."
]

Now that is all well and good, but how do we get these form the class? This is where quoteText.text = service.randomQuote() comes in. This is saying get the function randomQuote() from service – which we defined as our class on the line above and add that to the UILabel.text. So lets create the randomQuote() function. Under the array we just created and still inside the class, write:


func randomQuote() -> String {
 return quotes[ Int(arc4random_uniform(UInt32(quotes.count))) ]
}

This will return is String to use. and we have used arc4random_uniform to get a random one to display.

Now, we need to add the extension.

Add Extension to Today View

Click Run. The iOS Simulator will appear with the Today View. Click the Edit button:

today view ios simulator

You will then see the widget ready to add. Click the Green + button.

tutorial add widget today extension

Voila! There you have your up and running Today Extension created with Swift. When you view your widget, you might notice that the outputted text is slightly pushed to the right? That is because all widgets have a standard margin to the left. We can fix this by using a protocol method: NCWidgetProvidingProtocol. Go to your TodayViewController.Swift file, at the very bottom but still inside the class write:


func widgetMarginInsetsForProposedMarginInsets
 (defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) {
 return UIEdgeInsetsZero
}

Here is the complete file:

TodayViewController.Swift


import UIKit
import NotificationCenter
class TodayViewController: UIViewController, NCWidgetProviding {

@IBOutlet weak var quoteText: UILabel!
 override func viewDidLoad() {
 super.viewDidLoad()
 var service = QuoteService()
 quoteText.text = service.randomQuote()
 }
 
282 CHAPTER 11: Advanced iOS 8 Features
 override func didReceiveMemoryWarning() {
 super.didReceiveMemoryWarning()
 // Dispose of any resources that can be recreated.
 }

 func widgetPerformUpdateWithCompletionHandler(completionHandler: ((NCUpdateResult) ->
Void)!) {
 // Perform any setup necessary in order to update the view.
 // If an error is encountered, use NCUpdateResult.Failed
 // If there's no update required, use NCUpdateResult.NoData
 // If there's an update, use NCUpdateResult.NewData
 completionHandler(NCUpdateResult.NewData)
 }

 func widgetMarginInsetsForProposedMarginInsets
 (defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) {
 return UIEdgeInsetsZero
 }
}

Summary

In this Swift Create a Today Extension tutorial I have shown you how to create an Application Extension. You should now also understand how to add the extension to your Today View on the iOS Device. From the example application we created you have seen how we can create a class (class QuoteService {}) and to use a function to get information from that class. To alter the margins of the Today Widget you also used a protocol method NCWidgetProvidingProtocol.

I really hope you liked this tutorial. Sign up to the mailing list for future tutorials. I have a lot planned.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


iOS-Blog Admin Team

Written by:

We're here to help.

Comments

comments