Skip to content
This repository was archived by the owner on Apr 16, 2020. It is now read-only.

update to Swift 5, add new HealthKit parameters #7

Open
wants to merge 19 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
172 changes: 85 additions & 87 deletions Example/HealthKitSampleGenerator.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>IDEDidComputeMac32BitWarning</key>
<true/>
</dict>
</plist>
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>BuildSystemType</key>
<string>Original</string>
</dict>
</plist>
241 changes: 94 additions & 147 deletions Example/HealthKitSampleGenerator/Base.lproj/Main.storyboard

Large diffs are not rendered by default.

36 changes: 18 additions & 18 deletions Example/HealthKitSampleGenerator/ExportViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ class ExportViewController : UIViewController, UITextFieldDelegate {

var exportConfigurationValid = false {
didSet {
btnExport.enabled = exportConfigurationValid
btnExport.isEnabled = exportConfigurationValid
}
}

Expand Down Expand Up @@ -57,9 +57,9 @@ class ExportViewController : UIViewController, UITextFieldDelegate {

var exportInProgress = false {
didSet {
avExporting.hidden = !exportInProgress
btnExport.enabled = !exportInProgress
pvExportProgress.hidden = !exportInProgress
avExporting.isHidden = !exportInProgress
btnExport.isEnabled = !exportInProgress
pvExportProgress.isHidden = !exportInProgress
}
}

Expand All @@ -68,11 +68,11 @@ class ExportViewController : UIViewController, UITextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()

tfProfileName.text = "output" + UIUtil.sharedInstance.formatDateForFileName(NSDate())
tfProfileName.addTarget(self, action: "textFieldDidChange:", forControlEvents: UIControlEvents.EditingChanged)
tfProfileName.text = "output" + UIUtil.sharedInstance.formatDateForFileName(date: NSDate())
tfProfileName.addTarget(self, action: #selector(textFieldDidChange(_:)), for: UIControlEvents.editingChanged)
tfProfileName.delegate = self

scExportType.selectedSegmentIndex = HealthDataToExportType.allValues.indexOf(HealthDataToExportType.ALL)!
scExportType.selectedSegmentIndex = HealthDataToExportType.allValues.index(of:HealthDataToExportType.ALL)!

lbExportMessages.text = ""

Expand All @@ -94,23 +94,23 @@ class ExportViewController : UIViewController, UITextFieldDelegate {
exportConfiguration: exportConfiguration!,

onProgress: {(message: String, progressInPercent: NSNumber?)->Void in
dispatch_async(dispatch_get_main_queue(), {
DispatchQueue.main.async {
self.lbExportMessages.text = message
if let progress = progressInPercent {
self.pvExportProgress.progress = progress.floatValue
}
})
}
},

onCompletion: {(error: ErrorType?)-> Void in
dispatch_async(dispatch_get_main_queue(), {
onCompletion: {(error: Error?)-> Void in
DispatchQueue.main.async {
if let exportError = error {
self.lbExportMessages.text = "Export error: \(exportError)"
print(exportError)
}

self.exportInProgress = false
})
}
}
)
}
Expand All @@ -121,25 +121,25 @@ class ExportViewController : UIViewController, UITextFieldDelegate {

func createAndAnalyzeExportConfiguration(){
var fileName = "output"
if let text = tfProfileName.text where !text.isEmpty {
if let text = tfProfileName.text, !text.isEmpty {
fileName = FileNameUtil.normalizeName(text)
}

let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
print(documentsUrl)
let outputFileName = documentsUrl.URLByAppendingPathComponent(fileName+".json.hsg").path!
let outputFileName = documentsUrl.appendingPathComponent(fileName+".json.hsg").path

exportTarget = JsonSingleDocAsFileExportTarget(
outputFileName: outputFileName,
overwriteIfExist: swOverwriteIfExist.on)
overwriteIfExist: swOverwriteIfExist.isOn)

exportConfiguration = HealthDataFullExportConfiguration(profileName: tfProfileName.text!, exportType: HealthDataToExportType.allValues[scExportType.selectedSegmentIndex])
exportConfiguration = HealthDataFullExportConfiguration(profileName: tfProfileName.text!, exportType: HealthDataToExportType.allValues[scExportType.selectedSegmentIndex], startDate: Date().addingTimeInterval(-3600), endDate: Date(), shouldAuthorize: true)


exportConfigurationValid = exportTarget!.isValid()
}

func textFieldDidChange(_: UITextField) {
@objc func textFieldDidChange(_: UITextField) {
createAndAnalyzeExportConfiguration()
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
{
"images" : [
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "2x"
},
{
"idiom" : "iphone",
"size" : "20x20",
"scale" : "3x"
},
{
"idiom" : "iphone",
"size" : "29x29",
Expand Down Expand Up @@ -29,10 +39,15 @@
"idiom" : "iphone",
"size" : "60x60",
"scale" : "3x"
},
{
"idiom" : "ios-marketing",
"size" : "1024x1024",
"scale" : "1x"
}
],
"info" : {
"version" : 1,
"author" : "xcode"
}
}
}
24 changes: 12 additions & 12 deletions Example/HealthKitSampleGenerator/ImportProfileViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,11 @@ class ImportProfileViewController : UIViewController {

var importing = false {
didSet {
pvImportProgress.hidden = !importing
aiImporting.hidden = !importing
pvImportProgress.isHidden = !importing
aiImporting.isHidden = !importing
navigationItem.hidesBackButton = importing
swDeleteExistingData.enabled = !importing
btImport.enabled = !importing
swDeleteExistingData.isEnabled = !importing
btImport.isEnabled = !importing
}
}

Expand All @@ -48,13 +48,13 @@ class ImportProfileViewController : UIViewController {
lbImportProgress.text = ""
}

override func viewDidAppear(animated: Bool) {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

profile?.loadMetaData(true) { (metaData: HealthKitProfileMetaData) in
NSOperationQueue.mainQueue().addOperationWithBlock(){
OperationQueue.main.addOperation(){
self.lbProfileName.text = metaData.profileName
self.lbCreationDate.text = UIUtil.sharedInstance.formatDate(metaData.creationDate)
self.lbCreationDate.text = UIUtil.sharedInstance.formatDate(date: metaData.creationDate as NSDate?)
self.lbVersion.text = metaData.version
self.lbType.text = metaData.type
}
Expand All @@ -69,18 +69,18 @@ class ImportProfileViewController : UIViewController {
let importer = HealthKitProfileImporter(healthStore: healthStore)
importer.importProfile(
importProfile,
deleteExistingData: swDeleteExistingData.on,
deleteExistingData: swDeleteExistingData.isOn,
onProgress: {(message: String, progressInPercent: NSNumber?)->Void in
NSOperationQueue.mainQueue().addOperationWithBlock(){
OperationQueue.main.addOperation(){
self.lbImportProgress.text = message
if let progress = progressInPercent {
self.pvImportProgress.progress = progress.floatValue
}
}
},

onCompletion: {(error: ErrorType?)-> Void in
NSOperationQueue.mainQueue().addOperationWithBlock(){
onCompletion: {(error: Error?)-> Void in
OperationQueue.main.addOperation(){
if let exportError = error {
self.lbImportProgress.text = "Import error: \(exportError)"
print(exportError)
Expand All @@ -93,4 +93,4 @@ class ImportProfileViewController : UIViewController {
}
}

}
}
2 changes: 2 additions & 0 deletions Example/HealthKitSampleGenerator/Info.plist
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>NSHealthShareUsageDescription</key>
<string>for health export</string>
<key>CFBundleDevelopmentRegion</key>
<string>en</string>
<key>CFBundleDisplayName</key>
Expand Down
54 changes: 25 additions & 29 deletions Example/HealthKitSampleGenerator/ProfilesTableViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,30 +18,28 @@ class ProfilesTableViewController: UITableViewController {

override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = editButtonItem();
navigationItem.leftBarButtonItem = editButtonItem;
}

override func viewDidAppear(animated: Bool) {
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

let documentsUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
profiles = HealthKitProfileReader.readProfilesFromDisk(documentsUrl)

tableView.reloadData()
}

override func viewWillDisappear(animated: Bool) {
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
// make sure the table view is not in editing mode
if tableView.editing {
if tableView.isEditing {
tableView.setEditing(false, animated: true)
}
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "detailView" {
let detailViewController = segue.destinationViewController as! ImportProfileViewController
let detailViewController = segue.destination as! ImportProfileViewController
if let indexPath = tableView.indexPathForSelectedRow {
detailViewController.profile = profiles[indexPath.row]
}
Expand All @@ -53,25 +51,24 @@ class ProfilesTableViewController: UITableViewController {
// TableView DataSource
extension ProfilesTableViewController {

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return profiles.count
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let profile = profiles[indexPath.row]
let cell = tableView.dequeueReusableCellWithIdentifier("profileCell")!
let cell = tableView.dequeueReusableCell(withIdentifier: "profileCell")!

cell.textLabel?.text = profile.fileName

profile.loadMetaData(true) { (metaData:HealthKitProfileMetaData) in

NSOperationQueue.mainQueue().addOperationWithBlock(){
OperationQueue.main.addOperation(){

let from = UIUtil.sharedInstance.formatDate(metaData.creationDate)
let from = UIUtil.sharedInstance.formatDate(date: metaData.creationDate as NSDate?)
let profileName = metaData.profileName != nil ? metaData.profileName! : "unknown"

cell.detailTextLabel?.text = "\(profileName) from: \(from)"
Expand All @@ -87,33 +84,32 @@ extension ProfilesTableViewController {
// UITableViewDelegate
extension ProfilesTableViewController {

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
let profile = profiles[indexPath.row]

let alert = UIAlertController(
title: "Delete Profile \(profile.fileName)",
message: "Do you really want to delete this prolfile? The file will be deleted! This can not be undone!",
preferredStyle: .Alert)
preferredStyle: .alert)

alert.addAction(UIAlertAction(title: "Yes, delete it!", style: .Destructive, handler: { action in
alert.addAction(UIAlertAction(title: "Yes, delete it!", style: .destructive, handler: { action in
do {
try profile.deleteFile()
self.profiles.removeAtIndex(indexPath.row)
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Automatic)
self.profiles.remove(at: indexPath.row)
self.tableView.deleteRows(at: [indexPath], with:.automatic)
} catch let error {
let errorAlert = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .Alert)
errorAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
self.presentViewController(errorAlert, animated: true, completion: nil)
let errorAlert = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert)
errorAlert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(errorAlert, animated: true, completion: nil)
}
}))

alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))

self.presentViewController(alert, animated: true, completion: nil)
self.present(alert, animated: true, completion: nil)
}
}


}
}
21 changes: 10 additions & 11 deletions Example/HealthKitSampleGenerator/UIControls.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,17 @@ public class BaselineTextField : UITextField {

required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
borderStyle = UITextBorderStyle.None
borderStyle = UITextBorderStyle.none

}

override public func drawRect(rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(ctx, 1.0);

CGContextSetRGBStrokeColor(ctx, 0.6, 0.6, 0.6, 1);
CGContextMoveToPoint(ctx, 0, rect.size.height);
CGContextAddLineToPoint( ctx, rect.size.width, rect.size.height);

CGContextStrokePath(ctx);
override public func draw(_ rect: CGRect) {
if let ctx = UIGraphicsGetCurrentContext(){
ctx.setLineWidth(1.0)
ctx.setStrokeColor(UIColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 1.0).cgColor)
ctx.move(to: CGPoint(x: 0, y: rect.size.height))
ctx.addLine(to: .init(x: rect.size.width, y: rect.size.height))
ctx.strokePath()
}
}
}
}
Loading