Firebase GeoFire with Swift Tutorial

This tutorial assumes that you have a Firebase project set up and ready to go and are looking to incorporate GeoFire into it. There is a guide on getting started with Firebase, references to these two posts:

Installing with CocoaPods

Add the GeoFire library to your project pod file and run pod install:

Fixing FirebaseDatabase/FIRDatabase.h not found Error

If you open your project (of course the xcworkspace file now we’re dealing with a cocoapods project), in a view controller, import the required libraries:

Try and build your project. You may have a compile error saying “FirebaseDatabase/FIRDatabase.h not found”. This is because the Firebase Database framework isn’t visible to the GeoFire framework, and unsurprisingly the latter needs to know about the former.

To fix this error go and check the Target Membership for Geofire in the FirebaseDatabase.framework target:

Try rebuilding your project, and it should build successfully.

Adding Location Data For GeoFire

In this example we’ll suppose we’re tracking locations of users, of course this could be anything that your app requires that has coordinates (restaurants for example). A great thing about the GeoFire library is that it doesn’t really require much in the way of restructuring your data. GeoFire requires that you add a new node to your database to store the location related data of things. In this example it would make sense to do this at a new node in the root of the database called ‘user_locations’:

This ‘GeoFire’ object is how we’ll update location data for a given key and also how we’ll later query for nearby data.

To set a location for an object you call the setLocation method. For this example, lets suppose we’re responding to a CLLocationManager informing us that a users location has changed:

Here we get the last (the latest) CLLocation object from the array. We then set that location for the currently logged in user.

Query For Nearby Locations

Once we have location data in our database we’ll likely want to start querying our database for nearby data. This is done with the same GeoFire database reference.

There are a few ways you can query your data, the most basic is with a location and a radius. You’ll need a CLLocation object, this is the centre location, and a radius  from this point to search. Assuming we have our users location saved as a property of the view controller, our query might look like this:

We then set up a listener on this object. This should feel familiar to how we observe regular Firebase references:

This completion block will be called every time a user enters our search radius. This is because we passed in the ‘keyEntered’ as our event type. We can also pass in key ‘keyExited’ or keyMoved as our event type. The completion handler receives two values, a key (String) and a location (CLLocation). The key value should most likely be a reference to a child at another node in the database.

Indexing

 

Bootstrap 4 Hamburger Menu Animation

The HTML

First thing to note is that the way the “Hamburger” menu works in Bootstrap v4 is different to the previous version of Bootstrap. In Bootstrap v3 the hamburger was made up of three individual span tags. In the latest version, this has been replaced with a single span tag with an SVG graphic drawn into the background. This new approach isn’t going to work for this purpose, so the first thing we’ll do is adopt the previous approach.

In Bootstrap v4, the button in the nav that toggles the dropdown menu looks something like this:

We need to replace it with the following:

This replaces the single span tag with three as explained above. We also put the .icon-bar class on each of them, along with a unique class (top, middle and bottom-bar). We’ll need a way to uniquely identify each of them when it comes to animation them in just a second.

The CSS

Next to the CSS we need to make this look like the traditional Hamburger Menu is:

If you look at the page in a browser at this point, everything should look familiar. You should have the dropdown menu behaving as it always should.

 The Animation

The animation is all taken care of in the CSS with just a few extra classes:

 

Swift Classes

Classes

Classes really are the bread and butter of object oriented programming (OOP). They are the building blocks of any applications which allow you to create "objects" to work with.

Essentially, a class couples together variables/contants and functions into one manageable package for you to work with.

Classes are abstract blueprints for the objects that your application needs to work with.

As a starting point:

  • Each class should be its own Swift file.
  • Classe should start with an upper case letter and are camel cased.
  • Classes start with the keyword class, the class name and then a set of curly brackets.
  • Everything goes inside these brackets.
class Person {

}

The above is a class decleration for a Person object. It doesn't do a lot at the moment, but already we can start creating Person objects in our application:

let someone = Person()

Lets expand the class to make it a bit more useful. Generally you can think of objects as being made up of two main components.

  • Its properties
  • Its methods (functions)

Properties

Lets start with adding some properties. Properties are simply constants and vairables within a class, think of them as the information associated with the object. For example sticking with our Person class, typically a person may have an age and an name:

class Person {

  let name: String!
  var age: Int!

}

Here we're saying that a Person has a name which is a String and an age which is an Int. We've declared a name as a constant and age as a variable, in our example a persons age can change, but once a name is set, they are not allowed to change it. At the moment, we will actully have a compile error, that's because name hasn't be given a default value. We could fix this by setting it as nil, but lets look at adding an initilizer to solve this problem:

init(name: String, age: Int) {
  self.name = name
  self.age = age
}

The init is a decleration looks a lot like a normal function, just without the keyword func. All classes get a default initilizer which we dont have to write, but would like like init(). The one we've writen above works exactly like a normal funtion, we are saying that we want to pass a name which is of type String and an age which is of type Int. We then assign those value we passed into the init to the respective propertive of the Person object.

Self?

You may be wondering what this self word is all about. Well, the constants that we pass into our init are called "name" and "age" which are the same names we gave our poperties. Within the init function "name" and "age" would reference the values passed into it opposed to the properties. Prefixing them with self make it clear were referencing the class properties.

Creating a Person

Now we have a very basic class setup we can start using person objects, technically called "instances". Creating one would look like this:

let someone = Person(name: "John", age: 20)

Creating an instance of our Person class looks a lot like creating any other vairiable or constant, we define it with let or var, give it a name and then use the initilized that we declared in the class, in the above example we now have a constant called someone, which is a Person object. You accessing properties of the object by using dot syntax. Here we'll simple print the persons name and because the age property was declared with var, we can change it to something else:

print(someone.name)
//Prints "John"

someone.age = 21
//Someones age will now be set to 21

Swift Methods & Functions

Methods & Functions

Methods and functions in Swift work similarly to many other languages, if you understand functions in another language, chances are it won't take you long to feel right at home in Swift.

Method vs Function

For simplicity here regard the words "method" and "function" as interchangable, as the keyword to define them is func I'll use the term "function" from here on.

Functions are simple a block of code that you have wrapped up and given a name to. They can be as long or as short as you like, this largely depends on how comple the task that the function performs is. Although it's generally a good idea to try and keep your functions as short and concise as possible, this keep things clear and managable.

Declaring a Function

A simple function might look something like this:

func saySomething() {
  print("Hello")
}

As you can see, they start with the keyword func, are then given a name (camel cased), a set of bracket, then a set of curly brackets which contain the body of the function. In the above example this simple prints the word "Hello".

Calling A Function

Once you have a function defined, you have to call it in order to execute it. Calling a function is straight forward, you just write the name of the function followed by a set of brackets. Calling the function we declared above would look like this:

saySomething()

This saySomething function can now be called time and time again to repete a task, performing the same action every time, in this case printing the words "Hello", but what if we wanted it to change slightly each time? This is where "arguments" come in...

Functions With Arguments

Arguments (sometimes called parameters) can be "passed" to a function to subtly (or in some cases dramatically) change how that function executes. Carrying on from our above example, the empty set of brackets after the function name signals that it currently accepts no arguments, lets change that.

Rather than printing the word "Hello" every time, let's give ourselves the ability to change the word that is printed. To do this we need to change the decleration of the function to accept a String:

func saySomething(words: String) {
  print(words)
}

Arguments come two parts, first a name, then the Type. The value of that argument then exists as a constant that we can use within the body of the fucntion. So here we print out words, which will be whatever value is "passed" to the function when we call it, which now looks like this:

saySomething(words: "Hello")

saySomething(words: "Something else")

Above, we're making two calles to the same function, but passing in different arguments. We can no longer call the function without any arguments as before, Xcode will tell us that we are missing an argument and offer us a Fix-it.

Note: As always Swift if obsessed with Type. This is a good thing, in the above example it means we can't pass an Int where the function is expecting a String. If we tried to do so we would get an error.

Install CakePHP 3 On Ubuntu 16.04 Digital Ocean

This guide assumes you’ve set up a Ubuntu 14.04 server and have MYSQL up and running. This guide uses the “PHPMyAdmin” from the “One Click Apps” available on Digital Ocean running on a droplet running Ubuntu 16.04. The smallest memory (512mb) should be enough to get you up and running.

If you don’t have a Digital Ocean account (you should, they’re a great service) get one here.

Step 1: Update Package Manager

Fire up a new terminal window and ssh into you’re droplet:

Note: If this is the first time you’ve logged into your droplet, you will be asked to change the password from the one emailed to you when you created your droplet. This is fairly self explanatory, simply follow the prompts.

Update your package manager:

Step 2: Install Some PHP Modules

We need to install a few PHP modules that CakePHP uses. Namely the curl, zip, intl and sqlite modules.

Run these commands in succession. You may be asked if you want to take up the extra space, reply ‘Y’ for yes:

 

Step 3: Install Composer

Composer is a dependancy manager for PHP, this is ultimately what we’ll use to install CakePHP to our server:

 

Step 4: Enable Rewrite Module

Make sure the recite module is enabled:

 

Step 5: Restart Apache

For all the changes we’ve made to actually take affect, we need to restart our server:

 

Step 6: Enable AllowOverride

Navigate to the ‘/etc/apache2’ directory, download and open the ‘apache2.conf’ file. Around line 166 within the ‘<Directory /var/www/>’ tags, change the that says ‘AllowOverride None’ to:

This allows .htaccess files to override of the Apache config on a per directory basis, which is what CakePHP needs.

You’ll also need to restart apache again for this change to take affect:

 

Step 7: Install CakePHP

Tip: The install process can be memory intensive, if you’re on a server with limited resource it can be a good idea to stop some other processes before the install start. In this case mysql would be a good one to kill and then restart after composer has finished. This can be done with the following two commands:

Stat/Stopping MySql:

 

Finally, we’re at the point where we can actually install CakePHP. We’ll use composer to download and setup our application. First off we need to change to the directory that we want it installed to. This will most likely be your public folder:

Note: Change YOUR_APP_NAME to something applicable (no spaces):

 

Step 8: Update The Web Root For Your Droplet

At the moment when we visit our droplet via a browser, we are taken to the ‘html’ folder (currently displays the default apache page). If you look in the folder you created in the previous step, there is a ‘webroot’ folder. This is actually the folder we need to point our droplet to. We can do this in one of the apache config files.

Navigate to the ‘/etc/apache2/sites-enabled’ directory and download and open the ‘000-default.conf’ file. You need to just change one line (around line 12):

Note: Again, change YOUR_APP_NAME to whatever you used in the previous step.

Re-upload this from whence it came overwriting the old file. Finally give apache one last restart for that to take affect:

Done!

If you visit your droplet IP in a browser, all being well, you should now see the default CakePHP.

 

 

You should see an abundance of green under ‘Environment’, ‘Filesystem’ and ‘DebugKit’. The ‘Database’ will show an error as we haven’t set one up yet and edited the CakePHP config file to tell it where to look for our database. You’ll need to setup a database and then edit your config.php file details can be found on how to do that in the CakePHP documentation here.

Note

As we’re running our cake setup and developing on a server as opposed to a local environment, we’ve uploaded the cake shell script used to generate the scaffolding code for our database. This lives in the ‘bin’ directory. You’ll need to give this file write and execute permissions:

 

 

 

Swift Optionals

Optionals

Swift is obsessed with everything being in a valid state. That is to say a for example String has to contain a valid string. It can’t be a number, or anything else (see Swift Type Casting) or even nil.

That is unless we mark the value as an optional. I’ll start by stating there is much more to be said about optionals than will be covered here, this is just the core concept.

Generally is you see an exclamation point (!) or question mark (?), it’s a safe assumption that you’re dealing with an optional value. Only in the case of a variable/constant being marked as an optional can it contain a nil value.

Optionals also have to have their type declared. Lets take a look at one:

  var name: String?

This creates a new name variable which can contain a String (and only a String) but but can be nil, and in fact is currently nil. We can then set this value at a later point in time just like any other value:

  name = "Kyle"

If we were to print this to our console at this point we would see “Optional(Kyle)”. That’s because we haven’t unwrapped the optional value.

Another way we could do a similar thing is:

  var name: String!

The difference between ? and !

? – Indicates that this value may or may not contain a value, it could be nil.

! – Indicates that by the time we come to use it, it will contain a valid value.

Swift Type Casting

Type Casting

Swift is a Type Safe language. That means that it is obsessed with what type of data is associated with what

When we declare a variable or constant, there are a few ways we can do it:

let someNumber = 5 

let anotherNumber: Int = 8

These lines essentially do the same thing (with the exception of the constant name and the actual number clearly). The extra syntax in the second example is simply declaring the type of data that ‘anotherNumber’ is going to be an Int value. One of the most useful bits of advice I got when I started learning swift is to read the colon as “is of type”. To that line would read as “The constant anotherNumber is of type Int and equals 8”.

That being said the preferred way is to leave the type declaration off and let swift infer the type itself. In this example its blatantly clear the ‘anotherNumber’ is an integer, so there is no need for the explicit type declaration.

Type safety is awesome! Why? Well it simply means that once a value is set we know what type of data it will contain. That means that A String will always be a String, never an Int or any other type of data.

Swift Variables & Constants

Variables & Constants

Variables

To create a variable in swift, you start with the keyword 'var', followed by your name (camel cased, because you're a good developer) and then a value:

var someWords = "Hello World"

Variables, as the name implies, can change over time. For example at a later point you could reassign the 'someWords' value:

someWords = "Something else"

Constants

Constants are declared very similarly to variables, except instead of 'var', you use 'let':

let name = "Kyle"

Again, as the name suggests, constants cannot change. Once they are set, they keep the value until they are deallocated.

Notes

So why would you ever use a constant, they’re like variables, but with restrictions, right? Yes, but there are two main reasons. Most importantly, it makes your intent very clear. By making something a constant, you are explicitly stating that this value will not change, ever. By using a variable, you are stating that, yes, this may well change when I use it again at a later point in time. Secondly, the compiler can make some slight optimisations for constantly.

Xcode will actually inform you if you have declared a variable and never changes it, and suggest you change it to a constant, and if you try to change a constant it force you to change it’s declaration to a variable.

Basically, just declare everything with ‘let’. When you try and change it Xcode will force you to change the declaration.

Setting Up A Firebase Project in Xcode

This short guide will go over the few extra steps needed to get your Xcode project up and running with Firebase. This guide follows on from a previous post that demonstrates how to install the Firebase libraries with CocoaPods.

You need to create a new Firebase account, the free plan aka ‘Spark’ is more than enough to get you up and running.

When you login you’ll be presented with an empty Firebase console, click “Create New Project”

 

 

Generally each of your apps will be associated with a different Firebase project. It makes sense to name them appropriately, but this doesn’t matter too much (it can also be changed at a later date).

 

 

The next part is important. You need to enter the bundle ID for the app your Firebase project is going to be linked to. You can find this by going to the ‘General’ tab in your app settings.

 

 

The next screen will present you with a link to download a ‘GoogleService-Info.plist’ file. Download this and drag it into your project navigator to add it to your project.

 

 

The rest of these steps discuss how to install the Firebase libraries using Cocoapods, a guide on how to do that can be found here.

That’s it, you should now have project ready to start using Firebase.

Media Events jQuery

A common thing to want to do is respond to the state of some media (audio of video) playing on your page. You can “hook” into a number of events on the media object, like when the video is playing, when it is paused, even find out the current time of the video.

However, we’ll start by looking at probably the most common scenario, which is to do something when a video (or audio) comes to a stop, the is the “ended” event.

We’ll first set up a simple video in our HTML. Most importantly, we need to give it an id attribute. Here, I’ve called it “myVideo”:

 

Note: As always we’ll be working inside our $(document).ready() runction. 

This is an incredibly useful resource for finding all the events and information you can extract from a media object: https://www.w3.org/2010/05/video/mediaevents.html