Anybody familiar with Carekit can walk me through how to display a video on the instructions portion of care card. There is an option to add a photo through imageURL using the OCKCarePlanActivity Class but not video. Thank you!!
-
You'll have to use your own custom detail view controller to display a video. – tktsubota Dec 15 '16 at 03:38
-
Anybody care to elaborate? – Khalid Mohamed Dec 20 '16 at 16:06
1 Answers
The code below shows how an opening (storyboard-created) UIViewController can create a simple activity, add it to the Care Plan Store and show the standard OCKCareCardViewController. (This structure comes largely from "Beginning CareKit Development"). The view controller has only one button that functions to display the standard care card:
The Care Card is perfectly standard, as shown below. However, if you click on the event button it will show a custom view controller.
The custom view controller, shown below, is built in storyboard. The custom intervention is trivial - it just asks the user to click on the tree buttons that make up the scene. (You could have a video player view instead of three buttons).
Almost all of the code is in the OpeningViewController class. This class is shown below.
//
// OpeningViewController.swift
//
/*
Context:
This app demonstrates how to display a custom UIViewController when
the user taps on an event in a CareCard.
This app manages just one, hard-coded intervention activity. When
the user taps on an event-button (usually an open circle) on the
main Care Card then the app displays a custom UIViewController
with three buttons for the user to tap.
Purpose:
This root view controller for the app shows a button that allows
the user to request a standard OCKCareCardViewController.
Additionally:
1. In the init for this view controller an instance of
OCKCarePlanStore is created.
(Note: this is poor design, ordinarily you would probably
have a singleton model for the Care Plan Store. But as long
as you don't re-initialize this view it will serve for demo
purposes).
2. During viewDidLoad a convenience function is called that
will:
A. Check to see if an activity with an identifier of
"TapThreeButtons" exists
B. if not, it builds an activity scheduled to begin three
days ago.
C. The new intervention activity is added to the store.
3. In the ShowCareCard IBAction:
A. an instance of OCKCareCardViewController is built
B. the delegate for the new Care Card is set to self.
C. the new Care Card is presented modally
4. An extension is used to make this ViewController conform
to OCKCareCardViewControllerDelegate.
A. implements the optional method
careCardViewController(VC:
didSelectButtonWithInterventionEvent:)
THIS IS WHERE A CUSTOM DISPLAY CAN BE DISPLAYED TO
RESPOND TO THE TAPPING OF AN EVENT.
B. Returns "false" from
careCardViewController:
shouldHandleEventCompletionForActivity:
This prevents CareKit from automatically processing an
event when an event button is tapped.
*/
import UIKit
import CareKit
struct Global {
static let tapButtonsIdentifier = "TapThreeButtons"
}
class OpeningViewController: UIViewController {
var store: OCKCarePlanStore
required init( coder aDecoder: NSCoder )
{
// 1. get a URL for the Document directory, then a URL for
the CarePlanStore
let fileManager = FileManager.default
guard let documentDirectory
= fileManager.urls( for: .documentDirectory,
in: .userDomainMask ).last
else {
let msg = "*** Error: FileManager is not returning the document directory URL *** "
fatalError( msg )
}
let storeURL =
documentDirectory
.appendingPathComponent("TapInterventionStore")
// 2. create the store directory if it does not already exist
if !fileManager.fileExists( atPath: storeURL.path ) {
try! fileManager.createDirectory(at: storeURL,
withIntermediateDirectories: true,
attributes: nil )
}
// 3. set an instance constant to point to the store
store = OCKCarePlanStore(persistenceDirectoryURL: storeURL )
super.init( coder: aDecoder )!
}
@IBAction func ShowCareCard(_ sender: UIButton) {
let careCardViewController = createCareCardViewController()
careCardViewController.delegate = self
let embeddedCareCard =
UINavigationController(rootViewController:
careCardViewController)
// present the CareCard modally
self.present( embeddedCareCard,
animated: true,
completion: nil )
}
override func viewDidLoad() {
super.viewDidLoad()
// if no "tapThreeTimes" activity exists in CarePlanStore then
// create one
createActivity()
}
// MARK: Convenience Methods
fileprivate func createActivity()
{
// query the store to see if there already exists an activity
// with this identifier
store.activity(forIdentifier: Global.tapButtonsIdentifier )
{
[ unowned self ]
( success, foundActivity, error) in
// check that the query terminated successfully
guard success else {
let msg = "A query of CarePlanStore for the \( Global.tapButtonsIdentifier ) intervention activity produced an error."
fatalError( msg )
}
// check to see if the activity is in CarePlanStore
if foundActivity == nil {
// instatiate a new activity
let newTapButtonsActivity
= self.buildNewTapButtonsActivity()
// 4. save the new Activity instance, using the completion to check that the save worked
self.store.add( newTapButtonsActivity )
{
(success, error) in
guard success else {
let msg = "An error was returned while saving a new \( Global.tapButtonsIdentifier ) intervention activity."
fatalError( msg )
}
} // ends new activity closure
} // ends check that activity might be nil
} // ends closure on query for activity in store
}
fileprivate func buildNewTapButtonsActivity()
-> OCKCarePlanActivity
{
struct Lets {
static let title = "Push Three Buttons"
static let text = "Tap one of the circles below and you'll be asked to tap each of three buttons"
static let instructions = "When you tap on an event (those circles on your Care Card) the system will show you a screen with three buttons. Tap all three. They can be tapped in any sequence but try not to tap the same button twice."
}
// create events by starting three days ago,
// with 2 events per day
let gregorianCalendar = Calendar( identifier: .gregorian )
guard let threeDaysAgo =
gregorianCalendar.date(byAdding: .day,
value: -3,
to: Date() )
else {
let msg = "Could not calculate date for three-days-before-today."
fatalError( msg )
}
let startDate =
gregorianCalendar.dateComponents([.year, .month, .day ],
from: threeDaysAgo )
let thriceADay =
OCKCareSchedule.dailySchedule(withStartDate: startDate,
occurrencesPerDay: 2)
let activity =
OCKCarePlanActivity(
identifier: Global.tapButtonsIdentifier,
groupIdentifier: nil,
type: .intervention,
title: Lets.title,
text: Lets.text,
tintColor: nil,
instructions: Lets.instructions,
imageURL: nil,
schedule: thriceADay,
resultResettable: true,
userInfo: nil )
return activity
}
fileprivate func createCareCardViewController()
-> OCKCareCardViewController
{
let viewController =
OCKCareCardViewController(carePlanStore: self.store )
// Setup the controllers title
viewController.title =
NSLocalizedString("Tap Test App",
comment: "This app shows CareKit users how to add a custom interface to Care Card")
return viewController
}
}
extension OpeningViewController: OCKCareCardViewControllerDelegate {
/**
prevents CareKit from automatically coloring-in an event symbol when tapped
- parameter viewController: the view controller that displays the events
- parameter shouldHandleEventCompletionForActivity: the activity associated with the tapped event
*/
func careCardViewController(
_ viewController: OCKCareCardViewController,
shouldHandleEventCompletionFor interventionActivity:
OCKCarePlanActivity )
-> Bool
{
return false
}
/**
modally presents a custom UIViewController when the user taps an event button on the Care Card
- parameter viewController: the OCKCareCardViewController master/detail that presents the event
- parameter didSelectRowWithInterventionActivity: the user selected OCKCarePlanActivity tapped by the user
- Note in this implementation the new detail view controller will be an instance of ZCCareCardDetailViewController showing the "medication" and an associated medication image
*/
func careCardViewController( _ viewController: OCKCareCardViewController,
didSelectButtonWithInterventionEvent interventionEvent: OCKCarePlanEvent )
{
// In this simplistic app, assume that a user-tap on an already completed event always
// means that the user just wants to "clear" the event
if interventionEvent.state == .completed {
store.update( interventionEvent,
with: interventionEvent.result,
state: .notCompleted )
{
( success, event, error ) in
if success {
print( "toggled the event's state")
} else {
print( "failed to toggle event's state")
}
}
} else {
// 1. Create the custom detail view controller
let storyBoard = UIStoryboard( name: "Main", bundle: nil )
let tapThreeButtonsViewController =
storyBoard.instantiateViewController(
withIdentifier: Global.tapButtonsIdentifier ) as!
TapThreeButtonsViewController
// 2 set up the data model for the ViewController
tapThreeButtonsViewController.carePlanEvent
= interventionEvent
tapThreeButtonsViewController.store = store
// 3. Embed in a UINavigationController
let embeddedViewController =
UINavigationController(
rootViewController: tapThreeButtonsViewController )
// 4. modally present the custom detail view controller
viewController.present(embeddedViewController,
animated: true,
completion: nil )
}
}
}
The code for the custom view controller isn't particularly interesting (or, for that matter, very much debugged)! I'll show it anyway since I think this is how you retain detail data arising from a custom intervention.
//
// TapThreeButtonsViewController.swift
// CustomCareCard
//
/*
Context:
This app is meant to show how a custom view controller can be
displayed in the middle of a CareKit app.
Purpose:
This class defines the custom view controller built in the
storyboard. It has these elements:
1. A Done navigation button to indicate that the intervention
activity has been completed.
2. A Cancel navigation button to indicate that the user is not
interested in completing the activity.
3. A label giving the user instructions to tap on three
buttons (kind of silly, really, but the point here is to
show how to display a custom interface not to solve a real
medical problem).
4. Three buttons labeled "Button One", "Button Two",
"Button Three" for the user to tap.
The only significant content in this view controller comes in the
"doneButton" action. The code there shows you how to save a basic "value"
to record the user's actions. Here the "value" is equal to the total number
of times the threee buttons were tapped. Additionally, the code will save
the number of times each individual button was tapped, using the "userInfo"
property of the OCKCarePlanEventResult object. Detail data of this sort
could be useful for formulating OCKInsightViewController reports.
*/
import UIKit
import CareKit
class TapThreeButtonsViewController: UIViewController {
// MARK: data model
public var carePlanEvent: OCKCarePlanEvent!
public var store: OCKCarePlanStore!
fileprivate var tapCount = [ "Button One": 0,
"Button Two": 0,
"Button Three": 0
]
// MARK: actions
/**
when the user taps any of the three main buttons this logic adds to the count of that button
- parameter sender: the UIButton that was tapped (Button One, Button Two or Button Three)
*/
@IBAction func tapButton(_ sender: UIButton) {
let buttonName = sender.currentTitle!
tapCount[ buttonName ]! += 1
}
/**
saves the total number of button taps as the event "value", but also saves the counts-for-each-button in "userInfo"
- parameter sender: the UIButtonItem that initiated the action
*/
@IBAction func doneButton(_ sender: UIBarButtonItem!) {
var totalTaps = 0
var codableTapCount: Dictionary< String, NSNumber > = [ : ]
// CAREKIT reminder: "values" are stored as strings. The
// userInfo dictionary requires that the
// the "value" follow NSCoder requirements.
for (button, taps ) in tapCount {
totalTaps += taps
codableTapCount[ button ] = NSNumber( value: taps )
}
let results =
OCKCarePlanEventResult(
valueString: totalTaps.description,
unitString: "taps",
userInfo: codableTapCount )
store.update( carePlanEvent,
with: results,
state: .completed ) {
// use completion event simply to check that the Care
// Plan Store updated successfully
( success, event, error ) in
if !success {
fatalError("The Care Plan Store was not updated with the most-recent results from the Tap Buttons test.")
}
}
self.dismiss(animated: true)
}
/**
Dismisses the custom view controller without making changes to the Care Plan Store
*/
@IBAction func cancelButton(_ sender: AnyObject) {
self.dismiss(animated: true)
}
}

- 774
- 7
- 15