Tuesday, March 1, 2016

RK03 - ResearchKit "Hello World" with Instruction Step

"Hello World" with Instruction Step


No software can go forward without a simple "Hello World" application.
If we break this rule, the Gods of "Programming for Dummies" will crush us !
So without any further due lets do some coding !!!

https://gist.github.com/bishalg/c5268460b81344451e44


// 1
   @IBOutlet weak var gettingStartedButton: UIButton!   
// 2
    @IBAction func gettingStartedAction(sender: UIButton) {        self.sayHellowToTheWorld()    }        func sayHellowToTheWorld() {        // Make Steps         let step1 = ORKInstructionStep(identifier: "step1")        step1.title = "Hello World!"                let step2 = ORKInstructionStep(identifier: "step2")        step2.title = "That is it ! :] Thanks"        
                 // Make a Ordered Task of steps
        let task = ORKOrderedTask(identifier: "ourFirstTask", steps: [step1, step2])
                  // Present the ViewController of hence made Task !
        let taskVC = ORKTaskViewController(task: task, taskRunUUID: nil)        taskVC.delegate = self        presentViewController(taskVC, animated: true, completion: nil)    }
// 3
extension HomeVC: ORKTaskViewControllerDelegate {

   func taskViewController(taskViewController: ORKTaskViewController, didFinishWithReason reason: ORKTaskViewControllerFinishReason, error: NSError?) {        self.dismissViewControllerAnimated(true, completion: nil)        let buttonTitle: String?        switch reason {        case .Completed:            buttonTitle = "Completed"        case .Discarded:            buttonTitle = "Discarded"        case .Failed:            buttonTitle = "Failed"        case .Saved:            buttonTitle = "Saved"        }
        gettingStartedButton.setTitle(buttonTitle, forState: .Normal)    }

// 1 - Getting Started -
In our VC we have a button which will start a ResearchKit survey and will change based on our action

// 2 - Action on button will start the survey

If we do "Next" and "Done" after  we started from "Getting Started" button it would present us a Task-ViewController which will make a delegate at the end of it step.

// 3
// Extend out View Controller so that it handles the Delegate of TaskVC
// Once the task is completed we will update our button to reflect the result !
// And finally its our responsibility to dismiss the VC we presented.

Here is one of the expected flow -

1. Home Screen


2. Research Kit - TaskVC presented with "Hello World" Instruction Step ( ORKInstructionStep )



3. Second Instruction Step with "DONE" button - 2/ 2



Finally if we will get any one of the following result ( ORKTaskViewControllerFinishReason ) -
In this case we will have either Completed or Discarded result.