---
title: Creating and Displaying Tasks for a Patient
framework: CareKit
role: article
role_heading: Article
path: carekit/creating-and-displaying-tasks-for-a-patient
---

# Creating and Displaying Tasks for a Patient

Create tasks and schedules for patients and display them using a synchronized view controller.

## Overview

Overview When creating an app using CareKit, you can create tasks, such as taking medication or performing an exercise, for the user to complete. To create tasks for users, first create a store, so your task data has a place to be persisted. You can then create both simple and complex task schedules, so your users know when to perform their tasks. You can then present the scheduled tasks to the user. Create a Store Your first step is to create a store for your data. You instantiate your store with a name. There’s no specific validation of this name, but it’s good practice to make it distinctive. Use the reverse-url format bundle identifier of your app with a unique name appended: import CareKit

let storeName = "com.mycompany.myapp.nausea" let store = OCKStore(name: storeName)  If you try to create a store with a name of an already-existing store, the OCKStore initializer returns the existing store. Create a Schedule When you create a task, you have to provide a schedule so users know when they need to complete the task. For a task like taking a medication, the schedule specifies when the user should take that medication, for example at 11:00 am or after dinner. You build schedules by defining times, offsets from known times, and ranges across times and dates that consists of at least one schedule element. A schedule element represents a defined moment or range of moments. note: Calendar calculations are complex and depend on the user’s device settings for time zone and calendar. Use the provided Calendar API for the Date and DateComponents to simplify this. You can build a schedule in a few simple steps. For example, the code below shows how to create a schedule that occurs every day at 8:00 am, starting today. In the first line, Calendar returns the first moment of today’s date based on the user’s calendar. In the second line, you add 8 hours to it to create a date object at 8:00 am. Next, you create a schedule element, using today’s date at 8:00 am, and set it to occur daily. In the last line, you create a schedule using the schedule element you created in the line before. let startOfDay = Calendar.current.startOfDay(for: Date()) let atBreakfast = Calendar.current.date(byAdding: .hour, value: 8, to: startOfDay)!

let dailyAtBreakfast = OCKScheduleElement(start: atBreakfast, end: nil, interval: DateComponents(day: 1))

var schedule = OCKSchedule(composing: [dailyAtBreakfast]) It’s best practice to create your schedule using date objects initialized with the user’s calendar preference. There are a variety of calendars your user could be using, each with different properties and nuances. Creating dates with the user’s calendar preference ensures date calculations are made correctly. Schedule Multiple Elements If you need a schedule that’s more complex than listing once-a-day events, you can build it by working with multiple schedule elements. The code below expands on the previous code example by creating an additional schedule element, that occurs every other day at 12:00 pm. Finally, you create a schedule with the two schedule elements. let startOfDay = Calendar.current.startOfDay(for: Date()) let atBreakfast = Calendar.current.date(byAdding: .hour, value: 8, to: startOfDay)!

let dailyAtBreakfast = OCKScheduleElement(start: atBreakfast, end: nil, interval: DateComponents(day: 1))

let atLunch = Calendar.current.date(byAdding: .hour, value: 12, to: startOfDay)!

let everyTwoDaysAtLunch = OCKScheduleElement(start: atLunch, end: nil,                                interval: DateComponents(day: 2))

var schedule = OCKSchedule(composing: [dailyAtBreakfast, everyTwoDaysAtLunch]) Create and Save Tasks to the Store Once you’ve defined a schedule, use it to create a task. You create a task with an identifier, title, care plan, and schedule. You can also provide instructions for the task as shown in the second line: var task = OCKTask(identifier: "doxylamine", title: "Take Doxylamine", carePlanID: nil, schedule: schedule)

task.instructions = "Take 25mg of doxylamine when you experience nausea." Now, you can save your task to the store. You can also specify a function to handle the completion of the operation. The code below shows you how to save your task and the format of the parameters passed into the completion handler. store.addTasks([task],    queue: DispatchQueue.main,                completion: { (result: (Result<[OCKTask], OCKStoreError>)) in                         switch result {                         case .failure(let error) :                             print(error.localizedDescription)                         case .success( _) :                             print("Success!")                         }         })

The completion handler is an instance of type OCKResultClosure, which passes as a parameter a result enum. The enum contains a different value based on whether the enum is set to .success or .failure. When the enum is set to .success, it contains the objects sent to the store, and when it’s set to .failure, it contains an OCKStoreError. Handle Errors If interacting with the store returns an error, you can inspect the error to help troubleshoot the problem and decide how to handle it. The returned error is an instance of OCKStoreError, an enum that contains a value and a localized description. The enum value will be one of the following: Use this value to determine whether to retry the operation, inform the user, or handle the error some other way. To provide feedback to the user, you can present the localized description to the user. For example, if you attempt to add an entity to the store that’s missing required information, your app will return an error enum with the value of OCKStoreError.invalidValue(reason:), and the localized description of “OCKCDScheduleElement must have at least 1 non-zero interval”. Display Scheduled Tasks Once you have a store populated with tasks, you can display those tasks to the user. CareKit provides pre-built view controllers and a range of controls and views to build your own UI layouts. The simplest way to present data to the user is to use the pre-built view controllers.The code below builds on previous code listings, and shows how to present task data to the user using an OCKDailyTasksPageViewController. let manager = OCKSynchronizedStoreManager(wrapping: store) let careViewController = OCKDailyTasksPageViewController(storeManager: manager) self.present(careViewController, animated: true, completion: nil) The OCKDailyTasksPageViewController utilizes Combine to synchronize events between the store and the UI. First, you create an OCKSynchronizedStoreManager, which creates a wrapper around your store that listens for all activity in the store. In the second line, you create an OCKDailyTasksPageViewController using the synchronized store manager. The synchronized store manager notifies the view controllers views of changes to the store, and the UI updates automatically. In the last line, you present the view controller. The OCKDailyTasksPageViewController displays a header, that contains a weekly calendar, and a body, that includes a list of tasks scheduled for the currently selected date. When a user selects a date in the calendar, the calendar shows all tasks scheduled for that date. Since CareKit uses Combine, the synchronized store manager used to initialize the view controller acts as a publisher. When the user taps to complete a task, the outcome is saved in the store, and the store publishes this change to all subscribers. Any objects that are subscribers, for example the completion ring for that date, update their state automatically. You can use the many view controllers and views available in CareKit to customize the UI appearance, or use your own.

## See Also

### Tasks and Outcomes

- [Creating Schedules for Tasks](carekit/creating-schedules-for-tasks.md)
- [OCKTask](carekitstore/ocktask.md)
- [OCKSchedule](carekitstore/ockschedule.md)
- [OCKScheduleElement](carekitstore/ockscheduleelement.md)
- [OCKScheduleEvent](carekitstore/ockscheduleevent.md)
- [OCKEvent](carekitstore/ockevent.md)
- [OCKOutcome](carekitstore/ockoutcome.md)
- [OCKOutcomeValue](carekitstore/ockoutcomevalue.md)
