chapter 1 · web viewapple watch serve the mobile health application with it’s built in...
TRANSCRIPT
![Page 1: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/1.jpg)
The Design and Implementation of a
Mobile Healthcare System with AppleWatch For Seniors
(MyHealth)
By
Arij Atallh Alfaidi
B.A King Saud University 2010
A thesis submitted to the graduate faculty of the
University of Colorado at Colorado Spring
In partial fulfillment of the
Requirement for the degree of
Master of Science in Computer Science
Department of Computer Science
Spring 2016
![Page 2: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/2.jpg)
Sample copyright page
© Copyright by Arij Alfaidi 2016
All Rights Reserved
ii
![Page 3: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/3.jpg)
This thesis for Master degree by
Arij Alfaidi
Has been approved for
Department of Computer Science
By
__________________________________Advisor: Dr. Edward Chow
__________________________________Committee member: Dr. Rory Lewis
__________________________________Committee member: Dr. Jonathon Ventura
_______________________
Date
iii
![Page 4: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/4.jpg)
Abstract
In this thesis, we develop and implement mobile Healthcare system on the iPhone and Apple
watch to help seniors to manage their health life. MyHealth which is the application name will
remind the user to take their medicine and record the dosage they took. The Application will
measure the heart rate and when the heart rate became above or under a certain level it will
notify the user’s emergency contact. The notification will be a call, SMS and email, the user will
choose the contact when he using the App. Also, it will remind the user to move and exercise
and it will track the user movement. MyHealth will record the data that collected from the heart
rate measurement and send these data to the user physician weekly to monitor their health while
they are away from hospital.
iv
![Page 5: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/5.jpg)
Acknowledgements I would like to take the opportunity to thank My Family for their prayers and support, My
Husband Saud for his support and my daughter Laura for inspiring me by giving me a smile
each time I feel I couldn’t do it anymore. Her smile was the reason that gave me the power and
energy everyday.
I would like to thank Dr. Edward Chow for his supervision and help the whole time. His
encouragement, his ideas was a much of a help.
Also, I would like to Thank Dr. Rory Lewis and Dr. Jonathon Ventura for being interesting in
my thesis idea.
v
![Page 6: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/6.jpg)
Table Of Contents
Table of ContentsChapter 1 Introduction..........................................................................................................1
1.1 Aim............................................................................................................................................2
Chapter 2 Background...........................................................................................................42.1 The Apple watch.......................................................................................................................42.2 History......................................................................................................................................6
Chapter 3 Design....................................................................................................................9
3.1 System Architecture:......................................................................................................10
3.2 iOS Development:...........................................................................................................10
3.3 Swift 2.0:.........................................................................................................................10
3.4 AppGroup:.....................................................................................................................11
3.5 Healthkit:........................................................................................................................11
3.6 MyHealth........................................................................................................................12
3.7 MyHealth Design............................................................................................................15
Chapter 4 Implementation...................................................................................................18
Chapter 5 Lesson Learned and Challenges..........................................................................49
Chapter 6 Future Direction..................................................................................................51
Chapter 7 Conclusion...........................................................................................................53
Chapter 8 References:..........................................................................................................55
Chapter 9 Appendix.............................................................................................................57
9.1 Installation and Demo Steps...........................................................................................57
9.2 Performance:..................................................................................................................63
vi
![Page 7: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/7.jpg)
Chapter 1 Introduction
In the contemporary world, a lot of technological inventions are being developed at fast rate. In
this regard, many businesses are using the technological development to improve their functions
and operations for achieving the required levels of output. Many people can afford to manage
their social and private lives using different technologies like personal digital assistants among
others [Diva2013]. Technology has improved the manner in which information is developed and
shared [ONei2013]. The development of the Smartphone seems to have had a big impact in the
social and economic dimensions of life. With these smart devices, people can manage their
emails and social networking from their convenience. Developers have focused on creating many
essential functions that people often seek. Developers have not stopped at that, thousands of
mobile applications are being to influence business practices, governance, and investment. It is
important to point out that the beneficiaries of these technological have not been businesses
alone, the healthcare industry is also benefiting heavily from technology.
The healthcare is an urgent society problem. With the increase of elderly population, the
demand on senior healthcare has been increased. The GreatCall Health agency reported a
statistic shows that the mobile healthcare industry will be projected a 26-billion-dollar industry
by 2017. There are a lot of health and Fitness applications that have been downloaded daily by
users all over the world. To be able to manage your health from your phone is a promising idea.
Especially we would like to remind senior people their medication and to assist them to contact
their health providers easily.
1
![Page 8: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/8.jpg)
When people become old, the level of activity tends to reduce considerably and need
more support from other people. Additionally, [Yoo2013] explains that many elderly people tend
to have health issues that need constant attention from medical practitioners. When these elderly
people visit hospitals and are given medicines, they often forget taking them as required. This
observation is common among many elderly people, who in most instances, prefer to rest for
long hours with little physical activities. When these people do not have someone to monitor
their progress, they can succumb to the old-age health complications. Perhaps this may explain
why many people prefer having their elderly family members taken to nursing homes where they
can be taken care of by people specially trained for that.
According to [ONei2013], taking the elderly to nursing homes is not always a better
option, because most seniors like to be taken care of by their own relatives. In this regard, taking
them to the nursing homes makes them feel lonely and stressed up, something that can aggravate
their health conditions. This understanding has sparked the need of having special ways in
which, these elderly people can be monitored by doctors from the comfort of their homes without
necessarily having aides. Many developers have been active in the research and development of
various applications that can be used to achieve this important goal [Ozda2012].
1.1 Aim
My aim is to implement and evaluate Mobile application that could help seniors to manage their
health life while they are away from hospital. By remind them to take their medicine, measuring
their heart rate and remind them to move and track their movement. Also, to help the physician
to track the health data of their patient while they are away by sending the heart rate data to them
weekly. Also, the physician will know if their patients are taking their medicine as they describe
2
![Page 9: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/9.jpg)
or not. These data will help in many ways, to improve the patient health issue. Also it can be
used in research area if they took the approval from the patient to use their data.
My proposal question was: Can I design an accurate and effective application using the
HealthKit with the Apple Watch?
Since the correctness and timely of health information report by the mobile device is critical to
the user’s health. It is critical that the design of mobile healthcare app with Apple Watch be
conducted with extra care, more rigorous process, and thorough experiments. The difficulties are
further complicated by the fact that there are few resources for the watch. The challenge here is
to use the Apple Watch sensors in my health application and to send these data back to the
iPhone. Also, notifying the emergency contact based on the measured health information in real
time is still a new idea. Related questions include who to notify and in what order, and what are
the information to reveal. In this document I will discuss in details my work to achieve this aim.
3
![Page 10: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/10.jpg)
Chapter 2 Background
Currently, hundreds of applications have been developed with the aim of managing some
important tasks and resources like time and information, access and maintenance of health
records, consulting and communications, training, education and decision-making among many
others. However those are not the focus of the proposed research.
Different companies are currently researching on how they can tap into the business
opportunity that exists in the healthcare industry. Healthcare practitioners acknowledge the fact
that the use of mobile devices has been instrumental in improving the health of patients. The
mobile apps also help doctors in their clinical decision-making.
Apple has in the recent past made huge strides in this sector. The development of the
Apple watch has been regarded as one of the best innovation in healthcare [Guar2015].
2.1 The Apple watch
The Apple Watch has been described as the big thing in health care [Guar2015], having
features that bring the doctor virtually at the patient’s home, especially for the seniors in the
society. The Apple Watch comes with an accelerator and heart rate monitor, which are beneficial
in calculating the level of general fitness for the patient or person wearing it. The device has the
ability to augment the particular information by linking with the iPhone. Using Wi-Fi networks
and GPS satellites, the device can also gather information that is used in determining its specific
location at any point and any place.
The data from the Apple watch are provided by the two built-in sensors, accelerators and
infra ray sensor. One reports the movement of the body. The other reports the expansion or
4
![Page 11: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/11.jpg)
shrinkage of blood vessel. The data collected by the accelerator sensor will then used by the
apps to derive one’s workout and activities. The data collected by the infra ray sensor will be
used by the app to decide the heart rate. This device enables the user of the watch to track the
intensity of jogging and gym activities as well as walking and other exercises being done in the
neighborhood. On the other hand, the sensor devices are quite passive. It tracks light exercise
session like movements that the user makes during the day. These exercises may have been done
within a minute or 12 hours. The activity and workout apps work alongside the Healthkit
framework and health app, which have been announced by the company as having been
incorporated in its iOS 8 [Guar2015].
Apple develops the HealthKit to enable sharing data between the new health app and
between the apps that provide health and fitness. Also, by using the HealthKit any app that
provides health and fitness services can share date among each other. Managing the data from
different sources and merging the data from all sources based on the user choice is the HealthKit
design functionality. Apps who are using the HealthKit are able to access the data from any
source and do their own changes or merging’s on them. The user of the main health app can
choose which data to share because he is sure that his health information is safe and secure in the
Apple health database. The HealthKit also provides storage service that synchronizes the local
health data on apple watch with those in iPhone and iCloud. [Appledeveloper].
Another important feature of the Apple Watch is that it can easily monitor sleep patterns
and heart rates in the most convenient way [Kise2011]. Other essential tests that can be done
5
![Page 12: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/12.jpg)
including blood and urine where data can be entered by the user and can be managed through the
kits and the resulting information linked to the iPhone. The phone can perform an analysis of the
data and store it for future use, or the data can be sent to the doctor for further treatment.
The owner of the iPhone can have a highly comprehensive profile relating to their health.
In this regard, he can determine his lifestyle patters and activities that affect his life on daily
basis. This understanding is important in making decisions that can be used to improve the health
in different ways [Appledeveloper].. By developing mobile apps with Apple Watch, we hope to
contribute to the developer community and enable others to develop app in this area. The current
idea is to use the HealthKit to measure and record the heart rate and notify the elderly emergency
contact in case of emergency.
2.2 History
Using mobile technology in the health area is not a new idea. The need for using mobile
application has been increased with the increase of the cost of health insurance and staying in
hospitals and nursery. A lot of studies focused on using mobile health application un
different health situation. For monitoring patient health life, diagnose health issues and for
research and study areas. Some of these studies has a good results and some of them did not
achieve what they looking for. The cost of time and the critical of health experiments extent
of the result of using health application. In my search I tried to focus on some of these
experiments that made a print in mobile Healthcare area. The first study was called "The use
of personal digital assistants in clinical decision making by health care professionals: a
systematic review." Health informatics journal. In this study they made an exterminate in the
emergency room at hospital they gave the patient a smart phone with an application to page
his doctor in case of pain. They wanted to record how fast the doctor response and Did the
6
![Page 13: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/13.jpg)
patient use the application or not. Over all result was some time the patient does not have the
time or energy to use the application in case of pain so I thought how can we do that
automatically. in case of emergency we should let the application sense and call for help.
The second paper that I get used of it is called “Apple Watch has designs on health industry –
but is it good for doctors? “this paper discusses in detail how Apple watch sensors designed
and how the watch is related to Health application. The conclusion of the paper was
promising that the Apple watch future will make a difference in mobile healthcare industry.
That’s why I choose my application to use the Apple watch even though it’s a new feature
and it’s hard to fine resources to implement but maybe this thesis will be the base for future
studies that may make a difference in the mobile health area.
“25 ways to use your smartphone. Physicians share their favorite uses and apps.” This paper
shows how smartphone application helped to improve health in the society. They made the
users more aware of the disease and their effects on the patents. They gave the patient the
knowledge about the medicine that they use and what their side effect. The mobile health
application gave the user the aware of infection disease that are spread on a specific time and
how can they avoid it. It helped the physician to keep track of their patient health history. It
also discussed how the application used on the computers on clinics made it easier to know
what the patient history but this area is not my thesis interest. So, as a result of this paper the
mobile healthcare application can make a difference we can get a useful result and this is my
attention from my application.
In this paper “Applying surgical apps: Smartphone and tablet apps prove useful in clinical
practice”. They made a study on senior people in a nursery they train them to use some
application and they record the result of using these application. They said that these
7
![Page 14: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/14.jpg)
application make the patient more aware of their health issues and they became more careful
with their health. Also, they discuss the use of Artificial intelligent inventions on Operation
room and this is will be the future if the developers invest on it.
While I am reading in mobile health industry area I found this research paper that called
“"The smartphone in medicine: a review of current and potential use among physicians and
students." In this paper they made 60 study on the impact of using smartphones on health
area. How can we used of the phone feature such as Wi-Fi, GPS to make application that can
help users to improve their health life away from hospital.
“ The meaning of information technology (IT) mobile devices to me, the infectious disease
physician." Infection & chemotherapy” in this paper they studied why we should focus on
seniors because they have more health issues and the population of elderly people in increase
yearly. So, to produce application that can help them improving their health life is sparkle idea.
That’s why I wanted to make seniors my target of my MyHealth application.
8
![Page 15: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/15.jpg)
Chapter 3 Design
The basic functions of MyHealth Application are:
1. The user should Add their medicine by: name, start Date, End Date.
2. The application will notify the user when the time is due.
3. The Watch will read the heart rate of the user each 10 minutes.
4. If the heart rate above or below the normal level it will notify his emergency contacts.
5. The Application will remind the user to move and do some activity and track his
movement.
6. The application will collect the heart rate data and send it to the user physician weekly.
figure1.1: System overview Diagram.
9
![Page 16: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/16.jpg)
3.1 System Architecture:
To implement MyHealth application we need:
Mac Operating system with Xcode installed on it in my application I used xcode 7.3
Swift 2.0 is the program language that I used to implement my application
We need to use AppGroup in the xcode file
HealthKit is the major component of MyHealth xcode project.
3.2 iOS Development:
In the mobile platform, a large market share is held by the iPhone; this being
the reason behind interest in learning about iPhone development. The
process of development entails an outline of how to establish the hardware
for the applications. Setting of the software requirements and the final
system requirements is also part of the process. Apple Inc. has made it
easier for people who want to become developers with them. All a person
needs are an account charged $99 annually, a mac computer, Xcode
platform and a coding experience, such as the Swift and Objective-C coding
languages.
3.3 Swift 2.0:
The apple Inc. created a modern programming language called swift. It is
specifically developed to be more precise and flexible than the Objective-
C. Swift has LLVM (Low Level Virtual Machine) compiler framework that
utilizes the objective-C runtime allowing C, C++, Swift code and
Objective-C to run in a single program. The flexibility of Swift is attributed
10
![Page 17: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/17.jpg)
to its capacity to support widespread late binding, dynamic dispatch and
extensible programming. It is also considered safe and can effectively
manage the common programming errors, for example, the syntactic and
the null pointers to prevent occurrence of unwanted results.
Swift 2.0 is an open source programming language with a lot of better
performance than the old versions on error handling API, support
availability checking and it’s feel more natural with enhancement to the
Apple SDK.
3.4 AppGroup:
3.4 AppGroup used to share data between different application or in
different interface at the same application. To use AppGroup you
have to turn on the Appgroup in your application and on the
extension that you want to share data among them. [Tom2014]
11
![Page 18: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/18.jpg)
3.5 Healthkit:
Apple developed Healthkit to enable developer to develop health
and fitness application. By using Healthkit and the customer
approval you can share the health Data on Apple health Database
to your application. You can use these health data , make your
changes and calculation on it, which can make your application a
valuable health source. You can use Healthkit in your application by
turning on the Healthkit icon on xcode that will give a lot of options
in your code.
3.6 MyHealth In my thesis study I implemented a health application on iPhone and Apple watch that has
the name “ MyHealth”. The application will have two interfaces. The user interacts with
each interface differently.
12
![Page 19: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/19.jpg)
Figure 2: User interact with iPhone system.
Figure 2 shows how the User will interact with iPhone interface. The user should use the
iPhone to Add his medicine, Add emergency contacts and deal with the notifications.
13
![Page 20: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/20.jpg)
Figure 3: User interact with Apple Watch interface.
14
![Page 21: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/21.jpg)
Figure 3 shows the User interact with Apple watch interface. It will read the heart rate
and show what is the heart pulse. Also, the notification will show on the watch to remind the user
of his medicine. The user can deal with the notification on the watch.
Figure 4 DFD diagram of heart rate measurement
Figure 4 show the main feature of MyHealth application. To measure the heart rate the
user should wear the watch. The application will send notification to the user that it will measure
the heart rate. In case of the heart rate below or up the normal level the App will send the
notification to his emergency contact. Otherwise it will save the read and repeat the process after
10 minutes.
15
![Page 22: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/22.jpg)
3.7 MyHealth Design Since the target is elderly people in my design I choose it to be simple, direct, easy to use.
When you first run the app it will show the first interface screen.
This is my health main screen when you first run the app it will ask you the approval to user your
health data. If you approve you can use the application easily. As it is shown on the button there
are two tabs. If you click the Reminder button this page will be shown:
16
![Page 23: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/23.jpg)
In this page the user should write his medicine name. The start date and time and the End
date and time for his medicine. The Repeat drop down list it will give you the option to repeat
the reminder notification for a week, month, year.
The contacts button allows the User to choose or enter his emergency contacts. The user
can choose two of his contacts to let the App call them in case of emergency. The user can
choose three of his contacts to text and five contacts to send email to them of his Health data and
in case of emergency.
When the App run on the watch first it will show this message to test that the notification
will be shown when the user chooses First button it will Lunch the heart rate
measurement window.
17
![Page 24: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/24.jpg)
When the App is measuring the heart rate this window will be shown on the watch to record the heart rate of the user. At this time the sensor will be green led that’s
mean the App is measuring the heart rate.
18
![Page 25: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/25.jpg)
Chapter 4 Implementation.
To implement MyHealth Application I used:
Macbook pro with El Capitan Operating System.
Xcode 7.3 platform.
Swift 2.0 programming language.
iPhone 6 simulator.
Apple Watch 38 mm simulator.
In my xcode application I used:
Watchkit as target
Different swift files.
AppGroup.
Healthkit.
Inside the xcode application there are three main files which are:
MyHealth which is for the iPhone filesMyHealthWatch which is for the watch
interface.MyHealthWatchExtension which is for
the result on the Watch.
19
![Page 26: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/26.jpg)
The files under MyHealth folder are:
the first file is FirstViewController.swift
//// FirstViewController.swift// MyHealth//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKitimport HealthKit
/** ViewController for the first view to be displayed and register all required events **/
class FirstViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. //Register notifications declared in AppDelegate NSNotificationCenter.defaultCenter().addObserver(self, selector:"drawAShape:", name: "actionOnePressed", object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"showAMessage:", name: "actionTwoPressed", object: nil) // NSTimer.scheduledTimerWithTimeInterval(10.0, target: self, selector: #selector(FirstViewController.phoneNotificationHandler), userInfo: nil, repeats: true) //This calls ensures to call the alert every x.0 seconds //This is reminder for call the heart rate every X seconds , so it can be configured to any value NSTimer.scheduledTimerWithTimeInterval(300.0, target: self, selector:
These are the files that will be shown on the iPhone to implement
the notifications list and the the contacts list and Medicine
reminder list.
20
![Page 27: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/27.jpg)
#selector(FirstViewController.triggerHeartRateNotification), userInfo: nil, repeats: true) } let healthStore: HKHealthStore = HKHealthStore() // Create a MessageComposer let messageComposer = MessageComposer() func phoneNotificationHandler(){ let current = defaults.doubleForKey("heartRate") print("currentcurrentcurrent ",current) print("OLLLLLDDD ",old) if(current != old){ old = current // Make sure the device can send text messages if (messageComposer.canSendText()) { // Obtain a configured MFMessageComposeViewController let messageComposeVC = messageComposer.configuredMessageComposeViewController() // Present the configured MFMessageComposeViewController instance // Note that the dismissal of the VC will be handled by the messageComposer instance, // since it implements the appropriate delegate call-back presentViewController(messageComposeVC, animated: true, completion: nil) } else { // Let the user know if his/her device isn't able to send text messages let errorAlert = UIAlertView(title: "Unsupported Device", message: "Device doesnt support text message", delegate: self, cancelButtonTitle: "OK") errorAlert.show() } } } //This will trigger Heart rate count to notify every time //so it will create a notification event on user mobile to start the heart rate count every x minute func triggerHeartRateNotification(){ print("Trigger-------------") readHeartRate(); // createHeartRateStreamingQuery() let currDate = NSDate() let notification:UILocalNotification = UILocalNotification() //trigger the notification after a while notification.fireDate = NSDate(timeIntervalSinceNow: 5) notification.category = "FIRST_CATEGORY" notification.alertBody = "Heart Rate reminder" notification.fireDate = currDate UIApplication.sharedApplication().scheduleLocalNotification(notification) }
21
![Page 28: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/28.jpg)
let shareDate = DataSingleton.sharedInstance let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() var old = 0.0 var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor)) func checkHeartVital(){ guard HKHealthStore.isHealthDataAvailable() == true else { return } //Accepts the HealthData quantity guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return } let predicate = HKQuery.predicateForSamplesWithStartDate(NSDate(), endDate: nil, options: HKQueryOptions.None) NSLog("%@", "OKOKOKOKOKOKOKKOKo") let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: predicate, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in guard let newAnchor = newAnchor else {return} self.anchor = newAnchor self.printit(sampleObjects) } heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in self.anchor = newAnchor! self.printit(samples) } // return heartRateQuery } func printit(samples:[HKSample]?){ guard let heartRateSamples = samples as? [HKQuantitySample] else {return} guard let sample = heartRateSamples.first else{return} NSLog("samplesamplesample%lf", sample) } //https://github.com/mutualmobile/MMWormhole func readHeartRate() { //http://jamesleist.com/ios-swift-passing-data-between-viewcontrollers/ //pass data ll over viewcontroller //default woint work
22
![Page 29: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/29.jpg)
checkHeartVital() let heartRate = 0.0 print("READ THE VAKUE ",heartRate) NSLog("VALUE=WHY NOY >>>>>> %lf", DataSingleton.sharedInstance.heartRate) NSLog("oldoldold==>>>>>>>>>>>> %d", old) let appGroupID = "group.com.myheart.health.MyHealth" let defaultsGrp = NSUserDefaults(suiteName: appGroupID) if let rate = defaultsGrp?.doubleForKey("heartRateMain"){ NSLog("ZIAARARARARARRARARARARARA %lf", rate) } if(heartRate > 60.0 || (heartRate < 55.0 && heartRate > 0.0)){ old = heartRate //reset the heart Rate value to not get triggered //defaults.setDouble(58.0, forKey: "heartRate") //defaults.synchronize() let currDate = NSDate() let notification:UILocalNotification = UILocalNotification() //trigger the notification after a while notification.fireDate = NSDate(timeIntervalSinceNow: 20) notification.category = "HEART_RATE_ALERT" notification.alertBody = "Heart Rate Warning!!!" notification.fireDate = currDate UIApplication.sharedApplication().scheduleLocalNotification(notification) if (messageComposer.canSendText()) { // Obtain a configured MFMessageComposeViewController let messageComposeVC = messageComposer.configuredMessageComposeViewController() // Present the configured MFMessageComposeViewController instance // Note that the dismissal of the VC will be handled by the messageComposer instance, // since it implements the appropriate delegate call-back presentViewController(messageComposeVC, animated: true, completion: nil) } else { // Let the user know if his/her device isn't able to send text messages let errorAlert = UIAlertView(title: "Unsupported Device", message: "Device doesnt support text message", delegate: self, cancelButtonTitle: "OK") errorAlert.show() } } } /** shape to show the view **/ func drawAShape(notification:NSNotification){ let view:UIView = UIView(frame:CGRectMake(10, 10, 100, 100)) view.backgroundColor = UIColor.redColor()
23
![Page 30: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/30.jpg)
self.view.addSubview(view) } /** notification message to show**/ func showAMessage(notification:NSNotification){ let message:UIAlertController = UIAlertController(title: "A Notification Message", message: "Press Action or...", preferredStyle: UIAlertControllerStyle.Alert) message.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(message, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
The SecondViewContoller.swift has the code for the notification that will be shown on the iphone :
/ SecondViewController.swift// MyHealth//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKit
/** This view for Reminder List to show all available notifications **/class SecondViewController: UITableViewController { //holds number of events var todoItems: [TodoMedicineItem] = []
// to ensure user receives any visual feedback that a notificatoon has fired //when the app is running in the foreground. // and once the app resumes, the list must be refreshed automatically override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshList", name: "TodoListShouldRefresh", object: nil) }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. }
24
![Page 31: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/31.jpg)
override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) refreshList() } /** refresh the entire table list to update the new item Note :Limiting itto schedule 64 local notifications. If try to schedule more, the system will keep the 64 soonest firing notifications & automatically discard the rest **/ func refreshList() { todoItems = TodoMedicineList.sharedInstance.allItems() //avoid running into issue by disallowing the creating of new items if 64 already exist if (todoItems.count >= 64) { self.navigationItem.rightBarButtonItem!.enabled = false // disable 'add' button } tableView.reloadData() } //defines number of sections override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } //returns the number of rows override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoItems.count } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { return true } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("todoCell", forIndexPath: indexPath) // retrieve the prototype cell (subtitle style) let todoItem = todoItems[indexPath.row] as TodoMedicineItem cell.textLabel?.text = todoItem.title as String! if (todoItem.isOverdue) { // the current time is later than the to-do item's deadline cell.detailTextLabel?.textColor = UIColor.redColor() } else { cell.detailTextLabel?.textColor = UIColor.blackColor() // we need to reset this because a cell with red subtitle may be returned by dequeueReusableCellWithIdentifier:indexPath: } let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "'Due' MMM dd 'at' h:mm a" // example: "Due Jan 01 at 12:00 PM" cell.detailTextLabel?.text = dateFormatter.stringFromDate(todoItem.deadline) return cell }
25
![Page 32: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/32.jpg)
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // the only editing style we'll support // Delete the row from the data source let item = todoItems.removeAtIndex(indexPath.row) // remove TodoItem from notifications array, assign removed item to 'item' tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) TodoMedicineList.sharedInstance.removeItem(item) // delete backing property list entry and unschedule local notification (if it still exists) self.navigationItem.rightBarButtonItem!.enabled = true // we definitely have under 64 notifications scheduled now, make sure 'add' button is enabled } }
}
The code to design and implement the Medicine tables are:
// MedicineListTVC.swift// MyHealth//// Created by Areej on 07/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKit
class MedicineListTVC: UIViewController {
@IBOutlet weak var titleField: UITextField! @IBOutlet weak var deadlinePicker: UIDatePicker! @IBAction func savePressed(sender: UIButton) { print("Saving d values") let todoItem = TodoMedicineItem(deadline: deadlinePicker.date, title: titleField.text!, UUID: NSUUID().UUIDString) TodoMedicineList.sharedInstance.addItem(todoItem) // schedule a local notification to persist this item
}}
// MedicineTableViewController.swift// MyHealth//// Created by Areej on 09/11/2015.// Copyright © 2015 ABC. All rights reserved.//
26
![Page 33: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/33.jpg)
import UIKit
class MedicineTableViewController: UITableViewController {
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell! return cell } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 3 }}
// TodoMedicine.swift// MyHealth//// Created by Areej on 07/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import Foundation
/** Object to handle variable for Medicine data it acts like a bean object **/struct TodoMedicineItem { var title: String var deadline: NSDate var UUID: String init(deadline: NSDate, title: String, UUID: String) { self.deadline = deadline self.title = title self.UUID = UUID } var isOverdue: Bool { return (NSDate().compare(self.deadline) == NSComparisonResult.OrderedDescending) // deadline is earlier than current date }}
// TodoMedicineList.swift// MyHealth//// Created by Areej on 07/11/2015.// Copyright © 2015 ABC. All rights reserved.//
27
![Page 34: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/34.jpg)
import Foundationimport UIKit
class TodoMedicineList{ private let ITEMS_KEY = "todoItems" //Single Instance class var sharedInstance : TodoMedicineList { struct Static { static let instance : TodoMedicineList = TodoMedicineList() } return Static.instance } func allItems() -> [TodoMedicineItem] { let todoDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(ITEMS_KEY) ?? [:] let items = Array(todoDictionary.values) return items.map({TodoMedicineItem(deadline: $0["deadline"] as! NSDate, title: $0["title"] as! String, UUID: $0["UUID"] as! String!)}).sort({(left: TodoMedicineItem, right:TodoMedicineItem) -> Bool in (left.deadline.compare(right.deadline) == .OrderedAscending) }) } /** persisting our items to the memory **/ func addItem(item: TodoMedicineItem) { // persist a representation of this todo item in NSUserDefaults var todoDictionary = NSUserDefaults.standardUserDefaults().dictionaryForKey(ITEMS_KEY) ?? Dictionary() // if todoItems hasn't been set in user defaults, initialize todoDictionary to an empty dictionary using nil-coalescing operator (??) todoDictionary[item.UUID] = ["deadline": item.deadline, "title": item.title, "UUID": item.UUID] // store NSData representation of todo item in dictionary with UUID as key NSUserDefaults.standardUserDefaults().setObject(todoDictionary, forKey: ITEMS_KEY) // save/overwrite todo item list // create a corresponding local notification let notification = UILocalNotification() notification.alertBody = "Todo Item \"\(item.title)\" Is Overdue" // text that will be displayed in the notification notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view" notification.fireDate = item.deadline // todo item due date (when notification will be fired) //https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/index.html#//apple_ref/doc/uid/TP40001451-SW2 //notification.repeatInterval = NSCalendarUnit.Day notification.soundName = UILocalNotificationDefaultSoundName // play default sound notification.userInfo = ["title": item.title, "UUID": item.UUID] // assign a unique identifier to the notification so that we can retrieve it later notification.category = "TODO_CATEGORY" //notification.repeatInterval = NSCalendarUnit. UIApplication.sharedApplication().scheduleLocalNotification(notification)
28
![Page 35: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/35.jpg)
//update the badge on adding new item self.setBadgeNumbers() } /** clear out complreted items from the list since we need to remove the existing notification , so we need to retreive the old one and cancel the same before scheduling **/ func removeItem(item: TodoMedicineItem) { for notification in (UIApplication.sharedApplication().scheduledLocalNotifications )! { // loop through notifications... if (notification.userInfo!["UUID"] as! String == item.UUID) { // ...and cancel the notification that corresponds to this TodoItem instance (matched by UUID) UIApplication.sharedApplication().cancelLocalNotification(notification) // there should be a maximum of one match on UUID break } } if var todoItems = NSUserDefaults.standardUserDefaults().dictionaryForKey(ITEMS_KEY) { todoItems.removeValueForKey(item.UUID) NSUserDefaults.standardUserDefaults().setObject(todoItems, forKey: ITEMS_KEY) // save/overwrite todo item list } //update the badge on removing item self.setBadgeNumbers() } //promt user with re-reminder after X number of minutes func scheduleReminderforItem(item: TodoMedicineItem) { let notification = UILocalNotification() // create a new reminder notification notification.alertBody = "Medicine Intake\"\(item.title)\" Is Overdue" // text that will be displayed in the notification notification.alertAction = "open" // text that is displayed after "slide to..." on the lock screen - defaults to "slide to view" notification.fireDate = NSDate().dateByAddingTimeInterval(30 * 60) // 30 minutes from current time notification.soundName = UILocalNotificationDefaultSoundName // play default sound notification.userInfo = ["title": item.title, "UUID": item.UUID] // assign a unique identifier to the notification that we can use to retrieve it later notification.category = "TODO_CATEGORY" UIApplication.sharedApplication().scheduleLocalNotification(notification) } /** after App Delegate is activated the way to show the badges, here the badge number to schedule to update automatically where todo items become overdue. We can’t instruct the app to simply increment the badge value when our notifications fire, but we can pre-compute and provide a value for the “applicationIconBadgeNumber” property of our local notifications
29
![Page 36: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/36.jpg)
**/ func setBadgeNumbers() { // var notifications = UIApplication.sharedApplication().scheduledLocalNotifications as! [UILocalNotification] // all scheduled notifications let todoItems: [TodoMedicineItem] = self.allItems() for notification in (UIApplication.sharedApplication().scheduledLocalNotifications )! { let overdueItems = todoItems.filter({ (todoItem) -> Bool in // array of to-do items... return (todoItem.deadline.compare(notification.fireDate!) != .OrderedDescending) // ...where item deadline is before or on notification fire date }) UIApplication.sharedApplication().cancelLocalNotification(notification) // cancel old notification notification.applicationIconBadgeNumber = overdueItems.count // set new badge number UIApplication.sharedApplication().scheduleLocalNotification(notification) // reschedule notification } } }
// MedicineInputTableViewController.swift// MyHealth//// Created by Areej on 12/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKit
/** Medicine input controller to handle any medicine entry to the ui **/class MedicineInputTableViewController: UITableViewController {
@IBOutlet weak var startLabel: UILabel! @IBOutlet weak var startDate: UIDatePicker! @IBOutlet weak var endDatePicker: UIDatePicker! @IBOutlet weak var titleField: UITextField!
@IBOutlet weak var endDateDetail: UILabel! @IBOutlet weak var repeatLbl: UILabel! var repeatSelectedValue:String! = "Never" //Save the medicine add content @IBAction func saveMedAlert(sender: AnyObject) { let todoItem = TodoMedicineItem(deadline: startDate.date, title: titleField.text!, UUID: NSUUID().UUIDString) TodoMedicineList.sharedInstance.addItem(todoItem) // schedule a local notification to persist this item
30
![Page 37: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/37.jpg)
}
var datePickerHidden = false var endPickerHidden = false func datePickerChanged () { startLabel.text = NSDateFormatter.localizedStringFromDate(startDate.date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle) } func endDateChanged(){ endDateDetail.text = NSDateFormatter.localizedStringFromDate(endDatePicker.date, dateStyle: NSDateFormatterStyle.ShortStyle, timeStyle: NSDateFormatterStyle.ShortStyle) } @IBAction func startDatePickerValue(sender: UIDatePicker) { datePickerChanged() } @IBAction func endDatePickerValue(sender: AnyObject) { endDateChanged() } override func viewDidLoad() { super.viewDidLoad() datePickerChanged() endDateChanged() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() repeatLbl.text = repeatSelectedValue }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // print(":::::::: SEGUE :::::::::::::: ",segue.identifier) } override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) { // print("in medicine ",identifier," ::: ",sender) } override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
31
![Page 38: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/38.jpg)
if indexPath.section == 1 && indexPath.row == 0 { toggleDatepicker() }else if indexPath.section == 2 && indexPath.row == 0 { toggleEndPicker() } } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { if datePickerHidden && indexPath.section == 1 && indexPath.row == 1 { return 0 } else if endPickerHidden && indexPath.section == 2 && indexPath.row == 1 { return 0 } else { return super.tableView(tableView, heightForRowAtIndexPath: indexPath) } } //Start Date picker func toggleDatepicker() { datePickerHidden = !datePickerHidden tableView.beginUpdates() tableView.endUpdates() } // End date picker func toggleEndPicker(){ endPickerHidden = !endPickerHidden tableView.beginUpdates() tableView.endUpdates() } }
To repeat medicine notification:
// RepeatTableViewController.swift// MyHealth//// Created by Areej on 12/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKit
class RepeatTableViewController: UITableViewController { var intervals = [String]()
32
![Page 39: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/39.jpg)
var selectedRepeat = Int() //http://stackoverflow.com/questions/6966365/uilocalnotification-repeat-interval-for-custom-alarm-sun-mon-tue-wed-thu-f enum RepeatInterval : String, CustomStringConvertible { case Never = "Never" case Every_Day = "Every Day" case Every_Week = "Every Week" case Every_2_Weeks = "Every 2 Weeks" case Every_Month = "Every Month" case Every_Year = "Every Year" var description : String { return rawValue } static let allValues = [Never, Every_Day, Every_Week, Every_2_Weeks, Every_Month, Every_Year] } override func performSegueWithIdentifier(identifier: String, sender: AnyObject?) { //MedicineInputTableViewController print("PERFORMRMRMRRM ",sender," idee ",identifier) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { //print(" prepare for Repeat ",segue.destinationViewController) let destination = segue.destinationViewController as? MyHealth.MedicineInputTableViewController //print(destination!.repeatSelectedValue) //print("selectedRepeat ",selectedRepeat) destination!.repeatSelectedValue = intervals[selectedRepeat]
/** Close the view after operation, need to work on this **/ // self.dismissViewControllerAnimated(true, completion: nil ) //navigationController?.popViewControllerAnimated(true) //var StatusVC: MedicineInputTableViewController = MedicineInputTableViewController() } override func viewDidLoad() { super.viewDidLoad() intervals = ["Never","Every Day","Every Week","Every 2 Weeks","Every Month","Every Year"]
// Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() }
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning()
33
![Page 40: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/40.jpg)
// Dispose of any resources that can be recreated. }
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 }
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete implementation, return the number of rows return intervals.count } override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return "Choices" }
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("repeatIdentifier", forIndexPath: indexPath)
// Configure the cell... cell.textLabel!.text = intervals[indexPath.row]
return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // print("You selected cell #\(indexPath.row)!") // Get Cell Label text here and storing it to the variable //let indexPathVal: NSIndexPath = tableView.indexPathForSelectedRow! //print("\(indexPathVal)") //let currentCell = tableView.cellForRowAtIndexPath(indexPathVal) as UITableViewCell!; //print("\(currentCell)") //print("\(currentCell.textLabel?.text!)") selectedRepeat = indexPath.row //Storing the data to a string from the selected cell //Now here I am performing the segue action after cell selection to the other view controller by using the segue Identifier Name self.performSegueWithIdentifier("medDetailsSegue", sender: self) }
}
The code for the emergency contacts list on the iPhone are:
// ConfigurationTableViewController.swift// MyHealth
34
![Page 41: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/41.jpg)
//// Created by Areej on 16/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import UIKitimport Contactsimport ContactsUIimport MessageUIimport HealthKit
class ConfigurationTableViewController: UITableViewController,CNContactPickerDelegate,MFMessageComposeViewControllerDelegate { @IBOutlet weak var nameTF: UITextField! @IBOutlet weak var addNameBtn: UIButton! @IBOutlet weak var phoneTF: UITextField! @IBOutlet weak var emergencyTF1: UITextField! @IBOutlet weak var emergencyTF2: UITextField! @IBOutlet weak var emergencyTF3: UITextField! @IBOutlet weak var emailTF1: UITextField! @IBOutlet weak var emailTF2: UITextField! @IBOutlet weak var emailTF3: UITextField! @IBOutlet weak var emailTF4: UITextField! var emergencyStatus1 = false var emergencyStatus2 = false var emergencyStatus3 = false var addNameStatus = false let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() let shareDate = DataSingleton.sharedInstance //Save the object values @IBAction func saveConfig(sender: AnyObject) { //sets the key for each field in the configuration saveDefaults() } func saveDefaults(){ self.defaults.removeObjectForKey("nameTF") self.defaults.removeObjectForKey("phoneTF") self.defaults.removeObjectForKey("emergencyTF1") self.defaults.removeObjectForKey("emergencyTF2") self.defaults.removeObjectForKey("emergencyTF3")
35
![Page 42: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/42.jpg)
print("phoneTF.textphoneTF.text" ,phoneTF.text) self.defaults.setObject(nameTF.text, forKey: "nameTF") self.defaults.setObject(phoneTF.text, forKey: "phoneTF") self.defaults.setObject(emergencyTF1.text, forKey: "emergencyTF1") self.defaults.setObject(emergencyTF2.text, forKey: "emergencyTF2") self.defaults.setObject(emergencyTF3.text, forKey: "emergencyTF3") self.defaults.synchronize() print("The value no>>>>>>w is=s> ",self.defaults.objectForKey("phoneTF")) } @IBAction func addPhoneAction(sender: AnyObject) { addNameStatus = true self.showContactPickerController() } @IBAction func addName(sender: AnyObject) { addNameStatus = true self.showContactPickerController()
} @IBAction func emergencyBtn1(sender: AnyObject) { emergencyStatus1 = true self.showContactPickerController() } @IBAction func emergencyBtn2(sender: AnyObject) { emergencyStatus2 = true self.showContactPickerController() } @IBAction func emergencyBtn3(sender: AnyObject) { emergencyStatus3 = true self.showContactPickerController() } // A wrapper function to indicate whether or not a text message can be sent from the user's device func canSendText() -> Bool { return MFMessageComposeViewController.canSendText() } // Configures and returns a MFMessageComposeViewController instance func configuredMessageComposeViewController(textMessageRecipients:[String] ,textBody body:String) -> MFMessageComposeViewController { let messageComposeVC = MFMessageComposeViewController() messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed!
36
![Page 43: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/43.jpg)
messageComposeVC.recipients = textMessageRecipients messageComposeVC.body = body return messageComposeVC } // Configures and returns a MFMessageComposeViewController instance func configuredMessageComposeViewController() -> MFMessageComposeViewController { let messageComposeVC = MFMessageComposeViewController() messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed! messageComposeVC.recipients = ["1-800-867-5309"] messageComposeVC.body = "Heart Rate Warning!! Patient Heart rate is abnormal" return messageComposeVC } // Create a MessageComposer let messageComposer = MessageComposer() //TODO close @IBAction func cancelConfig(sender: AnyObject) { print("KYAYYAYAYAYAYAYAY") print("Cancel " ,MFMessageComposeViewController.canSendText()) // Make sure the device can send text messages if (messageComposer.canSendText()) { // Obtain a configured MFMessageComposeViewController let messageComposeVC = messageComposer.configuredMessageComposeViewController() // Present the configured MFMessageComposeViewController instance // Note that the dismissal of the VC will be handled by the messageComposer instance, // since it implements the appropriate delegate call-back presentViewController(messageComposeVC, animated: true, completion: nil) } else { // Let the user know if his/her device isn't able to send text messages let errorAlert = UIAlertView(title: "Cannot Send Text Message", message: "Your device is not able to send text messages.", delegate: self, cancelButtonTitle: "OK") errorAlert.show() } }
private func callNumber(phoneNumber:String) { if let phoneCallURL:NSURL = NSURL(string:"tel://\(phoneNumber)") { let application:UIApplication = UIApplication.sharedApplication() if (application.canOpenURL(phoneCallURL)) { application.openURL(phoneCallURL) } } } override func viewWillDisappear(animated: Bool) { self.navigationController?.navigationBarHidden = false }
37
![Page 44: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/44.jpg)
@IBOutlet weak var addPhoneBtn: NSLayoutConstraint! private var store: CNContactStore! private var menuArray: NSMutableArray?
override func viewDidLoad() { super.viewDidLoad() loadDefaultValues()
print("LOAD THE VALUES ") //read the heart rate //NSTimer.scheduledTimerWithTimeInterval(20.0, target: self, selector: Selector("readHeartRate"), userInfo: nil, repeats: true) // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() store = CNContactStore() authorizeAddressBookAddress() }
//This method reads the heart rate every x seconds and ensure that it doesn't crosses the //limit and if it does, as of now it throws an alert to the user //can be made to call user once the call api works properly func readHeartRate(){ let heartRate = self.defaults.doubleForKey("heartRate") print("READ THE VAKUE ",heartRate) if(heartRate > 60.0 || heartRate < 55.0){ if let phoneTF = defaults.stringForKey("phoneTF") { print("phonssseTF",phoneTF) } //reset the heart Rate value to not get triggered // self.defaults.setDouble(58.0, forKey: "heartRate") // self.defaults.synchronize() let currDate = NSDate() let notification:UILocalNotification = UILocalNotification() //trigger the notification after a while notification.fireDate = NSDate(timeIntervalSinceNow: 20) notification.category = "HEART_RATE_ALERT" notification.alertBody = "Heart Rate Warning!!!" notification.fireDate = currDate
38
![Page 45: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/45.jpg)
UIApplication.sharedApplication().scheduleLocalNotification(notification) } } //refer http://stackoverflow.com/questions/27642492/saving-and-loading-an-integer-on-xcode-swift //load default values once you launch the App func loadDefaultValues(){ let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() nameTF?.text = defaults.valueForKey("nameTF") as? String phoneTF?.text = defaults.valueForKey("phoneTF") as? String emergencyTF1?.text = defaults.valueForKey("emergencyTF1") as? String emergencyTF2?.text = defaults.valueForKey("emergencyTF2") as? String emergencyTF3?.text = defaults.valueForKey("emergencyTF3") as? String } func authorizeAddressBookAddress(){
switch CNContactStore.authorizationStatusForEntityType(.Contacts){ case .Authorized: print("Authorized")// completionHandler(accessGranted: true) case .NotDetermined: print("Not Determined") self.requestContactsAccess() default: print("Not handled") } } /* request Contact Access if its not determined. The access can be provided using grant access */ private func requestContactsAccess() { store.requestAccessForEntityType(.Contacts) {granted, error in if granted { dispatch_async(dispatch_get_main_queue()) { // self.accessGrantedForContacts() return } } } } //MARK: Show all contacts // Called when users tap "Display Picker" in the application. Displays a list of contacts and allows users to select a contact from that list.
39
![Page 46: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/46.jpg)
// The application only shows the phone, email, and birthdate information of the selected contact. private func showContactPickerController() { let contactPicker = CNContactPickerViewController() contactPicker.delegate = self contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey, CNContactEmailAddressesKey, CNContactGivenNameKey] self.presentViewController(contactPicker, animated: true, completion: nil) } func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) { let contact = contactProperty.contact //set the Phone Number in first column if let phoneNumber = contactProperty.value as? CNPhoneNumber { if addNameStatus { print(phoneNumber.stringValue) phoneTF?.text = phoneNumber.stringValue print(contact.givenName) nameTF?.text = contact.givenName addNameStatus = false }else if emergencyStatus1{ emergencyTF1?.text = phoneNumber.stringValue emergencyStatus1 = false }else if emergencyStatus2{ emergencyTF2?.text = phoneNumber.stringValue emergencyStatus2 = false }else if emergencyStatus3{ emergencyTF3?.text = phoneNumber.stringValue emergencyStatus3 = false } }
}
override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Implement this if you want to do additional work when the picker is cancelled by the user. func contactPickerDidCancel(picker: CNContactPickerViewController) { picker.dismissViewControllerAnimated(true, completion: {}) } func messageComposeViewController(controller: MFMessageComposeViewController, didFinishWithResult result: MessageComposeResult) {
40
![Page 47: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/47.jpg)
//... handle sms screen actions // self.dismissViewControllerAnimated(true, completion: nil) controller.dismissViewControllerAnimated(true, completion: nil) }}
The code to notify the Emergency cntacts in case of Emergency are:
//// MessageComposer.swift// MyHealth//// Created by Areej on 07/01/2016.// Copyright © 2016 ABC. All rights reserved.//
import Foundationimport MessageUI
let textMessageRecipients = ["1-800-867-5309"] // for pre-populating the recipients list (optional, depending on your needs)
class MessageComposer: NSObject, MFMessageComposeViewControllerDelegate { // A wrapper function to indicate whether or not a text message can be sent from the user's device func canSendText() -> Bool { return MFMessageComposeViewController.canSendText() } // Configures and returns a MFMessageComposeViewController instance func configuredMessageComposeViewController() -> MFMessageComposeViewController { let messageComposeVC = MFMessageComposeViewController() messageComposeVC.messageComposeDelegate = self // Make sure to set this property to self, so that the controller can be dismissed! messageComposeVC.recipients = textMessageRecipients messageComposeVC.body = "Heart Rate Warning!! Patient Heart rate is abnormal" return messageComposeVC } // MFMessageComposeViewControllerDelegate callback - dismisses the view controller when the user is finished with it func messageComposeViewController(controller: MFMessageComposeViewController!, didFinishWithResult result: MessageComposeResult) { controller.dismissViewControllerAnimated(true, completion: nil) }}
// DataSingleton.swift// MyHealth//// Created by Areej on 30/03/2016.// Copyright © 2016 ABC. All rights reserved.//
import UIKitimport Foundation
41
![Page 48: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/48.jpg)
class DataSingleton { static let sharedInstance = DataSingleton() private init() {} var heartRate : Double = 58.0
}
The code that handles the Watch output are on The MyHealthWatch Extension and these files are:
// InterfaceController.swift// MyHealthWatch Extension//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import WatchKitimport Foundationimport HealthKitimport UIKit
/** Watch Notification & Controller **/class InterfaceController: WKInterfaceController,HKWorkoutSessionDelegate { @IBOutlet var heart: WKInterfaceImage! @IBOutlet var headerLbl: WKInterfaceLabel! @IBOutlet var outputLbl: WKInterfaceLabel! let healthStore: HKHealthStore = HKHealthStore() // define the activity type and location var workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor) let heartRateUnit = HKUnit(fromString: "count/min") var anchor = HKQueryAnchor(fromValue: Int(HKAnchoredObjectQueryNoAnchor)) var workoutEndDate: NSDate! var workoutStartDate: NSDate!
42
![Page 49: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/49.jpg)
var heartRateSample: [HKQuantitySample] = []
override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) workoutSession.delegate = self print("Waakeeeee ") // Configure interface objects here. } //ass workout session is killed it cannot be restarted //so everytime after session is killed we are creating a n //new workout session func reCreateWorkoutSession(){ workoutSession = HKWorkoutSession(activityType: HKWorkoutActivityType.CrossTraining, locationType: HKWorkoutSessionLocationType.Indoor) workoutSession.delegate = self } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() // defaults.setDouble(58.0, forKey: "heartRate") // If HealthStore is not accesible or user denies the access guard HKHealthStore.isHealthDataAvailable() == true else { headerLbl.setText("not available") return } //Accepts the HealthData quantity guard let quantityType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { displayNotAllowed() return } //type of data to share from healthapp let typeToShare = Set(arrayLiteral: quantityType) let dataTypes = Set(arrayLiteral: quantityType) //requesting to autorize the HealthStore access healthStore.requestAuthorizationToShareTypes(typeToShare, readTypes: dataTypes) { (success, error) -> Void in if success == false { self.displayNotAllowed() }else{ //triggers as soon as the UI Opens self.healthStore.startWorkoutSession(self.workoutSession) } } print("will activate ") }
func displayNotAllowed() { headerLbl.setText("not allowed")
43
![Page 50: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/50.jpg)
} override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() healthStore.endWorkoutSession(workoutSession) print("deactivate ") reCreateWorkoutSession() } /** Type of workout session If user running or stopped **/ func workoutSession(workoutSession: HKWorkoutSession, didChangeToState toState: HKWorkoutSessionState, fromState: HKWorkoutSessionState, date: NSDate) { switch toState { case .Running: workoutDidStart(date) case .Ended: workoutDidEnd(date) default: print("Unexpected state \(toState)") } } func workoutSession(workoutSession: HKWorkoutSession, didFailWithError error: NSError) { // Do nothing for now print("faiLC asee ",error ) }
//https://github.com/schickling/hackrisk-calm/blob/master/Calm/HealthKitHelper.swift //triggers the workout state func workoutDidStart(date : NSDate) { print("WORK OUT DID START") self.workoutStartDate = date NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector(nilLiteral: triggerQuery()), userInfo: nil, repeats: true)
}
let countPerMinuteUnit = HKUnit(fromString: "count/min")
func saveWorkout() -> Void { print("Came to Save") //save a workout if there are valid start and end dates // guard let startDate = self.workoutStartDate, endDate = self.workoutEndDate else {return}
44
![Page 51: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/51.jpg)
if self.heartRateSample.count >= 1{ let heartRateSample: HKQuantitySample = self.heartRateSample[self.heartRateSample.count - 1] let completion: ((Bool, NSError?) -> Void) = { (success, error) -> Void in if !success { print("An error occured saving the Heart Rate sample \(heartRateSample). In your app, try to handle this gracefully. The error was: \(error).") abort() }else{ print("Save Done ",heartRateSample) } } //self.healthStore.saveObject(<#T##object: HKObject##HKObject#>, withCompletion: <#T##(Bool, NSError?) -> Void#>) self.healthStore.saveObject(heartRateSample, withCompletion: completion) }
} override func willDisappear() { print("Content Has Disappaerrad") } // save the workout @IBAction func saveBtnPressed() { saveWorkout()
} //triggers the workout session @IBAction func startBtnPressed() { healthStore.startWorkoutSession(workoutSession) } @IBAction func stopBtnPressed() { healthStore.endWorkoutSession(workoutSession) } //on killing the heart rate , stop the executing query //and change the text and save the heart rate func workoutDidEnd(date : NSDate) {
45
![Page 52: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/52.jpg)
self.workoutEndDate = date if let query = createHeartRateStreamingQuery(date) { headerLbl.setText("Killing Healthkit...") healthStore.stopQuery(query) headerLbl.setText("Stop") saveWorkout() } else { headerLbl.setText("cannot stop") } } func triggerQuery() { let currentDate = NSDate() if let query = createHeartRateStreamingQuery(currentDate) { healthStore.executeQuery(query) } } //creates Heart rate query func createHeartRateStreamingQuery(workoutStartDate: NSDate) -> HKQuery? { // adding predicate will not work let predicate = HKQuery.predicateForSamplesWithStartDate(workoutStartDate, endDate: nil, options: HKQueryOptions.None) guard let quantityType = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeartRate) else { return nil } let heartRateQuery = HKAnchoredObjectQuery(type: quantityType, predicate: predicate, anchor: anchor, limit: Int(HKObjectQueryNoLimit)) { (query, sampleObjects, deletedObjects, newAnchor, error) -> Void in guard let newAnchor = newAnchor else {return} self.anchor = newAnchor self.updateHeartRate(sampleObjects) } heartRateQuery.updateHandler = {(query, samples, deleteObjects, newAnchor, error) -> Void in self.anchor = newAnchor! self.updateHeartRate(samples) } return heartRateQuery } let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
46
![Page 53: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/53.jpg)
//updates heart rate, here can be schedule if heart rate crosses certain level func updateHeartRate(samples: [HKSample]?) { guard let heartRateSamples = samples as? [HKQuantitySample] else {return} let appGroupID = "group.com.myheart.health.MyHealth" let defaultsGrp = NSUserDefaults(suiteName: appGroupID) //let max_heart_rate = defaults.valueForKey("hearyRate") as? Int DataSingleton.sharedInstance.heartRate = 96.0 dispatch_async(dispatch_get_main_queue()) { guard let sample = heartRateSamples.first else{return} let value = sample.quantity.doubleValueForUnit(self.heartRateUnit) let default_heartRate = self.defaults.doubleForKey("heartRate") DataSingleton.sharedInstance.heartRate = value print("WHAT IS THE VALUE :) ",DataSingleton.sharedInstance.heartRate) defaultsGrp!.setDouble(value, forKey: "heartRateMain")// if let defaultsgp = NSUserDefaults(suiteName: appGroupID) {// defaultsgp.setValue(value, forKey: "heartRateMain")// }
if let phoneTF = self.defaults.stringForKey("phoneTF") { print("phonssseTF",phoneTF) } // print("Valueeee==> ", value) if(default_heartRate < value && (value > 60.0 || value < 55.0)){ print("DFINALALLALALALALLAAL :) ",DataSingleton.sharedInstance.heartRate) self.defaults.setDouble(value, forKey: "heartRate") //self.defaults.setInteger(UInt16(value), forKey: "heartRate") //self.defaults.setObject(value, forKey: "heartRate") self.defaults.synchronize() print("The value now is=s> ",self.defaults.doubleForKey("heartRate")) }
// print("valu ",value," Time ",NSDate() ) self.outputLbl.setText(String(UInt16(value))) self.heartRateSample += heartRateSamples // retrieve source from sample let name = sample.sourceRevision.source.name self.updateDeviceName(name) self.animateHeart() }
47
![Page 54: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/54.jpg)
} func updateDeviceName(deviceName: String) { headerLbl.setText(deviceName) } //heart rate animation which shows heart beat func animateHeart() { self.animateWithDuration(0.5) { self.heart.setWidth(60) self.heart.setHeight(90) } let when = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * double_t(NSEC_PER_SEC))) let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) dispatch_after(when, queue) { dispatch_async(dispatch_get_main_queue(), { self.animateWithDuration(0.5, animations: { self.heart.setWidth(50) self.heart.setHeight(80) }) }) } }
override func handleUserActivity(userInfo: [NSObject : AnyObject]?) { _ = userInfo!["identifier"] as! String print(" HANDLDLLD handleUserActivity " ,userInfo?["identifier"]) } override func handleActionWithIdentifier(identifier: String?, forLocalNotification localNotification: UILocalNotification) { print("CLCK HANDLE NOTIFICATIOn .......... ",identifier) }}
// ExtensionDelegate.swift// MyHealthWatch Extension//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import WatchKit
class ExtensionDelegate: NSObject, WKExtensionDelegate {
func applicationDidFinishLaunching() { // Perform any final initialization of your application. }
func applicationDidBecomeActive() {
48
![Page 55: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/55.jpg)
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. }
func applicationWillResignActive() { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, etc. }
}
// NotificationController.swift// MyHealthWatch Extension//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import WatchKitimport Foundation
class NotificationController: WKUserNotificationInterfaceController {
override init() { // Initialize variables here. super.init() // Configure interface objects here. }
override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() }
override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() }
override func didReceiveLocalNotification(localNotification: UILocalNotification, withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) { // This method is called when a local notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification interface as quickly as possible. // // After populating your dynamic notification interface call the completion block. completionHandler(.Custom) }
}
49
![Page 56: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/56.jpg)
// GlanceController.swift// MyHealthWatch Extension//// Created by Areej on 06/11/2015.// Copyright © 2015 ABC. All rights reserved.//
import WatchKitimport Foundation
class GlanceController: WKInterfaceController {
override func awakeWithContext(context: AnyObject?) { super.awakeWithContext(context) // Configure interface objects here. }
override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() }
override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() }
}
50
![Page 57: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/57.jpg)
Chapter 5 Lesson Learned and Challenges.
Since I start working on my proposal I faced a lot of bad times that I felt I couldn’t make it
anymore and good times when I achieve one task of my application. I was taking a risk of my
application since Apple announce that Healthkit will be open source five months before I start
working on my application. At the beginning I was working on Xcode 7.2 platform but two
months later Apple release Xcode 7.3 I read a lot about it and the decision was not easy should I
upgrade and risk that my application or nor or should I stay on this version even though it is slow
and hangs a lot. I took my chance and upgrade my Xcode to 7.3 which really made a difference
on the time processing the code. Swift 2.0 is an open source programming language it changes
everyday which some times made it hard to implements. Some times the code has no error and in
the second time you work on the code Xcode does not recognize the definition.
My application idea was to measure the heart rate each 10 minutes with out the user knowing
that the watch is measuring the heart rate but that was impossible. I searched a lot and contact
Apple developer society with my problem to find out that before the watch measurement begins
it should at least send a notification to the user because in real life if we implement application
who do that it will finish the Apple watch battery in minutes. So it is not logical to do. So, there
suppose to be a notification before the heart rate measurement. As my professor Chow suggested
after my proposal that I should use the research kit as an add to my application by searching I
found that the research kit is written in Objective-C so I can’t add it to my application but I tried
to record the heart rate data to the user and when the application send it by email weekly you can
do more that research on these data. You can monitor the heart rate health of the user if the
physician found something unusual on the data maybe he can help prevent bad things to happen.
51
![Page 58: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/58.jpg)
Many times the application did not work as it suppose to be that was frustrating to me. In these
cases, I learned that each problem has a solution if I tried to divide the task to small tasks and
each task individually. That’s will make me focus on each task and search a lot about it.
In summery I can say the lessons I learned working on my application are:
Implementing Mobile Health Application is not easy you have to consider all scenarios
that may happen and in real life you do not want any mistakes cause the result is related
to human lives. I can see why there is a limitation on Mobile health industry specially on
critical areas.
After implementing the application and want to test on actual devices the result may
changes the things that have been worked on simulator may not work as it is on the
devices that’s why you need to consider the changes.
My computer had some problems and I took to be formatted so I was trying to code on
my friend’s lab top and to use Xcode on different computer that will revoke your
developer certificate and you need to renew it and that’s gave me really hard time to find
the solution to this problem. I had to renew my Apple developer account for one year
more.
HealthKit gave you a lot of choices to work with the health data but sometimes there is
limits you can not exceed and if your goal is to do something beyond these limits you
have to search more and be smarter than the Healthkit.
52
![Page 59: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/59.jpg)
Chapter 6 Future Direction.
IOS development is an extensive process that involves mastery of the tools for the development
that is the WatchKit framework. It is then coupled with WatchKit extensions and WatchKit
application. The developer then needs to build up an understanding of the interface, positioning
and formatting. Also, they need mastery of the actions and outlets as well as the lifecycle for the
interface. Further, they need to know groups, the storyboard, interface objects, how to navigate
and finally to perform a test on the application. A lot of test needs to be performs on the
WatchKit but it is something really important to know and work with.
After implementing MyHealth application I hope that It will made the base for future
enhancements and improvements in this area. I had many ideas for my application that I wish in
the future if I had the time I could implement it or maybe in my PhD studies I can develop that.
One idea for the application as if it is for seniors it is common to have memory problems so, if
each time the medicine reminder notification shows if we can implement a bar code reader to
read the bar code on the medicine that can make sure that he is on his medicines. Second idea, if
we can develop and implement sensor machines that can track the hand and body movements so
in cases that the user need physical therapy that recommend doing some exercises we can track if
the user are doing these exercises on the right way. Doctor Lewis gave me a really interesting
idea he is doing a lot of researches on medical applications he told me that if we can develop and
implement sensor machine to record the ECG the electrocardiogram of the heart which can used
to assess the electrical and muscular functions of the heart. If we record it in a good and correct
way, we can find out the heart attack before it will happen. Managing your health life away from
hospitals is the goal of mobile health application if we can think of the diseases that you have to
53
![Page 60: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/60.jpg)
deal with and taking care of your self while you are doing your daily routine we can find an idea
for each need.
Mobile health development is considering a work in progress. It depends on the patients needs
and demands. That does not mean all these application is successful. To consider the application
is successful it depends on it’s performance when it is needed, on the market demand on it, is it
will be needed on five years or not. That’s what the developer are thinking about before develop
in health application. Nowadays Fitness application prove it is quality and effected on people
lives [Miller2014].
The future direction on mobile health application is the application that gather the information
from the user not the ones that give the user the information. That what Apple did in the
ResearchKit that helps to develop application that gather ingormation and health data from the
user to help in research areas[Miller2014]. So, if we consider this to improve MyHealth
application to record the heart rate measurement data and if we improve it to collect other health
information using other development tools that will take the application to upgraded level. I hope
to be able to work on that on the near future.
54
![Page 61: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/61.jpg)
Chapter 7 Conclusion.
These days’ people are depending on there smart phone in many ways. To organize their daily
tasks. To navigate to a specific location and to remember what they are suppose to do in a certain
time.
There are a lot of mobile health application these days on iPhone, android that’s aspiring to
achieve their goals to improve the health ad fitness life of the user. The requirements for mobile
health application will change with the change of people health issues. Health insurance expense
and care limitation on hospitals are main reasons for the continues demands on mobile health
application that helps users to adapt to his health issues away from hospitals.
These health application helps to increase the aware of the patient parent and relatives of the
illness that the user may have. In some Autosome cases there is a lot of application that helps the
parents to be more aware of their child needs. There are a lot of exercises that they can do to help
their child to adapt with his environment and improve his situation with the help of these Apps
that gives steps and detailed information for them.
iOS development using Swift 2 is an interesting experience it gives a lot of option that you can
implement but on the other hand Apple made some limitation to the developers that you can not
cross. You have to search, dig more to make the development tools serve your Application goal.
Healthkit gives you the access to the user health data and enable you to implement application
that serve health area. Appgroup made it easier to share data between the iPhone and Apple
watch. You can save data to Appgroup and retrieve these data using the same group name.
Apple watch serve the mobile health application with it’s built in features. Sensors to measure
heart rate and sensors to track the movement. While you are setting on your chair watching your
favorite TV show you can get the result of measuring heart rate as the same as on hospital with
55
![Page 62: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/62.jpg)
only one click on your Apple watch. No doubt that made our life easier and more functional.
Using these features of apple watch on developing mobile health application will achieve a
quantum jump in the field of mobile application development. Instead of developing machines
that has sensors to evaluate and measure your health vitals you can use the Apple watch to save
time implementing and developing with the same result as you want at the end.
Focusing on elderly people is important as their population has been increased. Some of them
alone with no relative to watch them all the time and some away of their relatives. To implement
mobile application with easy of use on its interface will help to manage and control their health
needs without the need of supervision or staying at nursery. Seniors needs health application
more cause when you get older your health life needs more care and attention. That is the reason
of choosing seniors as a target of my thesis study. Because I hope some one will use my study
and improve my application to help our parents, grandparents and our self’s when the time
comes that we need to focus more on our health issues and needs.
At the end my Thesis proposal question was: Can I design an accurate and effective application
using HealthKit with the Apple Watch?
After five months of studying and implementing my application on iPhone and Apple Watch I
can answer Yes I can design Health Application on both devices using HealthKit but to call my
application effective I need years of testing on real people life so as a developer I can say my
application can do what is suppose to do. In the future I can see promising ideas and
improvements.
56
![Page 63: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/63.jpg)
Chapter 8 References:
[Diva2013] Divall, Pip, Janette Camosso-Stefinovic, and Richard Baker. "The use of personal
digital assistants in clinical decision making by health care professionals: a systematic review."
Health informatics journal 19.1 (2013): 16-28.
[Guar2015], Guardian News (2015). Apple Watch has designs on health industry – but is it good
for doctors? The Guardian News. Retrieved from
<http://www.theguardian.com/technology/2014/sep/10/apple-watch-health-app-iphone-
smartwatch>
[Kise2011] Kiser, Kim. "25 ways to use your smartphone. Physicians share their favorite uses
and apps." Minn Med 94.4 (2011): 22-9.
[Onei2013] O’Neill, K. M., et al. "Applying surgical apps: Smartphone and tablet apps prove
useful in clinical practice." Bull Am Coll Surg 98.11 (2013): 10-18.
[Ozda2012] Ozdalga, Errol, Ark Ozdalga, and Neera Ahuja. "The smartphone in medicine: a
review of current and potential use among physicians and students." Journal of medical Internet
research 14.5 (2012).
[Yoo2013] Yoo, Jin-Hong. "The meaning of information technology (IT) mobile devices to me,
the infectious disease physician." Infection & chemotherapy 45.2 (2013): 244-251.
[GreatCall] http://www.greatcall.com/lp/is-mobile-healthcare-the-future-infographic.aspx
[Appledeveloper] https://developer.apple.com/
[Tom2014] Tom Harrington “Sharing data between iOS apps and app extensions” (2014)http://www.atomicbird.com/blog/sharing-with-app-extensions
57
![Page 64: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/64.jpg)
[Miller2014] Jen A. Miller “The Future of mHealth Goes Well Beyond Fitness Apps” (2014)
http://www.cio.com/article/2855047/healthcare/the-future-of-mhealth-goes-well-beyond-fitness-
apps.html
58
![Page 65: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/65.jpg)
Chapter 9 Appendix
9.1 Installation and Demo Steps.
Because my application is for test and study only I did not publish it to Apple store yet. To install
MyHealth application you need
Iphone 6 with 9.2 iOS or more
Apple watch
MyHealth xcode with developer account.
When you plug the iPhone paired with Apple watch to the computer open the xcode
application and run the App
On the iPhone and the watch, you will get the Application
This the iPhone main page when you first run the application it will be shown.
59
![Page 66: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/66.jpg)
When the application runs on The watch it will ask you to use Your Health Data The health data that is store on the
Apple Health database.
The application will ask you to send Notification that will be shown on the Watch and iPhone.
60
![Page 67: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/67.jpg)
This will be shown on the iPhone you have to turn on the Heart Rate button and click Allow on the top
right.
The Watch will start to measure your heart rate.
61
![Page 68: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/68.jpg)
In case of emergency when the heart rate above or under the Normal level the application will send a Notification to the user to notify him that his heart doesn’t seem good. When the user press Ok it will start
calling and texting.
62
![Page 69: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/69.jpg)
When the Medicine is overdue the Notification will be shown on both iPhone and watch to remind the user ta
take his medicine.
The User has two options either to remind him in 30 minutes or if he took his medicine he can choose
complete.
63
![Page 70: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/70.jpg)
The notification will show on the watch also so, twice daily there will be notification to remind the user to exercise if he chooses complete the phone will track
his movement and tell if he walks or run.
To make sure that the application is tracking the movement of the user the application when the
user start walking or running will send a notification to him.
64
![Page 71: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/71.jpg)
9.2 Performance:
After testing MyHealth application many times xcode enables you to measure your application
performance from Memory, CPU, Network and Disk usage.
This is the performance of running the application on the actual devices iPhone 6 and Apple
Watch.
65
![Page 72: Chapter 1 · Web viewApple watch serve the mobile health application with it’s built in features. Sensors to measure heart rate and sensors to track the movement. While you are](https://reader034.vdocuments.mx/reader034/viewer/2022042806/5f6bf04392327e15167ce7dc/html5/thumbnails/72.jpg)
so, the application is not heavy on the computer its only take 1% of CPU uses some times to 4 %
maximum. It is only needs 1.5 MB of memory used.
66