Thursday, February 8, 2018

Monday, February 5, 2018

Cloud Functions for Firebase

Cloud functions for firebase allow one to automatically run backend code in response to events triggered by firebase features and HTTPS requests. The code is stored in Google cloud and runs in managed environment. 



The cloud functions that a developer write can respond to events generated by below firebase and Google cloud features



1) Cloud Firestore Triggers

2) Realtime database triggers

3) Firebase authentication triggers 

4) Google analytics for firebase triggers 

5) Crashlytics Triggers 

6) Cloud Storage triggers 

7) Cloud Pub/Sub triggers 

8) HTTP triggers 



How does it work? 



After a function is deployed, Google servers begin to manage functions immediately. listening for events and running the function when it is triggered. As the load increases or decreases, Google responds by rapidly scaling the number of virtual server instances needed to run your function.



LifeCycle of a function 



- The developer writes code for a new function, selecting an event provider (such as Realtime Database), and defining the conditions under which the function should execute.

- The developer deploys the function, and Firebase connects it to the selected event provider.

-  When the event provider generates an event that matches the function's conditions, the code is invoked.

- If the function is busy handling many events, Google creates more instances to handle work faster. If the function is idle, instances are cleaned up.

- When the developer updates the function by deploying updated code, all instances for the old version are cleaned up and replaced by new instances.

- When a developer deletes the function, all instances are cleaned up, and the connection between the function and the event provider is removed.



To enable cloud functions, below is what has to be done: 



- Setup : Install CLI and initialise cloud functions in firebase project

- Write Functions: Write Javascript code (or Typescript ) to handle events from firebase services, Google cloud services, or other event providers. 

- Deploy and monitor : Deploy functions using firebase CLI. 



references:

https://firebase.google.com/docs/functions/

HealthKit introduction iOS

To integrate the HealthKit, first step is to enable HealthKit in the app. This can be done via the Capabilities tab
Second main step is to get the permission to access the HealthKit 

healthManager.authorizeHealthKit { (authorized,  error) -> Void in
    if authorized {
        
        // Get and set the user's height.
        self.setHeight()
    } else {
        if error != nil {
            print(error)
        }
        print("Permission denied.")
    }
}

We need to request authorisation to share the type of data. 

let healthKitStore: HKHealthStore = HKHealthStore()
    
    func authorizeHealthKit(completion: ((success: Bool, error: NSError!) -> Void)!) {
        
        // State the health data type(s) we want to read from HealthKit.
        let healthDataToRead = Set(arrayLiteral: HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)!)
        
        // State the health data type(s) we want to write from HealthKit.
        let healthDataToWrite = Set(arrayLiteral: HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)!)
        
        // Just in case OneHourWalker makes its way to an iPad...
        if !HKHealthStore.isHealthDataAvailable() {
            print("Can't access HealthKit.")
        }
        
        // Request authorization to read and/or write the specific data.
        healthKitStore.requestAuthorizationToShareTypes(healthDataToWrite, readTypes: healthDataToRead) { (success, error) -> Void in
            if( completion != nil ) {
                completion(success:success, error:error)
            }
        }
    }

Below is a sample that reads height data from the healthKit 

    func getHeight(sampleType: HKSampleType , completion: ((HKSample!, NSError!) -> Void)!) {
        
        // Predicate for the height query
        let distantPastHeight = NSDate.distantPast() as NSDate
        let currentDate = NSDate()
        let lastHeightPredicate = HKQuery.predicateForSamplesWithStartDate(distantPastHeight, endDate: currentDate, options: .None)
        
        // Get the single most recent height
        let sortDescriptor = NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: false)
        
        // Query HealthKit for the last Height entry.
        let heightQuery = HKSampleQuery(sampleType: sampleType, predicate: lastHeightPredicate, limit: 1, sortDescriptors: [sortDescriptor]) { (sampleQuery, results, error ) -> Void in
                
                if let queryError = error {
                    completion(nil, queryError)
                    return
                }
                
                // Set the first HKQuantitySample in results as the most recent height.
                let lastHeight = results!.first
            
                if completion != nil {
                    completion(lastHeight, nil)
                }
        }
        
        // Time to execute the query.
        self.healthKitStore.executeQuery(heightQuery)
    }

Now to write the distance value into the HealthKit store, below is what needed 

func saveDistance(distanceRecorded: Double, date: NSDate ) {
                
        // Set the quantity type to the running/walking distance.
        let distanceType = HKQuantityType.quantityTypeForIdentifier(HKQuantityTypeIdentifierDistanceWalkingRunning)
        
        // Set the unit of measurement to miles.
        let distanceQuantity = HKQuantity(unit: HKUnit.mileUnit(), doubleValue: distanceRecorded)
        
        // Set the official Quantity Sample.
        let distance = HKQuantitySample(type: distanceType!, quantity: distanceQuantity, startDate: date, endDate: date)
        
        // Save the distance quantity sample to the HealthKit Store.
        healthKitStore.saveObject(distance, withCompletion: { (success, error) -> Void in
            if( error != nil ) {
                print(error)
            } else {
                print("The distance has been recorded! Better go check!")
            }
        })
    }


references: