Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
ResearchKit activities controller managing a survey.
//
// ActivitiesViewController.swift
// MyStudyApp
//
// Created by Vincent Tourraine on 2/8/16.
// Copyright © 2016 Shazino. All rights reserved.
//
import UIKit
import ResearchKit
class ActivitiesViewController: UIViewController, ORKTaskViewControllerDelegate {
let QuestionStepIdentifier = "yes-no-step"
@IBAction func startSurvey(sender: UIButton) {
let introStep = ORKInstructionStep(identifier: ORKInstruction0StepIdentifier)
introStep.title = NSLocalizedString("Basic Survey", comment: "")
introStep.text = NSLocalizedString("This is a basic survey.", comment: "")
let step = ORKQuestionStep(identifier: QuestionStepIdentifier)
step.title = NSLocalizedString("Do you feel good?", comment: "")
step.answerFormat = ORKBooleanAnswerFormat()
let completionStep = ORKOrderedTask.makeCompletionStep()
let task = ORKOrderedTask(identifier: "yes-no-task", steps:[introStep, step, completionStep])
let viewController = ORKTaskViewController(task: task, taskRunUUID: nil)
viewController.delegate = self
presentViewController(viewController, animated:true, completion:nil)
}
// MARK: Task view controller delegate
func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) {
print("Task run UUID: \(taskViewController.taskRunUUID.UUIDString)")
if reason == .Completed {
if let stepResult = taskViewController.result.stepResultForStepIdentifier(QuestionStepIdentifier),
let stepResults = stepResult.results,
let stepFirstResult = stepResults.first,
let booleanResult = stepFirstResult as? ORKBooleanQuestionResult,
let booleanAnswer = booleanResult.booleanAnswer {
print("Result for question: \(booleanAnswer.boolValue)")
}
}
let durationFormatter = NSNumberFormatter()
durationFormatter.maximumFractionDigits = 2
if let results = taskViewController.result.results {
for result in results {
guard let startDate = result.startDate,
let endDate = result.endDate
else { continue }
let duration = endDate.timeIntervalSinceDate(startDate)
let formattedDuration = durationFormatter.stringFromNumber(duration)
print("Duration for step “\(result.identifier)”: \(formattedDuration!) s")
}
}
dismissViewControllerAnimated(true, completion: nil)
}
}
Owner

vtourraine commented Feb 25, 2016

Output example:

Task run UUID A507EBB0-305C-45C1-AACD-55263C102E64
Result for question: true
Duration for step “instruction”: 1.1 s
Duration for step “yes-no-step”: 1.92 s
Duration for step “conclusion”: 1.08 s

I doesn't work on xcode 8.2.1. Could you gently put an xcode project to test it? Thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment