iOS 8 HealthKit Santiapps Marcio Valenzuela

Saving HealthKit Data & Closures

This code bit saves: healthKitStore.saveObject(bmiSample, withCompletion: { (success, error) -> Void in if( error != nil ) { println(“Error saving BMI sample: \(error.localizedDescription)”) } else { println(“BMI sample saved successfully!”) } }) The method signature is: saveObject(object: HKObject!, withCompletion completion: ((Bool, NSError!) -> Void)!) This method takes an HKObject which is bmiSample and it takes a completion closure which itself takes a bool & error and returns void. So in our method call, we pass in the bmiSample as the HKObject and for the success and error completion block we say: if error is NOT nil then log that error’s description, else log that the bmiSample was saved successfully.  … Read More

Continue Reading

HealthKit for iOS8: Part 7

4. CoreData for other non-health stats You made it to the end!  Ok, so we are basically going to be adding another store to our app and reading and writing data to THAT store as well. First let’s add a new tab and make it a UITableViewController as well.  It will have dynamically populated cells. Now embed it!   Your final storyboard should look like this:   Add a new Swift class called Swimming Data and set that new UITableViewController scene to its class.  Make that class file look like this: import Foundation import UIKit class SwimmingData: UITableViewController { } Now we must add CoreData.  To do this we need to… Read More

Continue Reading

HealthKit for iOS8: Part 6

Here is the start of our WorkOut view controller: import Foundation import UIKit import HealthKit class WorkoutViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var numberOfLapsTextField: UITextField! @IBOutlet var metersPerLapTextField: UITextField! @IBOutlet var workoutDurationTextField: UITextField! @IBOutlet var paceTextField: UITextField! var numberOfLapsValue: NSString? var metersPerLapValue: NSString? var workoutDurationValue: NSString? var userWeight: Double? var  healthStore:HKHealthStore? } We import what we need, we subclass UITableViewController and add the Text Field delegate protocol.  Here I have created 4 labels for: numberOfLaps metersPerLap workoutDuration pace These labels have an underlying variable for each.  The reason the first 3 are strings is because these are not health kit data per se.  These will be stored in CoreData.  However they… Read More

Continue Reading

HealthKit for iOS8: Part 5

Jumping right in, our Energy view controller class starts out like this: import Foundation import UIKit import HealthKit class EnergyViewController: UITableViewController { var energyFormatter: NSEnergyFormatter { var energyFormatter: NSEnergyFormatter? var onceToken: dispatch_once_t = 0 dispatch_once(&onceToken, { energyFormatter = NSEnergyFormatter() energyFormatter?.unitStyle = NSFormattingUnitStyle.Long energyFormatter?.forFoodEnergyUse = true energyFormatter?.numberFormatter.maximumFractionDigits = 2 }) return energyFormatter! } // No required initWithCoder pasted in… var  healthStore:HKHealthStore? @IBOutlet weak var activeEnergyBurnedValueLabel: UILabel? @IBOutlet weak var restingEnergyBurnedValueLabel: UILabel? @IBOutlet weak var consumedEnergyValueLabel: UILabel? @IBOutlet weak var netEnergyValueLabel: UILabel? var activeEnergyBurned: Double = 0 var restingEnergyBurned: Double = 0 var consumedEnergy: Double = 0 var netEnergy: Double = 0 } We take care of our imports, subclass UITableViewController, create… Read More

Continue Reading

Implicitly Unwrapped Optionals

As an ObjC programmer, I despised the introduction of Optionals in Swift. However, I jumped on the Swift bandwagon on Day 1. So I understood the basic concepts: If a value may at some point not have a value, declare it as optional. If a value has been declared optional, you must test its contents. You can test with if == nil You can if let test Or you can force unwrap I also read about implicitly unwrapped optionals but I confused them with force-unwrapping.  It also threw me off about when and what to use them for. Recently I’ve been working on an app that involves a dance between… Read More

Continue Reading

HealthKit for iOS8: Part 3

Great!  Now let’s move on to the Journal View Controller.  It’ll be a good relax! 🙂 Ok we start out importing the frameworks we need: import UIKit import HealthKit Ok now let’s declare our class properties: class JournalViewController: UITableViewController {     let JournalViewControllerTableViewCellReuseIdentifier: NSString = “Cell”     var foodItems: NSMutableArray?     var energyFormatter: NSEnergyFormatter {         var energyFormatter: NSEnergyFormatter?         var onceToken: dispatch_once_t = 0         dispatch_once(&onceToken, {             energyFormatter = NSEnergyFormatter()             energyFormatter?.unitStyle = NSFormattingUnitStyle.Long             energyFormatter?.forFoodEnergyUse = true      … Read More

Continue Reading

HealthKit for iOS8: Part 2

So you got past the intro and learned about the health store and how we need authorization from the user in order to have read and write access to certain properties.  Now that the user trusts your app, let’s learn how to interact with the health store. 1. HKObjects and the health store Before we get into reading and writing, let’s get to know HKObjects.  Here is the class tree: As you can see, HKObjectType inherits directly from NSObject.  You can basically have 2 types of HKObjects; HKCharacteristic and HKSample -Type.  HKCharacteristicType doesn’t change over time whereas HKSampleType does change, such as calories consumed, calories burnt, Glucose levels etc.  Let’s… Read More

Continue Reading

HealthKit for iOS8: Part 1

Intro: What it’s for?   HealthKit is a framework that allows you to store health data to a persistent store on the users device.  We will begin with an app from Part 1 but we will take some detours that are important to understand so bare with me. The first steps are: – Create a tab bar application in Swift for iPhone Only – Rename First and Second view controllers to Profile and Journal and make them UITableViewControllers – In Capabilities turn on HealthKit HealthKit, (HK), requires permissions to access the health store since most of this data is considered confidential.  So to do this, move over to the AppDelegate.swift.… Read More

Continue Reading

Swift Closures Quick Reference: Part 3

Now let’s write our own closure! func fetchMostRecentDataOfQuantityType(quantityType: HKQuantityType, withCompletion completion: ((mostRecentQuantity:HKQuantity?, error:NSError?) -> ())? ) { let timeSortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: false) [timeSortDescriptor], resultsHandler: { (query:HKSampleQuery!, results:[AnyObject]!, error:NSError?) -> Void in let query = HKSampleQuery(sampleType: quantityType, predicate: nil, limit: 1, sortDescriptors: [timeSortDescriptor]) { query, results, error in if completion != nil && error != nil { completion!(mostRecentQuantity: nil, error: error) return; } let resultsArray = results as NSArray? var quantitySample: HKQuantitySample? = resultsArray?.firstObject as HKQuantitySample? var quantity: HKQuantity? = quantitySample?.quantity if completion != nil { completion!(mostRecentQuantity: quantity, error: error) } } self.healthStore?.executeQuery(query) } Notice we declare a function that takes a quantityType parameter and a completion parameter.  The… Read More

Continue Reading
iOS 8 HealthKit Santiapps Marcio Valenzuela

HealthKit for iOS8: Part 4

Ok so the Journal view controller was quite simple.  Let’s take another quick break by looking at an even simpler view controller, the FoodPicker: import Foundation import UIKit import HealthKit class FoodPickerViewController: UITableViewController { var selectedFoodItem: FoodItem? let FoodPickerViewControllerTableViewCellIdentifier:NSString = “cell” let FoodPickerViewControllerUnwindSegueIdentifier:NSString = “FoodPickerViewControllerUnwindSegueIdentifier” var foodItems: NSArray = NSArray() var energyFormatter: NSEnergyFormatter { var energyFormatter: NSEnergyFormatter? var onceToken: dispatch_once_t = 0 dispatch_once(&onceToken, { energyFormatter = NSEnergyFormatter() energyFormatter?.unitStyle = NSFormattingUnitStyle.Long energyFormatter?.forFoodEnergyUse = true energyFormatter?.numberFormatter.maximumFractionDigits = 2 }) return energyFormatter! } var  healthStore:HKHealthStore? } Here we are looking at imports, subclassing UITableViewController and property declarations. Our first property is selectedFoodItem, which will be set to whatever value the user selects from… Read More

Continue Reading

Swift Closures Quick Reference: Part 2

Let’s analyze some useful applications of closures in everyday code! Ok so let’s take a look at a real life function that uses a closure.  A typical closure is a completion handler.  A completion handler is a parameter, just like any other, that is passed into a function as a closure.  When that code gets executed, the completion handler gets filled.  Then your function will use the value of that completion handler to do something useful. Here are some typical uses of closures in API’s.  The typical one is UIView.animateWithDuration.  Open Xcode and start writing UIView.anim… and it will autocomplete for you with this: UIView.animateWithDuration(<duration: NSTimeInterval>, animations: <() -> Void()… Read More

Continue Reading

Swift Closures Quick Reference: Part 1

Blocks/Closures are confusing!  They’re confusing because its a bit abstract.  Most tutorials cover how a block is declared and used. Sometimes blocks or closures can me even more confusing… A block is a bunch of code wrapped up in a {}. You can 2 either of 2 things with them: A.  You can assign that block of code to a variable. (this is where completionHandlers, also a confusing concept, fit in) B.  You can use that block of code directly Let’s take a look at assigning it to something.  No doubt you have seen a construct like: var someName = “Mars” or var hisAge = 39 This would be considered hardcoding… Read More

Continue Reading

Swift is Confusing: Classes, Structures, Designated Initializers, Instance Methods, Type Methods, Functions, Methods, Convenience Initializers & External Parameter Names

Class vs Structs Both: Store values, initialize, subscripts, extensible & protocol Class can inherit, de-initialize, reference counting & typecast Functions vs Methods Methods are FUNCTIONS INSIDE A CLASS Functions can be inside or OUTSIDE A CLASS! Cannot use functionName(param1,param2) to call a function declared inside a class {} Methods: It is implicitly passed the object for which it was called It is able to operate on data that is contained within the class Instance Methods vs Type Methods (Instance Method vs Class Methods I think) Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for… Read More

Continue Reading
Swift Optionals Quick Reference for Newbies by Santiapps.com

Swift Optionals Quick Reference

Optionals confuse me so I wrote this post and hope it can be of some help. OPTIONALS Takeaway #1: Optionals are used to declare a variable but are not assigned a value at start Takeaway #2: Optionals contain a Some or None value, they DONT contain a String or Array or whatever else. Takeaway #3: Therefore we MUST unwrap the value of an Optional to see what the prize is 🙂 In other words, to access its value! Takeaway #4: DECLARATION OPTIONS A) Using the following syntax: var someVar? – You will mostly use this… B) Using “var someVar!” <Implicitly unwrapped> – Unfortunately UIKit & other Apple frameworks will use a lot of… Read More

Continue Reading

Why, oh Why, did Apple take away ARC just to give us Optionals!?

I’m having trouble understanding optionals so here is a shot at explaining them. 🙂 var thisIsAnInt: Int Simple, this is an Int variable declaration. var couldBeAnInt: Int? This on the other hand is an optional variable declaration. This optional declaration doesn’t mean: “this is an int, which is optional”. It reads more like: This is an OPTIONAL variable.  It’s a type of variable in and of itself.  Its NOT NECESSARILY an Int.  It just may or may NOT contain an Int”. Woah! Ok so what is it for and when do you use it.  Well that part seems simple enough: If that variable can or could or may be nil… Read More

Continue Reading

iOS : Swift : Blocks = Closures

I’ve never really liked blocks in ObjC. When Swift came out it made things more complicated for me because I’ve never really liked C either. Finally when I had to deal with closures in Swift, well that’s just gonna piss a lot of people off! After a few days reviewing tons of material online, and I mean TONS!  I came to understand this: The only C-like exposure I had prior to ObjC was a little PHP.  So that allows me to understand a function, which is the equivalent of a method in ObjC: DECLARING func sayHello( ) {      println(“Hello World”) } CALLING sayHello( ) RESULT Hello World Even… Read More

Continue Reading

Swift Tutorial II

Ok so in the first tutorial we covered let, which is the keyword for defining constants. let thisBeAConstant = 3.141 Now we are going to cover variables, which use the var keyword like so: var thisVariable = time Notice 2 things about Swift: 1) We don’t use ; at the end of a line.  That’s just weird 🙂 2) We don’t have to specify the type.  The type is inferred by whatever value you pass in, so: var someString = “this is a string” var someInteger = 5 So Swift is kinda smart.  Now let’s meet some old friends “Hao jiu bu juan” ARRAYS var energies = [“solar”, “wind”, “fossil”, “this is a… Read More

Continue Reading