Running head: ROLE OF DESCRIPTIVE EPIDEMIOLOGY IN NURSING SCIENCE 1
ROLE OF DESCRIPTIVE EPIDEMIOLOGY IN NURSING SCIENCE 8
Role of Descriptive Epidemiology in Nursing Science
Steve Akinbehinje
DNP/825- Population Management
May 22, 2019
Descriptive Epidemiology
According to Naito (2014), “descriptive epidemiology is the epidemiological studies with much of the activities being in the descriptive component rather than the analytical component”. From the analytical epidemiology prospective, descriptive epidemiology deals with the reporting and identification of patterns and frequency of disease process in a population. In descriptive epidemiology, “the focus is on the occurrence of the diseases which is described through temporal trends and geographical comparisons” (Cassone & Mody, 2015). Descriptive epidemiology is therefore at the realm of evidence-based pyramid, they dictate an influence that is strong in the approach of epidemiology. Prevalence and incidence data of disease are relevant in today’s healthcare setting and research.
Relationship of Descriptive Epidemiology in Nursing Science
Unarguably, descriptive epidemiology centers on distribution and frequency of the health-related exposure or health outcome. “The analysis of who is affected by health outcome and how common it is showing prevalence as well as incidence” (Kim & Hooper, 2014). Person, place, and time can describe the aspect of people affected. An example in the explanation of the description of the distribution of health outcome with elements such as geography, population and time. “These aspects are crucial in nursing science as they provide a guideline which will be employed in the provision of quality care to outcome” (Montoya, Cassone & Mody, 2016). Subsequently, better understanding of disease severity is increased which enhance the development of prevention and management strategies. Whenever there is an improvement in healthcare outcome, the process that allows understanding of the changes that resulted in attaining the improvement is made possible through descriptive epidemiology.
Role of Descriptive Epidemiology in Nursing Science
Health data source and disease surveillance system are used to gather information when monitoring disease and health trends, and they are organized in such a way that enables the data to be systematically analyzed by descriptive epidemiology. Thus, the discrepancies in the frequency of the disease can be better understood over a given time (Fazel, Geddes & Kushel, 2014). Moreover, better understanding of disease variation of individuals in the basis of personal traits such as place and time is made possible thereby making the process of planning resources to address healthcare issues of the population easier. “The hypothesis that are used in making of the determinants about health and diseases are generated from the descriptive epidemiology” (Karimi et al., 2014). Most importantly, generating hypothesis is an initial s.
Running head ROLE OF DESCRIPTIVE EPIDEMIOLOGY IN NURSING SCIENCE .docx
1. Running head: ROLE OF DESCRIPTIVE EPIDEMIOLOGY IN
NURSING SCIENCE 1
ROLE OF DESCRIPTIVE EPIDEMIOLOGY IN NURSING
SCIENCE 8
Role of Descriptive Epidemiology in Nursing Science
Steve Akinbehinje
DNP/825- Population Management
May 22, 2019
Descriptive Epidemiology
According to Naito (2014), “descriptive epidemiology is the
epidemiological studies with much of the activities being in the
descriptive component rather than the analytical component”.
From the analytical epidemiology prospective, descriptive
epidemiology deals with the reporting and identification of
patterns and frequency of disease process in a population. In
descriptive epidemiology, “the focus is on the occurrence of the
diseases which is described through temporal trends and
geographical comparisons” (Cassone & Mody, 2015).
Descriptive epidemiology is therefore at the realm of evidence-
based pyramid, they dictate an influence that is strong in the
approach of epidemiology. Prevalence and incidence data of
2. disease are relevant in today’s healthcare setting and research.
Relationship of Descriptive Epidemiology in Nursing Science
Unarguably, descriptive epidemiology centers on distribution
and frequency of the health-related exposure or health outcome.
“The analysis of who is affected by health outcome and how
common it is showing prevalence as well as incidence” (Kim &
Hooper, 2014). Person, place, and time can describe the aspect
of people affected. An example in the explanation of the
description of the distribution of health outcome with elements
such as geography, population and time. “These aspects are
crucial in nursing science as they provide a guideline which will
be employed in the provision of quality care to outcome”
(Montoya, Cassone & Mody, 2016). Subsequently, better
understanding of disease severity is increased which enhance
the development of prevention and management strategies.
Whenever there is an improvement in healthcare outcome, the
process that allows understanding of the changes that resulted in
attaining the improvement is made possible through descriptive
epidemiology.
Role of Descriptive Epidemiology in Nursing Science
Health data source and disease surveillance system are used to
gather information when monitoring disease and health trends,
and they are organized in such a way that enables the data to be
systematically analyzed by descriptive epidemiology. Thus, the
discrepancies in the frequency of the disease can be better
understood over a given time (Fazel, Geddes & Kushel, 2014).
Moreover, better understanding of disease variation of
individuals in the basis of personal traits such as place and time
is made possible thereby making the process of planning
resources to address healthcare issues of the population easier.
“The hypothesis that are used in making of the determinants
about health and diseases are generated from the descriptive
epidemiology” (Karimi et al., 2014). Most importantly,
generating hypothesis is an initial step in starting analytic
epidemiology which depends on the testing of the association
between disease and health. Descriptive epidemiology has other
3. specific functions such as priority establishment of possible
health in a given population and its role is fundamental in
identifying any emerging health problem and setting an alarm
for possible outbreak. “The reporting and monitoring of health
status and other traits in a population is possible by descriptive
technology” (Naito, 2014). To determine the effectiveness of
any intervention, descriptive epidemiology must be utilized.
Suffice to say that descriptive epidemiology provides detail
description of individuals affected by disease with all factors
surrounding the individual. Through the analysis of descriptive
data, causative factors of a disease could be derived. Therefore,
both systems can be useful to explain the progression of risk
factors and reduction of disease incidence. “More importantly,
these factors are important in understanding the circumstances
and factors that might require public health improvement”
(Montoya, Cassone & Mody, 2016).
Application of Descriptive Epidemiology in Public Health
Nursing
As a science of public health, epidemiology has procedures
which promotes accuracy and validity in drawing of a
conclusion. “The results from epidemiology can prompt
effective measures such as the declaration of formal emergency,
legislative action, urgent legal action and large-scale
quarantine” (Kim & Hooper, 2014). Notable organizations such
as CDC and WHO are well positioned in their roles and methods
due to the far- reaching impact from epidemiology results.
Epidemiology methodologies proficiency and efficiency are
often needed for DNP students to enhance their ability to work
in healthcare settings in case there is disease outbreaks.
Public health nursing therefore focuses on individuals affected
by factors such as genetic, lifestyle, and environment in a
community and the goal of public health nursing is to prevent
disease and improve health care outcomes. Besides this, they
provide more direct care such as screening services, preventive
care and health education (Fazel, Geddes & Kushel, 2014).
While working in such an environment, they are expected to
4. recognize and respond to healthcare crisis, hence the need for
epidemiology knowledge.
Example of Descriptive Epidemiology in Public Health Nursing
Breastfeeding practices is widely known to improve baby’s
health and bonding with their mothers. A study can therefore be
conducted on the significance of breastfeeding in children with
emphasis on socioeconomic status, educational level, ethnicity,
mother’s age, marital status, and geographical locations. The
relevant information gathered from this study can be used to
identify what is needed in that population to enhance the
concept. For example, length of breastfeeding and frequency
with different race and socioeconomic status to develop a
comprehensive analysis and strategies that can be used to
booster breastfeeding practices.
Components of Epidemiology Used to Analyze At-Risk
Populations
Health issues or disease is a measure of the frequency of disease
when compared to population at risk at a time. “Numerators and
denominators are two important components highlighted in the
analysis of population at risk” (Karimi et al., 2014). The formal
represents in a mathematical term the upper section of the
fraction otherwise called the epidemiology and it is an
indication of what has been counted for example, the amount of
people affected by a specific disease while the latter represents
lower portion of the fraction and populations derived which is
the composition of the entire population that if affected by the
disease were to be included in the numerator. “This is what is
referred to as the population at risk as it is all those people who
are free of the disease during the collection of data” (Montoya,
Cassone & Mody, 2016). The calculated risk occurs when there
is the inclusion of people who were not in the position of
developing the disease of interest is underestimated.
Incidence and prevalence give rise to the frequency of the
diseases affecting the population of interest. “Incidence is
expressed in the person-time unit and measures the new cases of
disease while prevalence is expressed as a population and
5. measures the existing cases of the disease” (Fazel, Geddes &
Kushel, 2014). According to Kim & Hooper 2014, the
prevalence is measure by noting the proportion of people
affected by a disease or health-related event in a specified
population at a given time. While the existing cases are
measured using prevalence of the emerging cases of the disease
in a given population at a specified time are measured as
incidence.
There is ample evidence of the association between
socioeconomic status (SES) and multiple disease outcomes
(National Center for Health Statistics [NCHS], 2010). Lower
socioeconomic status as reflected in poverty, minority status,
and low education levels is consistently related to higher
occurrence of a range of major diseases including cancer, heart
disease, stroke, and diabetes, and to fair or poor health status
(NCHS, 2010). “Low SES (individual poverty, income
inequality, and area level poverty) was related over a 25-year
period to mortality even when the causes of death changed over
time” (Galea et al., 2011).
Conclusion
In conclusion, disease risk factors are described with
descriptive epidemiology using such factors as place, people,
and time. Epidemiology studies is critical to the determination,
influence, distribution, and frequency of disease in a given
population. In a null shell, descriptive epidemiology describes
not only time, place, and people but also how these factors are
related to health issues or disease. When these factors are
evaluated, a pattern that correspond the risks factor for a
specific disease can be noted. Epidemiology data collected is
used to furnish specific information necessary to influence
public policy. It is therefore pertinent for the DNP to study
epidemiology as they will be required at some point to
undertake such roles in healthcare setting.
Socioeconomic status as a fundamental cause of health
inequalities. It influences multiple disease outcomes, meaning
6. that SES is not limited to only one or a few diseases or health
problems but to many, SES affects these disease outcomes
through multiple risk factors (currently things such as smoking,
diet, exercise), it involves access (or lack of access) to
resources that can be used to avoid risks or to minimize the
consequences of disease once it occurs, and the association
between a fundamental cause and health status is reproduced
over time via the replacement of intervening predisposing
factors (e.g., overcrowding and poor sanitation replaced by
lifestyle choices and behaviors); that is, SES continues to
influence health inequalities even when the susceptibilities to
major morbidity and mortality change over time (Link &
Phelan, 1995)
References
Cassone, M., & Mody, L. (2015). Colonization with multidrug-
resistant organisms in nursing homes: scope, importance, and
management. Current geriatrics reports, 4(1), 87-95.
Fazel, S., Geddes, J. R., & Kushel, M. (2014). The health of
homeless people in high-income countries: descriptive
epidemiology, health consequences, and clinical and policy
recommendations. The Lancet, 384(9953), 1529-1540.
Galea, S., Tracy, M., Hoggatt, K. J., DiMaggio, C & Karpati, A
(2011). Estimated deaths attributable to social factors in the
United States. American Journal of Public Health, 101(8):1456–
1465.
Karimi, P., Islami, F., Anandasabapathy, S., Freedman, N. D., &
Kamangar, F. (2014). Gastric cancer: descriptive epidemiology,
risk factors, screening, and prevention. Cancer Epidemiology
and Prevention Biomarkers, 23(5), 700-713.
Kim, E. S., & Hooper, D. C. (2014). Clinical importance and
epidemiology of quinolone resistance. Infection &
chemotherapy, 46(4), 226-238.
Link, B. G & Phelan, J. C (1995). Social conditions as
fundamental causes of disease. Journal of Health and Social
Behavior, 35:80–94
7. Montoya, A., Cassone, M., & Mody, L. (2016). Infections in
nursing homes: epidemiology and prevention programs. Clinics
in geriatric medicine, 32(3), 585-607.
National Center for Health Statistics. Health United States
2010: With chartbook on trends in the health of Americans.
Hyattsville, MD: 2010. Retrieved from
http://www.cdc.gov/nchs/data/hus/hus10.pdf#056.
Naito, M. (2014). Utilization and application of public health
data in descriptive epidemiology. Journal of
epidemiology, 24(6), 435-436.
Practice Hours Completion Statement DNP-825
I, Steve Akinbehinje, verify that I have completed 10 clock
hours in association with the goals and objectives for this
assignment. I have also tracked said practice hours in the
Typhon Student Tracking System for verification purposes and
will be sure that all approvals are in place from my faculty and
practice mentor.
8. CaseAide Source code
AbbrWordDict.json
{
"Dictionary":[
{"Abbreviation":"CCL", "Word":"community care
licensing"},
{"Abbreviation":"CASA", "Word":"Court
Appointed Special Advocate"},
{"Abbreviation":"CPS", "Word":"Child Protective
Services"},
{"Abbreviation":"CFS", "Word":"Children and
Family Services"},
{"Abbreviation":"DPSS", "Word":"Department of
Public Social Services"},
{"Abbreviation":"DBH", "Word":"Department of
Mental Health"},
{"Abbreviation":"SW", "Word":"Social Worker"},
{"Abbreviation":"ILP", "Word":"Independent
Living Program"},
{"Abbreviation":"ILPSW", "Word":"Independent
Living Program Social Worker"},
{"Abbreviation":"MSW", "Word":"Masters in
Social Work"},
{"Abbreviation":"AWOL", "Word":"Absent Without
Leave"},
{"Abbreviation":"FFA", "Word":"Foster Family
Agency"},
{"Abbreviation":"FF", "Word":"Face to face"},
{"Abbreviation":"F2F", "Word":"Family to
Family"},
11. organization"},
{"Abbreviation":"CMT", "Word":"Case
Management Team"},
{"Abbreviation":"CM", "Word":"case
management"},
{"Abbreviation":"clt", "Word":"client"},
{"Abbreviation":"DA", "Word":"district attorney"},
{"Abbreviation":"DCFS", "Word":"Department of
Children and Family Services"},
{"Abbreviation":"HIV", "Word":"Human
Immunodeficiency"},
{"Abbreviation":"ICU", "Word":"intensive care
unit"},
{"Abbreviation":"IL", "Word":"Independent
Living"},
{"Abbreviation":"NA", "Word":"Narcotics
Anonymous"},
{"Abbreviation":"PHN", "Word":"Public Health
Nurse"},
{"Abbreviation":"CD", "Word":"Conduct
Disorder"},
{"Abbreviation":"TBS", "Word":"Therapeutic
Behavioral Services"},
{"Abbreviation":"MHS", "Word":"Mental Health
Services"},
{"Abbreviation":"SOP", "Word":"Safety Organized
Practices"},
{"Abbreviation":"Plt", "Word":"Placement"},
{"Abbreviation":"CW", "Word":"Child welfare"},
{"Abbreviation":"CSWE", "Word":"Council of
Social Work Education"},
{"Abbreviation":"RJC", "Word":"Riverside Juvenile
Court"},
{"Abbreviation":"SBJC", "Word":"San Bernardino
Juvenile Court"},
12. {"Abbreviation":"IYRT", "Word":"Interagency
Youth Resiliencey Team"},
{"Abbreviation":"EFC", "Word":"Extended Foster
Care"},
{"Abbreviation":"DMH", "Word":"Department of
Mental Health"},
{"Abbreviation":"IHSS", "Word":"In Home Support
Services"},
{"Abbreviation":"APS", "Word":"Adult Protective
Services"},
{"Abbreviation":"DOB", "Word":"date of birth"},
{"Abbreviation":"DUI", "Word":"driving under the
influence"},
{"Abbreviation":"EAP", "Word":"Employment
Assistance Program"},
{"Abbreviation":"EW", "Word":"Eligibility
Worker"},
{"Abbreviation":"SSA", "Word":"Social Service
Assistant"},
{"Abbreviation":"SSP", "Word":"Social Service
Practitioner"},
{"Abbreviation":"SSS", "Word":"Social Service
Supervisor"},
{"Abbreviation":"TILP", "Word":"Transitional
Independent Living Plan"},
{"Abbreviation":"SILP", "Word":"Supervised
Independent Living Placement"},
{"Abbreviation":"CFVAN", "Word":"Client was
free from any visible signs of abuse or neglect"},
{"Abbreviation":"CVAN", "Word":"Client had
visible sings of abuse and neglect"},
{"Abbreviation":"IRC", "Word":"Inland Regional
Center"},
{"Abbreviation":"Sup", "Word":"supervisor"},
{"Abbreviation":"DPO", "Word":"Deputy Probation
Officer"},
13. {"Abbreviation":"SO", "Word":"Sherriff Officer"},
{"Abbreviation":"CAPTS", "Word":"Child Abuse
Prevention and Treatment Team"},
{"Abbreviation":"ACT", "Word":"Assessment and
Consultation Team"},
{"Abbreviation":"FVSC", "Word":"Family
Visitation and Support Center"},
{"Abbreviation":"CFT’s", "Word":"Child and
Family Team Meeting"},
{"Abbreviation":"CLETS", "Word":"California Law
Enforcement Telecommunication System"},
{"Abbreviation":"CPR", "Word":"Concurrent
Planning Review"},
{"Abbreviation":"CNS", "Word":"Children’s
Strengths and Needs"},
{"Abbreviation":"MDT", "Word":"Multi-
Disciplinary Team"},
{"Abbreviation":"PAS", "Word":"Purchase
Authorization for Service"},
{"Abbreviation":"PMU", "Word":"Placement
Managenent Unit"},
{"Abbreviation":"PPLA", "Word":"Planned
Permanent Living Arrangement"},
{"Abbreviation":"RAU", "Word":"Relative
assessment Unit"},
{"Abbreviation":"RCAT", "Word":"Riverside Child
Assessment Team"},
{"Abbreviation":"MHST", "Word":"Mental health
Screening Tool"},
{"Abbreviation":"PGM", "Word":"parental
grandmother"},
{"Abbreviation":"PGF", "Word":"paternal
grandfather"},
{"Abbreviation":"MGM", "Word":"maternal
grandmother"},
{"Abbreviation":"MGF", "Word":"maternal
14. grandfather"},
{"Abbreviation":"GM", "Word":"Grandmother"},
{"Abbreviation":"GF", "Word":"Grandfather"},
{"Abbreviation":"5150", "Word":"72 hour hold for
assessment (5150)"},
{"Abbreviation":"5250", "Word":"14 days
maximum hold for treatment (5250)"},
{"Abbreviation":"COE", "Word":"County Office of
Education"},
{"Abbreviation":"CYC", "Word":"California Youth
Connection"},
{"Abbreviation":"DSS", "Word":"California
Department of Social Services"},
{"Abbreviation":"FYS", "Word":"Foster Youth
Services"},
{"Abbreviation":"CAC", "Word":"Children’s
Assessment Center"},
{"Abbreviation":"DOJ", "Word":"Department of
Justice"},
{"Abbreviation":"OHC", "Word":"Out of Home
Care"},
{"Abbreviation":"JD",
"Word":"Jurisdictional/Dispositional"},
{"Abbreviation":"SD", "Word":"Staff
Development"},
{"Abbreviation":"PC", "Word":"protective
capacity"},
{"Abbreviation":"MSLC", "Word":"minimum
sufficient level of care"},
{"Abbreviation":"RAM", "Word":"risk assessment
meeting"},
{"Abbreviation":"BS", "Word":"basic needs"},
{"Abbreviation":"FTT", "Word":"failure to
thrive"},
{"Abbreviation":"SA", "Word":"Safety
15. Assessment"},
{"Abbreviation":"RA", "Word":"Risk
Assessment"},
{"Abbreviation":"PIP", "Word":"Program
Improvement Plan"},
{"Abbreviation":"SIP", "Word":"System
Improvement Plan"},
{"Abbreviation":"SIDS", "Word":"sudden infant
death syndrome"},
{"Abbreviation":"SIS", "Word":"shaken infant
syndrome"},
{"Abbreviation":"IRB", "Word":"Institutional
review board"},
{"Abbreviation":"NASW", "Word":"National
Association of Social Workers"},
{"Abbreviation":"NAMI", "Word":"National
Alliance of Mentally Ill"},
{"Abbreviation":"MSW", "Word":"Master of Social
Work"},
{"Abbreviation":"BASW", "Word":"Bachelors of
Social Work"},
{"Abbreviation":"LCSW", "Word":"Licensed
Clinical Social Worker"},
{"Abbreviation":"CalSWEC", "Word":"California
Social Work Education Center"},
{"Abbreviation":"CSWE", "Word":"Counsel on
Social Work Education"},
{"Abbreviation":"FI", "Word":"field instructor"},
{"Abbreviation":"FL", "Word":"field liaison"},
{"Abbreviation":"Pro", "Word":"professor"},
{"Abbreviation":"MFT", "Word":"Marriage and
Family Therapist"},
{"Abbreviation":"SOSW", "Word":"School of
Social Work"},
{"Abbreviation":"SWSA", "Word":"Social Work
Student Association"},
16. {"Abbreviation":"PDEP", "Word":"Pathways
Distance Education Program"},
{"Abbreviation":"GIM", "Word":"Generalist
Intervention Model"},
{"Abbreviation":"EPAS", "Word":"Education
Policy and Accreditation Standards"},
{"Abbreviation":"LPA", "Word":"Learning Plan
Agreement"},
{"Abbreviation":"PR", "Word":"process
recordings"},
{"Abbreviation":"OH", "Word":"Office Hours"},
{"Abbreviation":"BPSS", "Word":"BPSS = bio-
psycho-social-spiritual"},
{"Abbreviation":"COETH", "Word":"code of
ethics"},
{"Abbreviation":"CV", "Word":"core values"},
{"Abbreviation":"NREFM", "Word":"non-related
extended family member"}
]
}
AndroidTextField.swift
//
// AndroidTextField.swift
// CaseAide
//
// Created by Alan Perez on 7/21/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
22. println("tap ended")
self.delegate?.assetErrorViewTapped(self)
}
}
}
AppDelegate.swift
//
// AppDelegate.swift
// CaseAide
//
// Created by Alan Perez on 7/14/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [NSObject:
AnyObject]?) -> Bool {
// Override point for customization after application
launch.
UIApplication.sharedApplication().statusBarStyle =
UIStatusBarStyle.LightContent
23. // R:74, G:144, B:226
UINavigationBar.appearance().barTintColor =
UIColor.caseAideBlue()
UINavigationBar.appearance().tintColor =
UIColor.whiteColor()
UINavigationBar.appearance().titleTextAttributes =
[NSForegroundColorAttributeName: UIColor.whiteColor()]
UIPageControl.appearance().pageIndicatorTintColor =
UIColor.lightGrayColor()
UIPageControl.appearance().currentPageIndicatorTintColor =
UIColor.blackColor()
UIPageControl.appearance().backgroundColor =
UIColor.whiteColor()
UITabBar.appearance().tintColor =
UIColor.caseAideBlue()
return true
}
func applicationWillResignActive(application:
UIApplication) {
// 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,
and throttle down OpenGL ES frame rates. Games should use
this method to pause the game.
}
24. func applicationDidEnterBackground(application:
UIApplication) {
// Use this method to release shared resources, save user
data, invalidate timers, and store enough application state
information to restore your application to its current state in
case it is terminated later.
// If your application supports background execution, this
method is called instead of applicationWillTerminate: when the
user quits.
}
func applicationWillEnterForeground(application:
UIApplication) {
// Called as part of the transition from the background to
the inactive state; here you can undo many of the changes made
on entering the background.
}
func applicationDidBecomeActive(application:
UIApplication) {
// 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 applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save
data if appropriate. See also applicationDidEnterBackground:.
}
}
25. AssetHeaderView.swift
//
// AssetHeaderView.swift
// CaseAide
//
// Created by Alan Perez on 8/12/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
class AssetHeaderView: UICollectionReusableView {
@IBOutlet weak var titleLabel: UILabel!
}
AssetLoadingView.swift
//
// AssetLoadingView.swift
26. // CaseAide
//
// Created by Alan Perez on 8/12/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
class AssetLoadingView: UIView {
@IBOutlet weak var activityIndicator:
UIActivityIndicatorView!
override func awakeFromNib()
{
super.awakeFromNib()
self.accessibilityViewIsModal = true
}
28. // Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
class AssetView: UIView {
@IBOutlet weak var dayLabel: UILabel!
@IBOutlet weak var dateLabel: UILabel!
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance
during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
29. BasicCell.swift
//
// BasicReportCell.swift
// CaseAide
//
// Created by Alan Perez on 8/19/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
class BasicCell: UITableViewCell
{
@IBOutlet weak var fieldLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
override func layoutSubviews()
31. class BlobCell: UITableViewCell
{
@IBOutlet weak var fieldLabel: UILabel!
@IBOutlet weak var valueLabel: UILabel!
override func layoutSubviews()
{
super.layoutSubviews()
self.contentView.layoutIfNeeded()
self.valueLabel.preferredMaxLayoutWidth =
CGRectGetWidth(self.valueLabel.frame)
}
}
CAAddClientInfo.swift
//
// CAAddClientInfo.swift
32. // CaseAide
//
// Created by Andrew on 9/27/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
import UIKit
class CAAddClientInfo: UIViewController ,
UITextFieldDelegate {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var phoneNumberTextField:
AndroidTextField!
@IBOutlet weak var EmailTextField: AndroidTextField!
@IBOutlet weak var addressTextField: AndroidTextField!
@IBOutlet weak var submitButton: UIButton!
//SEEDED CLIENT
var client: CAClient?
private var emailToAdd: CAEmail?
private var phoneNumberToAdd: CAPhoneNumber?
private var addressToAdd: CAAddress?
private var keyboardShown: Bool = false
private var keyboardRectWRTView = CGRectZero
private var preKeyboardContentOffset = CGPointZero
private let api: CAApi = CAApi.defaultApi
37. println(address)
saveAddress()
}
func createPhoneNumber(){
var phoneNumber = phoneNumberTextField.text
var phoneID = self.client?.phoneNumbers.last?.id ?? 1
self.phoneNumberToAdd = CAPhoneNumber(id: phoneID,
phonenumber: phoneNumber)
if count(phoneNumber) == 10{
if checkNumber(phoneNumber) {
phoneNumber =
convertToPhoneNumberStandard(phoneNumber)
self.phoneNumberToAdd?.number = phoneNumber
println(phoneNumber)
savePhoneNumber()
println("Is a valid integer")
}
else
{
phoneNumberInputError()
println("Is not a valid integer")
}
}
}
func convertToPhoneNumberStandard(phoneNumber:
String!) -> String{
38. var number = "("
number += indexing(phoneNumber, beginingIndex: 0,
endingIndex: -7)
number += ") "
number += indexing(phoneNumber, beginingIndex: 3,
endingIndex: -4)
number += "-"
number += indexing(phoneNumber, beginingIndex: 6,
endingIndex: 0)
return number
}
//A way to index strings without using integer notation
func indexing(string: String, beginingIndex: Int,
endingIndex: Int) ->String{
var stringToReturn: String
var index = advance(string.startIndex, beginingIndex)
string[index]
var endIndex = advance(string.endIndex, endingIndex)
stringToReturn = string[Range(start: index, end:
endIndex)]
return stringToReturn
}
func checkNumber(string: String) -> Bool {
//return true if both the incoming string is a number
var confirmedStringIsANumber = ""
for char in string {
let i = "(char)"
if let checkInteger = i.toInt()
{
confirmedStringIsANumber += i
}
40. shiftUpIfNeeded(textField)
}
}
func keyboardWillShow(notification: NSNotification)
{
let window =
UIApplication.sharedApplication().keyWindow!
let keyboardInfo = notification.userInfo!
// keyboard frame with respect to screen
let keyboardRectWRTScreen =
keyboardInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValu
e()
// set parameters and shift for first textfield focus
self.keyboardRectWRTView =
self.view.convertRect(keyboardRectWRTScreen, fromView: nil)
self.keyboardShown = true
self.preKeyboardContentOffset =
self.scrollView.contentOffset
if self.phoneNumberTextField.isFirstResponder()
{
self.shiftUpIfNeeded(self.phoneNumberTextField)
}
else if self.EmailTextField.isFirstResponder()
{
self.shiftUpIfNeeded(self.EmailTextField)
}
else if self.addressTextField.isFirstResponder()
{
self.shiftUpIfNeeded(self.addressTextField)
}
41. }
func keyboardWillHide(notification: NSNotification)
{
keyboardShown = false
shiftBack()
}
func shiftUpIfNeeded(textField: UITextField)
{
let textFieldRectWRTView =
self.view.convertRect(textField.bounds, fromView: textField)
// if user text field is hidden by keyboard
if CGRectIntersectsRect(self.keyboardRectWRTView,
textFieldRectWRTView)
{
let overlapAmount =
CGRectGetMaxY(textFieldRectWRTView) -
CGRectGetMinY(self.keyboardRectWRTView) + 10
let contentOffset = scrollView.contentOffset
scrollView.setContentOffset(CGPointMake(contentOffset.x,
contentOffset.y + overlapAmount), animated: true)
}
}
func shiftBack()
{
scrollView.setContentOffset(self.preKeyboardContentOffset,
animated: true)
}
func savePhoneNumber(){
42. if let validClient = self.client
{
self.api.createPhone(validClient.id, phone:
self.phoneNumberToAdd!, completitionHandler: { (error) ->
Void in
if let updateError = error
{
Functions.alertError(updateError)
}else{
self.view.makeToast(message: "Client Information
Saved")
}
})
}
}
func saveEmail(){
if let validClient = self.client{
self.api.createEmail(validClient.id, email:
emailToAdd!, completitionHandler: { (error) -> Void in
if let updateError = error
{
Functions.alertError(updateError)
}else{
self.view.makeToast(message: "Client Information
Saved")
}
})
}
43. }
func saveAddress(){
if let validClient = self.client{
self.api.createAddress(validClient.id, address:
addressToAdd!, completitionHandler: { (error) -> Void in
if let updateError = error
{
Functions.alertError(updateError)
}else{
self.view.makeToast(message: "Client Information
Saved")
}
})
}
}
func customizeView(){
submitButton.backgroundColor = UIColor.caseAideBlue()
var greyColor = UIColor(red: 195/255, green: 195/255,
blue: 195/255, alpha: 1)
phoneNumberTextField.addBottomBorderWithColor(greyColor,
borderWidth: 1)
phoneNumberTextField.borderColor = greyColor.CGColor
EmailTextField.addBottomBorderWithColor(greyColor,
borderWidth: 1)
EmailTextField.borderColor = greyColor.CGColor
addressTextField.addBottomBorderWithColor(greyColor,
borderWidth: 1)
addressTextField.borderColor = greyColor.CGColor
}
func phoneNumberInputError(){
Functions.alert("Invalid Input", message: "Please enter a
valid 10 digit phonenumber.")
44. }
}
CAApi.swift
//
// TestApi.swift
// CaseAide
//
// Created by Alan Perez on 9/8/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
import Foundation
class CAApi
{
// shared instance of API
static let defaultApi = CAApi()
private var afHttpManager: Manager
private var authKey: String? // can only be set by
authenticating
private var baseUrl: NSURL
// error handling
private let caseaideDomain = "org.caseaide.error"
private let userNotLoggedInErrorCode = 1
private let operationUnsuccessfulErrorCode = 2
private let authenticationErrorCode = 3
init()
{
self.baseUrl = NSURL(string: "https://139.182.74.19/v2-
2")!
self.afHttpManager = Manager.sharedInstance // alamofire
45. manager singleton
// TODO: remove this when it is no longer needed for
security reasons
// ignore security warnings for server
let serverTrustPolicies: [String: ServerTrustPolicy] = [
"139.182.74.19": .DisableEvaluation
]
self.afHttpManager.session.serverTrustPolicyManager =
ServerTrustPolicyManager(policies: serverTrustPolicies)
}
// MARK: Generic API methods
func authenticate(user: String, pass: String,
completionHandler: (NSError?) -> Void)
{
let loginUrl =
self.baseUrl.URLByAppendingPathComponent("/login")
self.afHttpManager.request(.POST, loginUrl, parameters:
["username": user, "password": pass.md5()], encoding: .JSON,
headers: nil).responseJSON { _, _, JSON, error in
let status = self.validateAuthenticationSuccess(JSON,
error: error)
if let key = status.0
{
self.authKey = key // set authentication key
}
completionHandler(status.1)
}
46. }
func create<T: Mappable>(path: String, asset: T,
completionHandler: (NSError?) -> Void)
{
self.validateUserLogin({ key in
let createPath = "/(key)/(path)"
let createUrl =
self.baseUrl.URLByAppendingPathComponent(createPath)
let data = Mapper().toJSON(asset)
self.afHttpManager.request(.POST, createUrl,
parameters: data, encoding: .JSON, headers: nil).responseJSON
{ _, _, JSON, error in
println(JSON)
completionHandler(self.validateOperationSuccess(JSON, error:
error))
}
}, errorBlock: { error in
completionHandler(error)
})
}
func read<T: Mappable>(path: String, completionHandler:
(T?, NSError?) -> Void)
{
47. self.validateUserLogin({ key in
let readPath = "/(key)/(path)"
let readUrl =
self.baseUrl.URLByAppendingPathComponent(readPath)
self.afHttpManager.request(.GET, readUrl, parameters:
nil, encoding: .JSON, headers: nil).responseObject { (obj: T?,
error: NSError?) -> Void in
completionHandler(obj, error)
}
}, errorBlock: { error in
completionHandler(nil, error)
})
}
func readAll<T: Mappable>(path: String, completionHandler:
([T]?, NSError?) -> Void)
{
self.validateUserLogin({ key in
let readAllPath = "/(key)/(path)"
let readAllUrl =
self.baseUrl.URLByAppendingPathComponent(readAllPath)
self.afHttpManager.request(.GET, readAllUrl,
parameters: nil, encoding: .JSON, headers: nil).responseArray {
(objects: [T]?, error: NSError?) -> Void in
println(objects)
completionHandler(objects, error)
48. }
}, errorBlock: { error in
completionHandler(nil, error)
})
}
func update<T: Mappable>(path: String, asset: T,
completionHandler: (NSError?) -> Void)
{
self.validateUserLogin({ key in
let updatePath = "/(key)/(path)"
let updateUrl =
self.baseUrl.URLByAppendingPathComponent(updatePath)
let data = Mapper().toJSON(asset)
self.afHttpManager.request(.PUT, updateUrl,
parameters: data, encoding: .JSON, headers: nil).responseJSON
{ _, _, JSON, error in
println(JSON)
completionHandler(self.validateOperationSuccess(JSON, error:
error))
}
}, errorBlock: { error in
completionHandler(error)
49. })
}
func delete(path: String, completionHandler: (NSError?) ->
Void)
{
self.validateUserLogin({ key in
let deletePath = "/(key)/(path)"
let deleteUrl =
self.baseUrl.URLByAppendingPathComponent(deletePath)
self.afHttpManager.request(.DELETE,
deleteUrl).responseJSON { _, _, JSON, error in
completionHandler(self.validateOperationSuccess(JSON, error:
error))
}
}, errorBlock: { error in
completionHandler(error)
})
}
// MARK: Contact API methods
func createContact(clientId: Int, contact: CAContact,
completionHandler: (NSError?) -> Void)
{
let path = "clients/(clientId)/contacts"
self.create(path, asset: contact, completionHandler:
completionHandler)
}
56. {
// if error occurred override error to be more specific
let userInfo = [NSLocalizedDescriptionKey:
"Authentication error.", NSLocalizedFailureReasonErrorKey:
"Username or password is incorrect",
NSLocalizedRecoverySuggestionErrorKey: "Type in correct
username and password"]
let authenticationError = NSError(domain:
self.caseaideDomain, code: self.authenticationErrorCode,
userInfo: userInfo)
return (nil, authenticationError)
}
}
}
private func validateOperationSuccess(response: AnyObject?,
error: NSError?) -> NSError?
{
if let err = error
{
return err
}
else
{
if self.getJsonResponseValue(response, key:
"response") == "success"
{
return nil
}
else
{
// create error
let userInfo = [NSLocalizedDescriptionKey:
"Operation was unsuccessful.",
57. NSLocalizedFailureReasonErrorKey: "Unable to perform
operation", NSLocalizedRecoverySuggestionErrorKey: "Try
again later"]
let operationError = NSError(domain:
self.caseaideDomain, code:
self.operationUnsuccessfulErrorCode, userInfo: userInfo)
return operationError
}
}
}
//----------------------------------------------------------
func readFromJson() -> [String : String] {
var dictionary = [String : String]()
let url = "AbbrWordDict"
if let path = NSBundle.mainBundle().pathForResource(url,
ofType: "json")
{
if let jsonData = NSData(contentsOfFile: path, options:
.DataReadingMappedIfSafe, error: nil)
{
if let jsonResult: NSDictionary =
NSJSONSerialization.JSONObjectWithData(jsonData, options:
NSJSONReadingOptions.MutableContainers, error: nil) as?
NSDictionary
{
if let jsonArray = jsonResult["Dictionary"] as?
NSArray
{
for item in jsonArray {
if let abbreviation: AnyObject =
item["Abbreviation"]! {
58. if let word: AnyObject = item["Word"]!{
dictionary.updateValue(word as!
String, forKey: abbreviation as! String)
}
}
}
}
}
}
}
return dictionary
}
}
CABlobPageController.swift
//
// CABlobPageController.swift
// CaseAide
//
// Created by Alan Perez on 8/22/15.
// Copyright (c) 2015 CSUSB Mobile apps. All rights reserved.
//
import UIKit
class CABlobPageController: CAPageController,
UITextViewDelegate
{
// configuration by caller
var text: String?
@IBOutlet weak var fieldLabel: UILabel!
@IBOutlet weak var clientNameLabel: UILabel!
59. @IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewTopConstraint:
NSLayoutConstraint!
@IBOutlet weak var textViewBottomConstraint:
NSLayoutConstraint!
private lazy var endEditingButton: UIBarButtonItem =
self.createFinishEditingButton()
// need to save original distance from top of textview to top
relational view
private var textViewTopOffset: CGFloat!
// store buttons that were located in navbar before showing
end editing button
private var rightNavbarButtonsState: [AnyObject]?
private var rightNavbarButtonState: UIBarButtonItem?
override func viewDidLoad()
{
super.viewDidLoad()
self.clientNameLabel.text = self.clientName
self.fieldLabel.text = self.fieldType
// fix short type cursor jumping bug
self.textView.layoutManager.allowsNonContiguousLayout
= false
self.textView.text = self.text ?? ""
self.textView.delegate = self
self.textView.textContainerInset = UIEdgeInsetsMake(15,
10, 15, 10)
60. // store textview original offset, in order to shift back to
original position, when keyboard is hidden
self.textViewTopOffset =
self.textViewTopConstraint.constant
}
override func viewWillDisappear(animated: Bool)
{
self.dismissKeyboard()
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self,
name: UIKeyboardWillHideNotification, object: nil)
}
override func viewWillAppear(animated: Bool)
{
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("keyboardWillShow:"), name:
UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self,
selector: Selector("keyboardWillHide:"), name:
UIKeyboardWillHideNotification, object: nil)
if(textView.text == "")
{
self.showPlaceholder()
}
}
func dismissKeyboard()
{
61. self.view.endEditing(true)
}
func keyboardWillShow(notification: NSNotification)
{
let window =
UIApplication.sharedApplication().keyWindow!
let keyboardInfo = notification.userInfo!
// keyboard frame with respect to screen
let keyboardRectWRTScreen =
keyboardInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValu
e()
let keyboardRectWRTView =
self.view.convertRect(keyboardRectWRTScreen, fromView: nil)
self.moveTextViewAwayFromKeyboard(keyboardRectWRTVie
w.origin.y)
}
func keyboardWillHide(notification: NSNotification)
{
self.moveTextViewBack()
}
func textViewDidChange(textView: UITextView)
{
self.delegate?.didEditPage(self)
}
func getText() -> String
{
return self.textView.text
}
63. }
func removePlaceholder()
{
self.textView.text = ""
self.textView.textColor = UIColor.blackColor()
}
// MARK: textview shifting logic
func createFinishEditingButton() -> UIBarButtonItem
{
return UIBarButtonItem(title: "Done", style:
UIBarButtonItemStyle.Done, target: self, action:
"dismissKeyboard")
}
func moveTextViewAwayFromKeyboard(keyboardMinY:
CGFloat)
{
self.storeNavbarButtonState()
self.navDelegate?.setRightNavbarItem(self.endEditingButton)
// The textview is not at bottom of parent view, so we only
want to move the textview by the offset necessary to clear the
keyboard
let bottomOffset = CGRectGetMaxY(self.textView.frame)
- keyboardMinY
self.textViewTopConstraint.constant = 0
self.textViewBottomConstraint.constant = bottomOffset
}
func moveTextViewBack()
{
self.restoreNavbarButtonState()
64. self.textViewTopConstraint.constant =
self.textViewTopOffset
self.textViewBottomConstraint.constant = 0
}
func storeNavbarButtonState()
{
self.rightNavbarButtonState =
self.navDelegate?.getRightNavbarItem()
self.rightNavbarButtonsState =
self.navDelegate?.getRightNavbarItems()
}
func restoreNavbarButtonState()
{
self.navDelegate?.setRightNavbarItem(self.rightNavbarButtonSt
ate)
self.navDelegate?.setRightNavbarItems(self.rightNavbarButtons
State)
}
// MARK: Short type
func textView(textView: UITextView,
shouldChangeTextInRange range: NSRange, replacementText
text: String) -> Bool
{
let textViewText = textView.text
let inputedText = text
let inputedTextLength = count(text)
let inputStartIndex = advance(textViewText.startIndex,
range.location)
let inputEndIndex = advance(inputStartIndex,
65. range.length)
let inputTextRange = Range<String.Index>(start:
inputStartIndex, end: inputEndIndex)
let isTypingCharacter = inputedTextLength == 1 // user is
typing character (could be replacing exiting text or not)
let isTypingMultipleWords =
inputedText.numberOfWords() > 1 // user is typing many words
at once (caused by paste or speech to text; could be replacing
exiting text or not)
// check if user typed in word seperating character
if isTypingCharacter && inputedText.hasWordSeperator()
{
// meant to capture words as they are entered character
by character
// check last word before seperator for abbreviations
let wordCheckRange = Range<String.Index>(start:
textViewText.startIndex, end: inputStartIndex)
let lastWordSubstring =
textViewText.lastWordSubstringInRange(wordCheckRange)
let lastWord = lastWordSubstring.word
let lastWordRange = lastWordSubstring.range
var mappedLastWord =
CAShortType.mapToWords(lastWord)
if mappedLastWord != lastWord
{
mappedLastWord = mappedLastWord + inputedText
//add word seperator to mapped word
66. // replace abbreviated words to their respective words
textView.text.replaceRange(lastWordRange, with:
mappedLastWord)
let mappingWordOffset = count(mappedLastWord) -
count(lastWord)
let pointerLocation = range.location +
mappingWordOffset // textLength is for new seperator entered
textView.selectedRange =
NSMakeRange(pointerLocation, 0)
return false
}
}
else if isTypingMultipleWords // meant to capture words
as they are inputed in bunches such as copy and paste and
speech to text
{
// user inserting new string or replacing range with
string
let mappedText =
CAShortType.mapToWords(inputedText)
if mappedText != inputedText
{
textView.text.replaceRange(inputTextRange, with:
mappedText)
let pointerLocation = range.location +
count(mappedText)
textView.selectedRange =
NSMakeRange(pointerLocation, 0)
return false
}
67. }
return true
}
}
CACheckboxPageController.swift
//
// CACheckboxPageController.swift
// CaseAide
//
// Created by Alan Perez on 8/22/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import UIKit
class CACheckboxPageController: CAPageController,
UITableViewDataSource, UITableViewDelegate
{
var options: [String]?
var selectedIndicies: [Int]?
// Internal parameters
private var selectedOptions: [Int]!
let optionCellReuseIdentifier = "optionCellReuseIdentifier"
let optionCellHeight: CGFloat = 60.0
@IBOutlet weak var fieldLabel: UILabel!
@IBOutlet weak var clientNameLabel: UILabel!
68. @IBOutlet weak var tableView: UITableView!
override func viewDidLoad()
{
super.viewDidLoad()
// ensure controller has selections have valid state
if let selOpt = self.selectedIndicies
{
self.selectedOptions = selOpt
}
else
{
self.selectedOptions = [Int]()
}
self.clientNameLabel.text = self.clientName
self.fieldLabel.text = self.fieldType
self.tableView.dataSource = self
self.tableView.delegate = self
}
// MARK: Table view data source methods
func numberOfSectionsInTableView(tableView:
UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int
{
return options?.count ?? 0
}
69. func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) ->
UITableViewCell
{
let cell =
tableView.dequeueReusableCellWithIdentifier(self.optionCellR
euseIdentifier, forIndexPath: indexPath) as! CheckboxCell
cell.optionLabel.text = self.options?[indexPath.row]
// if cell index is in selectedindexes
if self.isSelectedIndex(indexPath.row).0
{
cell.accessoryType =
UITableViewCellAccessoryType.Checkmark
}
else
{
cell.accessoryType =
UITableViewCellAccessoryType.None
}
return cell
}
func tableView(tableView: UITableView,
didSelectRowAtIndexPath indexPath: NSIndexPath)
{
let cellIndex = indexPath.row
let (isSelected, selIndex) = self.isSelectedIndex(cellIndex)
if isSelected
{
self.selectedOptions.removeAtIndex(selIndex!)
}
70. else
{
self.selectedOptions.append(cellIndex)
}
tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow:
cellIndex, inSection: 0)], withRowAnimation:
UITableViewRowAnimation.Automatic)
self.delegate?.didEditPage(self)
}
func isSelectedIndex(index: Int) -> (Bool, Int?)
{
if let i = find(self.selectedOptions, index)
{
return (true, i)
}
return (false, nil)
}
func getSelectedIndicies() -> [Int]
{
return self.selectedOptions
}
@IBAction func informationButton(sender: UIButton) {
//description of the view
let discriptionText = Functions.message(fieldLabel.text!)
//Custom box for the view
Functions.discriptionBox(fieldLabel.text!, message:
discriptionText)
}
71. }
CAClient.swift
//
// CAClient.swift
// CaseAide
//
// Created by Alan Perez on 8/5/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
import Foundation
class CAClient: Mappable
{
var id: Int
var name: String
var addresses: [CAAddress]
72. var emails: [CAEmail]
var phoneNumbers: [CAPhoneNumber]
var hearing: CAHearing?
var seen: Bool
var daysUntilHearing: Int
var reports: [CAReport]
var contacts: [CAContact]
init(id: Int, name: String)
{
self.id = id
self.name = name
self.seen = false
self.addresses = [CAAddress]()
self.phoneNumbers = [CAPhoneNumber]()
self.emails = [CAEmail]()
self.reports = [CAReport]()
74. self.addresses <- map["addresses"]
self.emails <- map["emails"]
self.phoneNumbers <- map["phones"]
self.seen <- map["seen"]
self.hearing <- map["hearing"]
self.contacts <- map["contacts"]
self.reports <- map["reports"]
self.daysUntilHearing <- map["daysUntilHearing"]
}
}
CAContact.swift
//
// CAContact.swift
// CaseAide
//
// Created by Alan Perez on 8/5/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
75. import Foundation
class CAContact: Mappable, Equatable
{
var id: Int
var startDate: NSDate
var endDate: NSDate
var staff: String
var personsIncluded: [String]
var inSupportOf: [String]
var note: String
private var _objective: Int
private var _approach: Int
private var _place: Int
private var _outcome: Int
76. static let objectiveOptions = ["Conduct Client Evaluation",
"Consult with Attorney", "Consult with Collateral", "Consult
Service Provider"]
static let approachOptions = ["Email", "Fax", "In Person",
"Telephone", "Written"]
static let placeOptions = ["Court", "CWS Office", "Home",
"In Placement", "School", "Other"]
static let outcomeOptions = ["Attempted", "Completed",
"Scheduled"]
var objective: String {
get {
return CAContact.objectiveOptions[self._objective]
}
set {
self._objective = find(CAContact.objectiveOptions,
newValue) ?? 0
}
}
var approach: String {
get {
77. return CAContact.approachOptions[self._approach]
}
set {
self._approach = find(CAContact.approachOptions,
newValue) ?? 0
}
}
var place: String {
get {
return CAContact.placeOptions[self._place]
}
set {
self._place = find(CAContact.placeOptions, newValue)
?? 0
}
}
var outcome: String {
get {
return CAContact.outcomeOptions[self._outcome]
85. CAEmail.swift
//
// CAEmail.swift
// CaseAide
//
// Created by Alan Perez on 9/10/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import Foundation
class CAEmail: Mappable
{
var id: Int
var address: String
init(id: Int, address: String)
{
self.id = id
self.address = address
}
convenience init(id: Int)
{
self.init(id: id , address: "N/A")
}
static func newInstance(map: Map) -> Mappable?
{
return CAEmail(id: -1)
}
func mapping(map: Map)
{
self.id <- (map["id"],CAIntTransform())
self.address <- map["email"]
86. }
}
CAHearing.swift
//
// CAHearing.swift
// CaseAide
//
// Created by Alan Perez on 8/5/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
import Foundation
enum CAHearingType: String
{
case SixMonthReview = "366.21 E, Six Month Review"
case TwelveMonthReview = "366.21 F, Twelve Month
Review"
case EighteenMonthReview = "366.22, Eighteen Month
Review"
87. case SelectionAndImplementation = "366.26, Selection and
Implementation"
case PostPermPlanReview = "366.3, Post Perm Plan Review"
case FamilyMaintenanceReview = "364, Family Maintenance
Review"
case DualStatus = "241.1, Dual Status"
}
class CAHearing: Mappable, Equatable
{
var id: Int
var date: NSDate
var type: CAHearingType
// readonly deadlines computed by server
private(set) var cprDueDate: NSDate?
private(set) var supervisorDueDate: NSDate?
private(set) var courtDueDate: NSDate?
92. if self.numberOfPages() > 0
{
let startControllers =
[self.viewControllerAtIndex(self.currentPage)!]
self.pageViewController.setViewControllers(startControllers,
direction: UIPageViewControllerNavigationDirection.Forward,
animated: true, completion: nil)
self.pageViewController.view.frame = self.view.bounds
self.addChildViewController(self.pageViewController)
self.view.addSubview(self.pageViewController.view)
self.pageViewController.didMoveToParentViewController(self)
}
}
// MARK: Override methods for children
func prepareForm()
{
println("prepareForm(): override this method to prepare
data used in form")
}
func didEditPage(pageController: CAPageController)
{
println("didEditPage(): override this method to register for
page changes")
}
func setRightNavbarItems(items: [AnyObject]?)
{
self.navigationItem.rightBarButtonItems = items
93. }
func setRightNavbarItem(item: UIBarButtonItem?)
{
self.navigationItem.rightBarButtonItem = item
}
func getRightNavbarItems() -> [AnyObject]?
{
return self.navigationItem.rightBarButtonItems
}
func getRightNavbarItem() -> UIBarButtonItem?
{
return self.navigationItem.rightBarButtonItem
}
func startPageIndex() -> Int
{
println("startPageIndex(): override this method for setting
the initial page loaded")
return 0
}
func numberOfPages() -> Int
{
println("numberOfPages(): override this method for setting
the number of pages")
return 0
}
func pageControllerForIndex(index: Int) ->
CAPageController?
{
println("pageControllerForIndex(): override this method to
pass in page at index")
94. return nil
}
func save()
{
println("save(): override this method for consistent saving
across all forms")
println("Save form")
}
// MARK: Page view controller data source methods
final func pageViewController(pageViewController:
UIPageViewController, viewControllerBeforeViewController
viewController: UIViewController) -> UIViewController?
{
if let index = (viewController as!
CAPageController).pageNumber
{
return self.viewControllerAtIndex(index - 1)
}
return nil
}
final func pageViewController(pageViewController:
UIPageViewController, viewControllerAfterViewController
viewController: UIViewController) -> UIViewController?
{
if let index = (viewController as?
CAPageController)?.pageNumber
{
return self.viewControllerAtIndex(index + 1)
}
return nil
95. }
final func pageViewController(pageViewController:
UIPageViewController, didFinishAnimating finished: Bool,
previousViewControllers: [AnyObject], transitionCompleted
completed: Bool)
{
// whenever new page is loaded, set current page and
register for notifications to changes in page
let currentPageController =
pageViewController.viewControllers.last as! CAPageController
self.currentPage = currentPageController.pageNumber!
}
// page control indicator methods
final func
presentationCountForPageViewController(pageViewController:
UIPageViewController) -> Int
{
return self.numberOfPages()
}
final func
presentationIndexForPageViewController(pageViewController:
UIPageViewController) -> Int
{
return self.currentPage
}
// MARK: Helper methods
final func viewControllerAtIndex(index: Int) ->
UIViewController?
{
if index >= self.numberOfPages() || index < 0
{
96. return nil
}
var controller = self.pageControllerForIndex(index)
controller?.pageNumber = index
controller?.delegate = self
controller?.navDelegate = self
return controller
}
func currentPageController() -> CAPageController?
{
return self.pageViewController.viewControllers[0] as?
CAPageController
}
func cancelAction()
{
println("cancelAction: Override this method to provide a
custom implementation when user presses cancel")
}
}
CAMapperTransforms.swift
//
// CAApiManager.swift
// CaseAide
//
97. // Created by Alan Perez on 8/5/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import Foundation
public class CADateTransform: TransformType {
public typealias Object = NSDate
public typealias JSON = String
let dateFormat = "yyyy-MM-dd HH:mm:ss"
let dateFormatter = NSDateFormatter()
public init() {
self.dateFormatter.dateFormat = self.dateFormat
}
public func transformFromJSON(value: AnyObject?) ->
NSDate? {
98. if let timeString = value as? String {
return self.dateFormatter.dateFromString(timeString)
}
return nil
}
public func transformToJSON(value: NSDate?) -> JSON? {
if let date = value {
return self.dateFormatter.stringFromDate(date)
}
return nil
}
}
public class CAArrayTransform: TransformType {
public typealias Object = [String]
public typealias JSON = String
99. let seperator = "$"
public init() {}
public func transformFromJSON(value: AnyObject?) ->
[String]? {
if let string = value as? String {
return string.componentsSeparatedByString(seperator)
}
return nil
}
public func transformToJSON(value: [String]?) -> JSON? {
if let v = value {
return seperator.join(v)
}
return nil
}
100. }
public class CAIntTransform: TransformType {
public typealias Object = Int
public typealias JSON = String
public init() {}
public func transformFromJSON(value: AnyObject?) ->
Object? {
if let value = (value as? String)?.toInt() {
return value
}
return nil
}
public func transformToJSON(value: Int?) ->
JSON? {
if let v = value {
101. return "(v)"
}
return nil
}
}
CAPhoneNumber.swift
//
// CAPhoneNumber.swift
// CaseAide
//
// Created by Alan Perez on 9/10/15.
// Copyright (c) 2015 Alan Perez. All rights reserved.
//
import Foundation
class CAPhoneNumber: Mappable
{
var id: Int
var number: String
init(id: Int, phonenumber: String)
{
self.id = id
self.number = phonenumber
}
103. self.id <- (map["id"], CAIntTransform())
self.address <- map["address"]
}
}
CAPageController.swift
//
// CAPageController.swift
// CaseAide
//
// Created by Alan Perez on 8/22/15.
// Copyright (c) 2015 CSUSB Mobile apps. All rights reserved.
//
import UIKit
protocol CAPageControllerDelegate
{
func didEditPage(pageController: CAPageController)
}
104. protocol CAPageControllerNavbarDelegate
{
func setRightNavbarItems(items: [AnyObject]?)
func setRightNavbarItem(item: UIBarButtonItem?)
func getRightNavbarItems() -> [AnyObject]?
func getRightNavbarItem() -> UIBarButtonItem?
}
class CAPageController: UIViewController
{
var pageNumber: Int?
var clientName: String?
var fieldType: String?
var delegate: CAPageControllerDelegate?
var navDelegate: CAPageControllerNavbarDelegate?
func endEditing()
105. {
println("endEditing(): override me for form to be able to
end editing for a specific page")
}
}
CARadioPageController.swift
//
// CARadioPageController.swift
// CaseAide
//
// Created by Alan Perez on 8/22/15.
// Copyright (c) 2015 CSUSB Mobile apps. All rights reserved.
//
import UIKit
class CARadioPageController: CAPageController,
UITableViewDataSource, UITableViewDelegate
{
let radioCellReuseIdentifier = "radioCellReuseIdentifier"
let optionsPrefixHeaderCellReuseIdentifier =
"optionsPrefixHeaderCellReuseIdentifier"
let selectedRadioImg = UIImage(named: "radio_selected")
let unselectedRadioImg = UIImage(named:
"radio_unselected")
var optionsPrefix: String?
106. @IBOutlet weak var fieldLabel: UILabel!
@IBOutlet weak var clientNameLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let radioCellHeight: CGFloat = 50.0
let optionsPrefixHeaderHeight: CGFloat = 40.0
var options: [String]?
var selectedIndex: Int?
private var selectedOption: Int = 0
override func viewDidLoad()
{
super.viewDidLoad()
// ensure that selected index is set
if let selIndex = self.selectedIndex
{
self.selectedOption = selIndex
}
self.clientNameLabel.text = self.clientName
self.fieldLabel.text = self.fieldType
self.tableView.dataSource = self
self.tableView.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
109. let prevIndexPath = NSIndexPath(forRow: prevSelected,
inSection: 0)
let currIndexPath = NSIndexPath(forRow:
self.selectedOption, inSection: 0)
self.tableView.reloadRowsAtIndexPaths([prevIndexPath,
currIndexPath], withRowAnimation:
UITableViewRowAnimation.Automatic)
self.delegate?.didEditPage(self)
}
func getSelectedOptionIndex() -> Int
{
return self.selectedOption
}
@IBAction func informationButton(sender: UIButton) {
//description of the view
let discriptionText = Functions.message(fieldLabel.text!)
//Custom box for the view
Functions.discriptionBox(fieldLabel.text!, message:
discriptionText)
}
}
CAReport.swift
//
// Models.swift
110. // CaseAide
//
// Created by Alan Perez on 8/4/15.
// Copyright (c) 2015 CaseAide. All rights reserved.
//
import Foundation
struct CAField: Equatable
{
var name: String
var value: String
}
func ==(lhs: CAField, rhs: CAField) -> Bool
{
return lhs.name == rhs.name && lhs.value == rhs.value
}
111. enum CAReportType: String
{
case Generic = "Generic"
case StatusReview = "366.3, Status Review"
case ExParte = "Ex Parte"
}
enum CAReportTemplate
{
case StatusReview
case ExParte
case Generic
var type: CAReportType {
switch self
{
112. case .StatusReview:
return CAReportType.StatusReview
case .ExParte:
return CAReportType.ExParte
case .Generic:
return CAReportType.Generic
}
}
var fields: [CAField] {
switch self
{
case .StatusReview:
return [CAField(name: "Summary Recommendation",
value: ""),
CAField(name: "Child Whereabouts", value: ""),
CAField(name: "Indian Child Welfare Status", value:
""),
CAField(name: "Search Results", value: ""),
114. CAField(name: "Recommendation", value: "")]
default:
return [CAField]()
}
}
// Status Review fields
static let SUMMARY_REC_INDEX = 0
static let CHILD_WHEREABOUTS_INDEX = 1
static let ICWA_STATUS_INDEX = 2
static let SEARCH_RESULTS_INDEX = 3
static let HEARING_REASON_INDEX = 4
static let LEGAL_RELATIONSHIPS_INDEX = 5
static let FAMILY_LAW_STATUS_INDEX = 6
static let FAMILY_ASSESMENT_UPDATE_INDEX = 7
static let CHILD_EVAL_INDEX = 8
static let OUT_OF_HOME_PLACEMENT_INDEX = 9
115. static let PLACEMENT_HISTORY_INDEX = 10
static let SERVICES_PROVIDED_INDEX = 11
static let VISITATION_INDEX = 12
static let CONTACTS_INDEX = 13
static let FAMILY_PERCEPTION_OF_NEEDS_INDEX = 14
// Exparte fields
static private let REASON_FOR_APPL_INDEX = 0
static private let NOTICES_INDEX = 1
static private let REASON_FOR_REC_INDEX = 2
static private let RECOMMENDATION_INDEX = 3
}
class CAReport: Mappable, Equatable
{
var id: Int
var date: NSDate
116. var court: String
var room: String
var children: [String]
private(set) var type: CAReportType
private(set) var fields: [CAField]
init (report: CAReport)
{
self.id = report.id
self.date = report.date
self.court = report.court
self.room = report.room
self.children = report.children
self.type = report.type
self.fields = report.fields
}
119. self.room <- map["room"]
self.children <- (map["children"], CAArrayTransform())
self.type <- (map["type"],
EnumTransform<CAReportType>())
// if report type has changed update fields to new report
template
let modifiedType = self.type != preMapReportType
if modifiedType
{
// want to set fields
switch self.type
{
case .StatusReview:
self.fields = CAReportTemplate.StatusReview.fields
case .ExParte: