2016-08-31T15:08:35+02:00http://fancypixel.github.io/Octopress2015-11-24T14:35:45+01:00http://fancypixel.github.io/blog/2015/11/24/moving-to-watchos-2A while ago we released Gulps on the AppStore. Gulps is a simple water tracking app that also reminds you when to drink throughout the day.
This was an app of “firsts” for me: first Swift app, first full app open sourced, first WatchKit app, first HealthKit app, first 3D touch implementation. It’s my go-to app when I need to experiment with new stuff. The streak continues with WatchOS 2.
In this post we’ll cover how to share data between the main app and the watch extension with the WatchConnectivity framework, and how to create a simple set of watch face complications. As an added bonus we’ll be doing that with a full open source app, that’s live on the AppStore. Off we go.

Gulps

The previous version of Gulps relied on Apple’s App grouping to share data between the app and the watch extension. The data was stored on Realm, and thanks to its notification system, the watch app was always kept up to date when a change occurred. This was possible because the watch extension used to live on the phone alongside the main app. It was a brilliant system, and so easy to implement… my heart sank when Apple announced that they were moving the watch extension on the watch itself. I knew that a storm of refactoring was coming. Before opening that can of worms, let’s reminisce about the good old times.
This is the setup for a WatchOS 1 app:

Once a change occurred on the phone or on the Watch app, a broadcast notification was fired, triggering a closure that updated the UI.
If you want to know more about Realm and app grouping, checkout this article by yours truly. It still is the best way to share data between the main app and an extension (e.g: a today widget).

WatchOS 2

I do realize it took me a while to jump on the WatchOS 2 train, but since Gulps was fairly good received and reviewed, I wanted to be extra careful in handling the transition to the new OS. Just as a reminder, WatchOS 2 drastically changes how a watch app works, by moving the extension from the iPhone app to the Apple Watch itself.

This has a major advantages: less spinning spinner of spinning boredom, the app is a lot snappier, and can rely a lot less on the phone (e.g. by making independent network requests).
That’s cool, but it comes at a cost… sharing data as we did before is impossible.
Apple provided a new framework though: WatchConnectivity.

The framework offers different ways to enable the communication between the phone and the watch, but it can be really tricky to get everything working reliably.
We can say that WatchOS 2 added some complexity and some complications 😬.
Complications are small modules used to personalize the watch faces and show small tidbits of interesting data when the user glances at the time. Now we can finally add our own modules, and having the percentage of your daily water intake goal sounds pretty good (so good that users started to request them the day after WatchOS 2’s release).

Sharing

WatchConnectivity introduces four main ways to communicate between the phone and watch:

Application Context, a dictionary with the latest up to date information. It’s transferred by the system in the background, and each new entry overwrites the old one. This is great to share the application current state

Use info, similar to the application context, but the transfers are queued up and delivered in order, without overwrites

File transfer to share files

Interactive messages, used when both the app and the phone are active and in range. It’s a more interactive way to share data, ideal when the user needs to see the feedback on both screens.

For Gulps I picked Application Context sharing, since the current state of the daily progress is what really matters, and the user hardly uses both apps at the same time (although since the transfer is pretty fast, when he does, the feedback is still snappy).
All the code is available on GitHub, for sharing the data we’ll reference the WatchConnectivityHelper and WatchEntryHelper: here and here.

Setting up the session

Before communicating back and forth we need to enable the watch session on both the phone and the watch. We do this using WatchConnectivity’s singleton WCSession.
The session must be initiated as soon as possible, so the AppDelegate sounds like a reasonable place to to that on the phone counterpart:

From phone to watch

All the utility functions to send and read data from the watch are held in a handy struct: WatchConnectivityHelper, and an instance of this struct is held by the AppDelegate. We need a way to be notified when a change occurs on our database, so that we can trigger an update to the application context. As I mentioned before, Realm makes this pretty easy, thanks to Realm Notifications. Soon after the session is set a new Realm notification is created (the token needs to be strongly held):

realmNotification = watchConnectivityHelper.setupWatchUpdates()

setupWatchUpdates implementation is straightforward:

/**
Updates data on WatchOS, and listens for changes
- Returns: RLMNotificationToken that needs to be retained
*/
public func setupWatchUpdates() -> RLMNotificationToken {
// Send the current data right away
sendWatchData()
return EntryHandler.sharedHandler.realm.addNotificationBlock { note, realm in
// Once a change in Realm is triggered, refresh the watch data
self.sendWatchData()
}
}

This opportunistically sends the current status right away, and creates a new token that, once a change is triggered, calls again the method that sends the application context.

This is a good time to think about what we really need on the watch, and model our application context accordingly. We want to keep the data transfer at a minimum to avoid lengthy transfer times, while having all what we need at hand.
For my purpose all I need is the current user status, his daily goal and his portion sizes (they might change over time, so they need to be refreshed often).

Since we are implementing all this in the Extension delegate, to update the interface (in the off chance that the user is staring at both his phone and watch with both apps running) we toss a notification through the NSNotificationCenter, letting the interface controller handle that with an animation. Another approach would be to force a reload of the interface controller, but that would prevent such animation.

Luckily the communication between watch and phone works pretty much the same way.

You’ll notice that once the application context updates I also reload the complications, let’s talk about that.

Life is not that complicated

Complications are elements that live on the watch face and can be customized by the user. There are different kinds of complications with different sizes, depending on the space that they are displayed on. These are the possible complication families that we can implement:

Complications are provided by a single object that implements the CLKComplicationDataSource protocol. This object is declared straight in the watch app’s Info.plist file, and gets loaded automatically by the system.
A single complication can offer a static snapshot of the current situation (the current temperature, your activity data, or in Gulp’s case the current daily goal’s completion rate), and it also can offer time travel features, allowing the user to nudge the digital crown to have a past or future snapshot. Time travel is great for apps that already know the future, but won’t fit the bill with Gulps, so you won’t see its implementation here. If you want to learn more, jump to the end of this post for a bunch of references.

CLKComplicationDataSource

In our case the datasource methods that need an implementation are these two:

The first function requests a template for a given complication type. A template is a simple static placeholder that is shown to the user while he’s configuring the watch face. The second function requests the current complication that needs to be loaded. They both require you to call a completion handler with the correct object for each complication you support. You declare the support to a given complication type in the project’s settings.

Pretty mundane bit of code, we check which complication family was requested, and we provide one. Complications have many settings and preset types, so I encourage you to check Apple’s reference guide.

The final complication setup doesn’t differ too much from the template, beside the obvious current value that replaces the pre baked placeholder:

Reloading complications

So, the user fills his progress, goes to sleep, picks up the watch in the morning and… there it is… his previous percentage still showing.
Finding a way to reset the percentage wasn’t that straightforward, since I’m only refreshing the complications when a new portion is added.

As it turns out though, the data source protocol holds a pretty handy function:

/** This method will be called when you are woken due to a requested update. If your complication data has changed you can
then call -reloadTimelineForComplication: or -extendTimelineForComplication: to trigger an update. */
optional public func requestedUpdateDidBegin()

A-ha! WatchOS asks your complications how they are feeling every once in a while… so kind of him. We can use this opportunity to reset the complications:

You can head to the GitHub repo of Gulps and compile it, or even better download it from the store, and you’ll notice that the WatchOS app is a lot snappier, and the communication time between the two devices is pretty fast.

I’m pretty happy with it, but it required a good dose of patience. WatchConnectivity works great when you are learning it with a simple demo app, but once you factor in an app just a little bit more complex, you’re in for a treat. In the end it all boils down to figuring out what needs to be transfered and when. It doesn’t help that getting the app compiled on a real device requires quite a lot time. You’ll be seeing the loading spinner A LOT, soldier on.
With that being said, in the end the app runs way smoother, so it’s all worth it.

References

You can read more on the WatchConnectivity framework in this article by Natasha Murashev (who was also kind enough to contribute to this project), this one by Kristina Thai or Raywenderlich’s one written by Mic Pringle.
Also Raywenderlich’s “watchOS 2 by Tutorials” was of great help, consider picking it up if you want to delve deeper into WatchOS development.

]]>2015-06-19T12:35:31+02:00http://fancypixel.github.io/blog/2015/06/19/playing-with-uidynamics-in-ios-9UIDynamics was a welcome addition to the iOS 7 SDK. It’s basically a physics engine backing common UIViews, allowing us to define physics traits to the UI elements. The API is fairly straightforward, so you can easily create animations and transitions that look and feel great. I already covered the basics in this article a while ago, this time we’ll be looking at what’s new in UIDynamics in iOS 9.

Collision Bounds

The first release of UIDynamics shipped with a collision system (provided by UICollisionBehavior) that only supported rectangular bodies. It made sense, since UIViews are backed by rectangular frames, but it’s not uncommon to have a circular view, or even better our own custom Bezier path. With iOS 9 a new property has been added to the UIDynamicItem protocol: UIDynamicItemCollisionBoundsType, which accepts one of these enum values:

Rectangle

Ellipse

Path

The property is readonly, so if we want to change it we need to provide our own subclass:

This covers round views, if we want to get fancy and draw a more complex view with a coherent rigid body we can use the enum property .Path and also override this property:

var collisionBoundingPath: UIBezierPath { get }

The path can be whatever you can think of, as long as it’s convex (this means that for any given couple of points inside the polygon, the segment between the two is always entirely contained in the polygon itself) and counter-clockwise wound.
The convex requirement could be a significant limit, so UIDynamicItemGroup was introduced to specify shapes as a group of different shapes. This way as long as each shape in the group is convex we are fine even if the resulting polygon composition is concave.

Field Behavior

Field behaviors are a new type of behavior that is applied to the whole scene. The most common example that we’ve been using implicitly all along is UIGravityBehavior, which applies a down force to each item in the scene. Now we can use a new set of field forces, like Radial (the forces are stronger at the center and weaker around the edges), Noise (forces with different magnitudes are scattered around the field), and so on.

Dynamic Item Behavior

UIDynamicItemBehavior received a couple of interesting new properties:

var charge: CGFloat
var anchored: Bool

charge represent the electric charge that can influence how an item moves in an electric or magnetic field (yeah, it’s bonkers), while anchored basically turns a shape into a static object that participates in the collisions, but without response (if something crashes into the item, it won’t budge), so it’s perfect to represent something like a floor or a wall.

Attachment Behavior

UIAttachmentBehavior was revamped and now has a sleuth of new methods and properties, like frictionTorque and attachmentRange. The attachments can now be more flexible, we can specify relative sliding movements, fixed attachments, rope attachments and what I like the most: pin attachment. Think of two objects nailed together and you get the idea.

This more or less covers what’s new in UIDynamics, now it’s time to drop the changelog and start building something silly.

Let’s play ball

I’ve been spending a lot of idle time with Ball King in the last week. It’s a brilliant little time waster, the concept is simple but well executed. Also it adopts the same monetization policies of the Apple design winner Crossy Road: it doesn’t bother the player in any way. Kudos.

One thing I really like about it is the physic model of the ball and how the hoop’s backboard reacts when it gets hit by it. Looks like a fun exercise to test out the new UIDynamics stuff listed above. Let’s take a step by step look at how to build our own scruffy version: BallSwift

The hoop

The basket can be created with a single UIView acting as the backboard, a couple of views with rigid bodies as the left and right arms of the hoop, and a frontmost view as the hoop itself (without a physic body). Using the previously defined class Ellipse we can create the visual representation of our game scene:

Nothing new here, the hoop is created programmatically and is placed in the constant CGPoint hoopPosition. The order of the views is important though, since we want the hoop to be above the basket ball.

Nuts and bolts

The most important part of the hoop are the left and right arms. They need a physical round body (so that the collision with the ball is smooth) and need to be bolted to the board and the front hoop. These two will be basic UIDynamicItems and won’t partecipate directly in the collisions. The newly introduced pin attachment is perfect for this job, it can hold everything together quite nicely as we can see in this rather ugly drawing:

The pin can be attached only to a couple of views at a time, within a given absolute spatial point:

If you’re not participating in the race to Swift’s functional awesomeness you’re probably not familiar with zip and map. It might seem contrived at first, but it’s rather simple: each view is coupled with the offset point in which we’re going to pin the attachment, resulting in an array of tuples that is then used in the map function that, as the name suggests, creates a mapping with each element of the array with the provided closure. This results in both the left and right arms of the hoop to be bolted to the board and the front hoop as follows:

Left arm bolted to the left of the board

Right arm bolted to the right of the board

Hoop bolted to the left of the board

Hoop bolted to the left of the board

The next step requires us to hang the board, letting it rest loosely, so that a collision can cause it to swivel a bit like it does in Ball King:

In this bit of code I set the elasticity (how much it should bounce after a collision), density (think of it as the weight) and a handy action closure that resets the world state when the ball exits the play area (the main view).

Collisions and gravity

I mentioned the new anchored property of UIDynamicItemBehavior, which disables the dynamic behavior of an object while keeping it in the collision’s loop. Sounds like a great way to build a steady floor:

The gravity is a field behavior that applies a down force of 1 point per second as default. The collision behavior takes as parameter only the views that should collide with each other. The world is set up, now we can apply an instantaneous force to the ball and keep our fingers crossed:

And there you go, it’s really rough around the edges, but that was a lot of fun to build (yes, the clouds and the bushes are the same drawing, like in Super Mario).
As always you can find the source on our GitHub page.

]]>2015-06-11T11:03:06+02:00http://fancypixel.github.io/blog/2015/06/11/ios9-notifications-and-text-inputWhen iOS8 opened the API to have actionable notifications many of us were disappointed that the text input action used in Messages wasn’t available. It turns out that with iOS9 this API is now public, although as I’m writing this the documentation doesn’t mention it. After some digging in the UIKit changelog I was able to build a sample making use of this new behavior.
Like with iOS8 the NDA is more relaxed this year, but it still forbids showing screenshots. In any case, you’ll find the full sample on GitHub.
Let’s take a step by step look at what changed.

Requesting the permission

First of all we need to ask the permission to the user before we can start sending notifications. We start off by building a new UIMutableUserNotificationAction, that alongside the main properties of the notification will also specify the desired behavior:

And that’s it. A welcome addition to the API, let’s hope that all the major messaging apps will adopt it soon.
You can find the full sample here. Once you run the app and schedule the notification, hop back to the home screen and you’ll be able to reply with some text, that will be displayed in the app’s view controller.

]]>render :json => the_simple_way]]>2015-06-01T14:50:41+02:00http://fancypixel.github.io/blog/2015/06/01/apis-with-rails-render-json-the-simple-wayLately my work at Fancy Pixel has focused on the backend of a product we’re about to launch and for which we decided to build a JSON API-only server. These APIs can be consumed from third party clients/services but are also used by our frontend. In this short report I’d like to share with you the simple solution that we’re using for the JSON generation and that in my humble opinion can be a quick and easy alternative to most commonly used systems like Jbuilder or ActiveModel::Serializers.

Rails, one of my favourite work buddies that I happened to use several times on projects that included the development of APIs. Due to personal curiosity, during the years I had the opportunity to try several solutions for JSON generation and I have to say that sometimes I found some difficulties with certain tecnologies: great for the majority of their functionalities sometimes they may force you to take weird paths to achieve the desired result. To be honest, the main reason for this continuative experimentation is probably the constant search for the top balance between comfort/ease of use/development-speed and performances and after all this test and try I arrived to the current solution, that probably is not something new, but that in my opinion can give somebody an alternative idea combining together great flexibility and bare metal performances.

To cut a long story short…

I don’t want to dwell with epic tales or “disquisitions about the gender of the Angels” so I built a trivial demo app that you can find on our GitHub account, to show you what I’m talking about.

For the purposes of this article I decided to use rails-api (if you don’t already know it I reccomend you to give it a try) instead of standard Rails, for the simple fact that this is what we’re using right now in the project I mentioned at the beginning of this post. Obviously the same concepts apply identically to vanilla Rails.
Let’s open together the code and take a rapid look at it: as you can see these few lines of source do nothing but respond to three routes and if you take a look at config/routes.rb you’ll find something like:

As you can see I’ve set json as the default format and I defined a namespace in such a way to replicate a typical process of APIs versioning.
Let’s jump to the only existing controller (comparison_controller) where we find the implementation of the actions called from the routes. Each of these actions does exactly the same: load a bunch of records from the DB and render it as JSON, but each one does the rendering in its own way i.e. using respectively jbuilder, ActiveModel::Serializers and “my solution” that I’m going to call “simple”… what a fancy name uh?

We’re not going to focus on the first two systems, because chances are that you master those tecnologies better than me already and, also, there is nothing out of standard in my implementations, but instead we’re jumping feet together to the simple action. Like the competitors, it does nothing more than render some JSON, but this time the serialize_awesome_stuffs helper method is called. This method is defined in the V1::SimpleAwesomeStuffSerializer module that is included by the controller. You can find the module under app/serializers/v1 and if you’re going to open the file you’ll notice that it’s just a plain Ruby module defining methods.

Both the methods do nothing more that returning an Hash defining key-values couples that we’re willing to return as JSON. In particular serialize_awesome_stuffs creates an Array of Hash and internally, just for DRYing things up a bit, calls serialize_awesome_stuff (singular). Maybe the overall naming is not the best in the world, uh? Bonus point: defining the method’s parameter awesome_stuffs = @awesome_stuffs allows us to make our code lighter and more readable, because if we remained adherent to conventional variable naming, probably our controller is defining something like @awesome_stuff (and as a matter of fact, we did) that is directly visible and usable by our module. If we’re going to have a bout of creativity and want to use our personal variables names, we won’t have any sort of problem.

Now that everything is prepared, let’s follow some of the steps we’d usually do during an API creation. Let’s create a UserController through which return to the client also user’s associated awesome records™.
Create users_controller.rb` underapp/controllers/v1/and addindex“` action:

As you can see I already added some stuff that we’ll need in short, that is the V1::UsersSerializer module. If you haven’t already, notice the scoping (V1) of our serializers: in doing so we can follow the evolution of our API’s versions with no hassles, possibly going to redefine the behavior of only serializers that may change.
Do not forget to add new routes:

What you’ve seen so far is a simple example of what it’s possibile to do with the tools we already have at hand and mainly wants to be an idea for those wo are constantly looking for the best performances and simplicity.

We reached the end and I hope I have not bored you too much, but if you got to this point, I probably didn’t :)
What you have seen today may or may not be liked, but I personally find it a surely performant system that offers pure modularity, extensibility and code reuse.

]]>2015-04-13T21:26:20+02:00http://fancypixel.github.io/blog/2015/04/13/gulps-new-open-source-watchkit-appWe released a new app on the AppStore and decided to open source it. The app is called Gulps, a simple tracker of your daily water consumption. Gulps was a fun little side project built to learn a bit more about WatchKit and to strengthen my Swift-fu.
If you read our latest post on how to share data with Realm, you’ll find a lot of code in common in this app, but there’s also quite a bit of new stuff that’s worth checking out. For starters I personally really like the water meter that follows your device movement, made possible by the amazing DPMeterView. You might also like the Facebook Paper-like wavy effect in the onboarding, provided by one of my pride and joys, AMWaveTransition.
You’ll find the source here.

]]>2015-03-29T15:00:32+02:00http://fancypixel.github.io/blog/2015/03/29/share-data-between-watchkit-and-your-app-with-realmIt’s been a busy year for iOS developers. We got a slew of new toys to play with: a new version of iOS, new frameworks, a new language, new screen sizes and some new hardware to put on our wrists, just as soon as we thought that watches were anachronistic.
New technology is always exciting, but keeping up to date can be a daunting task when deadlines keep getting closer. Lately I’ve been taking some time off to delve deeper in these new topics and build a simple app out of it (that we are planning to open source). At the time of this writeup the app is still waiting to be reviewed, so we’re going to just focus on something that I learned in the process and that can be useful to a lot of other iOS devs: sharing data between your app and its WatchKit extension, using Realm.

Why Realm

Realm is a great replacement for both SQLite and Core Data, it offers a quick and painless way to persist data in your iOS (and Android) app. The thing that makes it so great is the ease of use, it reduces your boilerplate code to next to nothing (I’m watching you, Core Data), keeping things at a high level of abstraction (I’m watching you SQLite) and… it’s fast. It really is a brilliant piece of software, and I urge you to checkout the official documentation if you’re in need of a persistence framework for your app.

The sample app

We’re going to learn how to share data between an app and its WatchKit extension, and what better way to use a sample app as reference?.
I’m not a fan of TODO app demos, they always feel… unimaginative… but I have to admit that they are the perfect sample for a task like this. So, bear with me, let me introduce to you another TODO sample app: Done!, a simple TODO list where we can add items and mark them as done from our Apple Watch.

Setting up Realm

WatchKit extensions are just another target inside your app, just like Today extensions, so they are packed alongside your app, but they have their own life, and most importantly, their own bundle identifier. This means that data stored within an app is not visible to the extension and vice versa. Apple offers a way to solve the issue through app groups.
App groups, like bundle identifiers, are defined by a reverse URI and they are prefixed with group.. They let you share data between your apps and are tightly bound to your provisioning profile (luckily Xcode handles their creation in your developer portal with ease).
We can take advantage of that to create our Realm database in a shared space that will be visible (and writeable) by both our app and the app’s WatchKit extension. Let’s start by creating the group in our project’s capabilities section:

Once this is out of the way we can tell Realm to store the database inside the group.
We’ll do so in our AppDelegate’s application(application: didFinishLaunchingWithOptions launchOptions:) function:

If you worked with Core Data in the past you should have a better understanding of my claim “less boilerplate code”.

WatchKit

Ok, new technology, new framework, so much to learn, right?
Well, it turns out that Apple did some thinking on this, and for what I witnessed, developing a Watch app is going to feel familiar for a lot of Cocoa and Cocoa Touch developers, albeit with some significant philosophical changes. First things first, let’s create a new target holding the Watch app:

Then, the layout. We won’t be using Autolayout, but something reminiscing a simplified version of Android’s linear and relative layouts (no need to touch beefy XML files though, storyboards are still there for us). The layout for this will be a WKInterfaceTable with a custom TableRowController, holding a WKInterfaceImage and a WKInterfaceLabel:

The custom TableRowController is a plain class with a couple of properties, so let’s take a look at this first:

That’s a little different from what we’re used in UIKit. No delegate nor dataSource, in WatchKit we explicitly define every row before showing the table.
Also, as you can see in the awakeWithContext function, we are setting up Realm as we did in the main app. As a side note, the pieces of code that are shared between the two targets (in our case, everything concerning the model) should be moved in a custom framework to avoid code duplication. For the purpose of this sample I opted to duplicate the Realm initialization and shared the model between the two targets, but in a more structured app I would definitely take the framework route.
If we build and run we can add an item on the phone, and once we reload the app we’ll see the same item in the watch extension too.
That doesn’t feel very responsive though, right? We’ll fix that in a bit, but first let’s add the ability to mark an item as done from the watch:

That pretty much covers it. Right now it’s even more apparent that even if the two apps are communicating, there’s no real sense of interaction, since we need to reload the app to see the changes.

Syncing data

We need to somehow advertise that our watch app or our main app performed something meaningful. There are official ways to do that, and you can read more about them on this blog post from Natasha The Robot, but in this case I want to show you how a brilliant library called MMWormHole can abstract this task for us.

MMWormHole

MMWormhole creates a bridge between an app and its extensions. The API is clear and concise and it has a delightfully geeky name. It works like a pub/sub system, one end registers its interest for a kind of message (defined by a string identifier), and the other end can broadcast a new event. When the event is raised the subscriber’s handler is fired. Sounds like something we can leverage from our app. Let’s start by registering interest in watch updates on our main app:

And that’s it. When something changes in our model we just need to call these function:

// From the watch
self.wormhole.passMessageObject("update", identifier: "watchUpdate")
// From the main app
self.wormhole.passMessageObject(someObject, identifier: "mainUpdate")

Realm notifications

Update

Once this post was live, Tim Anglade from Realm reached out to me and was kind enough to point out that there’s a built-in notification system in Realm, so MMWormHole in this case isn’t really needed. The API is really easy to use and requires no configuration, here’s how it works:

As long as we keep a strong pointer to the token, the system fires the notification block as soon as a write transaction is committed. You can find the updated code in the sample app.

Demo

Here’s the demo app in all of its glory:

As you can see it’s really easy to bootstrap a simple app for WatchKit, and thanks to a couple of great open source libraries adding persistence and interactivity is a painless effort. A big thank you to both the Realm team and Mutual Mobile for the amazing work on MMWormHole.

]]>2015-01-30T15:40:43+01:00http://fancypixel.github.io/blog/2015/01/30/react-plus-flux-backed-by-rails-api-part-3This is the last part of “React + Flux backed by Rails API”, make sure to check out Part 1 and Part 2 if you have missed them.

In part 1 we built a Rails API for a tiny clone of Medium, called appropriately Small. In part 2 we went through the setup of a React app with a Flux architecture, and built our authentication workflow. We close this series by providing the list of the stories and a creation page, protected by authentication. A note of warning: this is a quick and sometimes naive implementation, its main purpose is to show you how to get started with React and Flux, that’s why we didn’t put too much effort in handling possible errors or, for that matter, even showing progress indicators.

Listing stories

Looking back at our routes, I defined a default route, mounted under /stories, handled by a component called StoriesPage. This component will abide the flux architecture, therefore its only goal in life will be displaying data fetched by a store, and re-render when something has changed. Before diving in this component, let’s create a store then:

At this point this should look familiar, we define our private state, the properties to access it from outside, and we register our callbacks. Once a new action tagged RECEIVE_STORIES is dispatched, we take the content of the payload, store it in the store’s state and emit a change. The RECEIVE_STORIES is generated when WebAPIUtils receives the XHR response from the server, just as the login process. What component does fire this AJAX request though? That’s a view action, initiated by the user when he requests the /stories route. Here’s the component of this route handler:

In this component I took advantage of the componentDidMount function to start the asynchronous request to our API. The stories are then retrieved from the aforementioned StoryStore and held in the component’s state. In the render function I took the chance to show you a more React-y way to write a view, with modular and reusable components. These component might also live in separate files (or even projects), but for readability I put them in the same file. As you can see the page renders just one component, StoriesList, passing the stories list as props. The StoriesList uses the .map function to render one StoryItem component for each item in the stories array. Note how I needed to specify a unique key for the item (you could use an index as I did or even the story’s id), this helps React keeping track of what element changed.
The last element of the chain is the StoryItem component, that renders the props provided by its parents. You might notice the weird css class names, bear with me, I’m trying to get accustomed with the BEM methodology.

Loading a story

If everything has gone smoothly we should see a list of stories, something like this:

What happens when I click a story? Looking back at our StoriesPage we have this bit of code:

This means that once we select an item from the list, the router will switch the current component (or handler) with the StoryPage component, passing along a query parameter named storyId. Our StoryPage will then be able to get that id, and create a new action, requesting the download of the selected item. As usual the request will be handled by the WebAPIUtils, the response will be encapsulated in a new action, handled by the store, that emits the change, ending with our StoryPage refreshing its content. If you followed along you should have this pattern memorized by now. If so, you have the Flux architecture figured out.
Just for kicks, here’s the StoryPage:

In the render function we defined an html form with a text input and a textarea. Notice the ref property of those tags, its value is the binding we’ll use to retrieve their content when the users submits the form, using the getDOMNode() function. The submit once again kickstarts the Flux chain, by creating a view action. There’s one thing to note here: posting a new story is an action performed by an authenticated user, so our WebAPIUtils method will look like this:

Notice how we are passing the user’s access token in the request header. That’s it, our Rails API will authenticate the user thanks to that header, and the action will be performed.

Wrap up

This concludes this tiny application. As stated above, this is a naive implementation, not meant for production, so I didn’t cover too much the error handling, the user feedback when the app is loading, or the testing.
You can find all the sources here:

Flux vs. Fluxxor vs. Reflux vs…

Flux is not the only implementation of this architecture, you can find several libraries that do so, some of them are tied to React, some of them aren’t, some of them don’t even use the whole architecture. It’s just a matter of preferences, you can checkout this discussion on GitHub for more info. Personally I chose vanilla flux to have a better understanding of all the underlying components, once you figure that out, there’s always time to trim out the fat.

The future of React

While I was writing this the React.js conf took place, you can find a summary of what they announced here. The most exciting thing was probably React native. Being an iOS developer at the core I always frowned upon web frameworks with native capabilities like Phonegap or Rubymotion, but if you take a look at this presentation it’s hard not to be excited about React native. The thing that strikes me the most is that they nailed the core concept: forget “Write once run anywhere”, embrace “Learn once, write anywhere”.
React is here to stay, and it’s already influencing every other JS framework around. I’m excited to build future application with it and see how it’s going to expand in the future.

]]>2015-01-29T10:31:00+01:00http://fancypixel.github.io/blog/2015/01/29/react-plus-flux-backed-by-rails-api-part-2This is the second part of “React + Flux backed by Rails API”, make sure to checkout Part 1.

In part 1 we created our fancy Rails API, setup the authentication and defined a resource for our tiny clone of Medium.
Time to reach the core of this post: the frontend built in React with the flux architecture.

Setting up the frontend

The whole idea behind splitting the backend from the fronted is to treat the web UI as a first class citizen, sitting in its own folder, in its own repo, with no bindings to the backend. The backend can be easily interchanged, as long as the API specs remain consistent. So we’ll create a new app from scratch. We have the option to use automated tools like Yeoman, but I wasn’t able to find the solution that fit all my needs.

Tools

I’ll be using node’s NPM to fetch the main tools, Gulp for the build and watch tasks, and Bower for the resources.
Before diving in the details, I have to warn you, I’m awful with gulp, so I pretty much gathered tasks around the web. So take my gulp file lightly, I’m planning on fixing all the horrors as soon as I can. You might also notice that I didn’t use ES6, although I wanted to. I encountered in a couple of issues while working with ES6, so being time in short supply, I switched to vanilla Javascript.
You’ll find the package.json and gulpfile.js in the sample repo, to make a long story short we’ll be using react (obviously), react-router, superagent for the ajax calls and flux.
As I said before, Flux is just an architecture, so what am I importing really in my package.json? Turns out that Facebook released a small library called flux that contains basically the code for a Flux Dispatcher (more on that later), that will cut down the amount of boilerplate code that we’ll need to get started.

Flux Architecture

If you already took a stab at Flux you might know this diagram:

It might not be easy to understand at first, but it makes more and more sense while you are implementing all those coloured blocks. Let me shed some light over it if I can.

The leftmost block is our Web API, we built that in the previous part of this blog post, so we are set. Our API will be called by the “Web API Utils”, that’s just a plain JS file making ajax requests. Eventually this JS component will receive an AJAX callback, and it’ll need to update our frontend app. It does that using Actions. An action is just a data structure that tells the system what happened and what payload is associated with that action.
There are two types of actions: the one initiated by a server (e.g.: an AJAX callback) and those initiated by the views (e.g.: the user clicks a button). The difference between the two is basically semantics.
The actions are created through Action Creators, that are really just utility functions that build the action and toss it to the system, or to be more precise, the dispatcher.
The dispatcher is a single object (one per app) that, as the name suggests, dispatches actions to those who registered interest in them. Look at it as a pub-sub mechanism, plain and simple.
The objects that register interest in this actions are called Stores. Stores contain the application logic and state. They are similar to a model, but they manage the state of all the objects, not a single record.
Stores are the one offering the state that will be presented by the React views. React views should hold as few state as possible, they should grab the state of the data from a store, and pass the state to their children as props.

That’s it really, it seems rather convoluted at first, but an example can clear the fog, let’s consider the login process:

The user enters his username and password, and clicks Login

The React view handles the click event, grabs the content of the fields and creates an action through an action creator, with the tag LOGIN_REQUEST and a payload with the user’s credentials

The Action creator creates the LOGIN_REQUEST action with its payload attached, and alerts the Dispatcher

The Web API Utils receives the JSON and creates a new action, called LOGIN_RESPONSE, with the new JSON as payload.

The dispatcher is notified, and forwards the action to the store(s) that is(are) interested in a LOGIN_RESPONSE action

The store (e.g.: a SessionStore) gets notified and extracts the payload from the action

The store updates its state (username, auth token and login state set to true)

The store emits its changes

The React views are notified of the changes and can be refreshed

The React views can grab the state from the store, and if needed pass the state to their children

And that’s it. Looks like a lot of work for a simple login, but the secret sauce that makes Flux work is that this pattern can be applied to every action performed by the user or the server. It keeps the main components decoupled, it’s easier to maintain, and best of all, everything is tidy, for once.

That’s our first taste of React and JSX. JSX is a JS extension that lets us write nodes with a syntax similar to XML. It’s optional, but it cleans up the syntax and can be handled with ease by designers.

Routes

router.jsx holds all of our routes that will be used to instantiate react-router:

Routes are expressed in JSX syntax, we can specify a name (that will be used to perform transitions and to create links), an handler (the React component that will be mounted when the route is visited) and an optional path (that the user will see in his address bar). As you can see we can also mount routes inside another route in a RESTful way.

Dispatcher

The dispatcher is the core of the app, it’s the central hub for our messages (actions). It’s also a fairly easy component to implement, it’s mostly just boilerplate code:

We are basically defining two main methods that will be used to dispatch a message. We use two instead of one just for semantics: one will handle the dispatch of server-initiated action, the other one the view-initiated actions.
Before proceeding to the meat of the implementation we’ll take a look at the Constants file:

This is an utility file that holds the constants that we’ll use throughout the project, mainly the API endpoint and the types of action that we can perform in our app.
Now, let’s talk about the authentication process.

Authentication

As explained in the Flux example above, the data flow will be initiated by the user, that will visit the login page, fill a form with his credentials and click on submit. We’ll handle the submit as a VIEW_ACTION, this means that our view will call a method of our action creator for the session. Let’s take a look at it:

This cover all the user-initiated actions in the context of the session. The login action creator as you can see creates a new ViewAction, attaching a payload with the user’s email and password, and then calls the WebAPIUtils.login method. If other components registered their interest in receiving the LOGIN_REQUEST action, the dispatcher would deliver this action right now.
The login method of our WebAPIUtils class is this:

A common pattern should start to be apparent right now: no class is directly modifying the state of another one, but they are just creating new actions. That’s the Flux way of handling data in a nutshell.
To keep things tidy the actions for results of the login process are created in a separate action creator:

And this covers the server and view actions for the login process. Who handles the result though? Let’s talk about stores.

SessionStore

Stores are like a mix between a model and a controller, they handle the data, the main state of the application, feeding the records to the views, while retrieving the data from a server. We are about to see the SessionStore, which keeps track of the current user (and holds his access token, used in the API calls) and listens for the LOGIN_RESPONSE action.

That looks like a bunch of code, but most of it is boilerplate, the interesting part is in the .register function. When the store receives the LOGIN_RESPONSE action unpacks the payload and checks wether the login was successful or not. It then updates its state (that will be accessed by the public properties declared on top of the file) and notifies a change to whomever might be listening (that’s why we import node’s EventEmitter and merge the class with it).
Ok, we have the ability to send a view action, we receive the result and store it, cool, now we need to use this store somewhere and show some UI already.

Application

Having a store and a state brings up a tricky question: who should listen to its changes and who should use its state? Following the React philosophy we should find the component at the topmost of our view’s tree, without bloating the component itself though. As far as session goes I think the best place is the root of our app. The root is the first component that is mounted by the routes, and if you take a look at our routes, that would be the component called SmallApp:

This is a really simple component that serves as the root layout. If you take a closer look at the render function you can see that it only renders a React component named Header and then mounts the content provided by the Router. The header has a couple of properties though (React props to be exact) and we fill them with the SmallApp state. Those props will be accessible within the Header component. The SmallApp state is obtained by querying the SessionStore in two ways:

by the function getInitialState, fired when the component is initialized

by the _onChange function, called when the Sessionstore emits a new change.

The latter behaviour is possible since the SmallApp component registered its callback in the function componentDidMount, that is fired, you guessed it, when the component is mounted in the page.

Small recap: the user initiates a view action, the WebAPIUtils calls the server, the server replies, a new action is raised, the dispatcher forwards it to the SessionStore, which updates its status and emits a change event, catched by the SmallApp component. The SmallApp component forwards its state to its child: the Header component. Wew! Let’s close the circle by writing our Header:

As you can see we are finally defining our markup. Within this markup you might notice a couple of calls within curly braces, that references this.props. This object is filled with the properties declared in the previous component, so that’s how a parent can forward informations down the chain of its child components. No more two way bindings, the data just flows from the root to the leaves. Also, React offers the ability to validate the props, by specifying the propTypes. Whenever we pass a prop to a component, React checks the data type, and raises a JS warning in the inspector’s console. That’s a handy debugging tool that improves the reusability of a single component.
It’s apparent how we are defining our views in a declarative way. Once defined we are not handling the state with a barrage of spaghetti jQuery calls, we keep in mind that the view will get refreshed down the line.

It does look convolute at first, right? The Flux architecture becomes awesome once you realise that every interaction follows the same principle, then everything clicks in your brain. Noticed the logout function in the Header? It doesn’t make a reference to the SessionStore, the Header doesn’t even know it exists, it just follows a pattern: “when something happens, create an action”.
The code is decoupled, the responsabilities are separated, we can achieve modularity and reusability. For real this time. Brilliant.

LoginPage

We covered the server action, but we still need to let the user perform the login action. Let’s fix that. You might have guessed it: we’ll create a React component that will fire and action when the user submits the form.

As you can see we have our boilerplate declaration of the change callback at the start of the file, that’s pretty common. You might also notice that this component has its own state, unlike the Header. This is because I felt that the login error (retrieved by the SessionStore) belongs in the page itself, since it’ll be rendered there, and there’s no need to let it have a broader scope by integrating it as a state in the main SmallApp component.
Getting back to the login process, the render function defines the markup of our login form, and on submit the component will retrieve email and password, and create a new action with them. That’s it.

Next up

It might be a good time to take another break, in the next part we’ll go through listing and posting a new story in our app, and then it’s conclusions time. I’ll see you soon.

]]>2015-01-28T16:04:00+01:00http://fancypixel.github.io/blog/2015/01/28/react-plus-flux-backed-by-rails-apiI’ve been working on a frontend for a project we are developing here at Fancy Pixel. We are embracing what looks like a good habit: slicing what would be a monolithic Rails app in a lightweight backend serving APIs and a frontend consuming them. We did this in the not so distant past using Angular.js. It was all fine and dandy, until it wasn’t. There’s something about it that doesn’t sit right with me, I wouldn’t go in detail, since many others already did, but let’s just say that there’s too much magic involved for my tastes (says the guy using Rails). Magic is fine as long as I can figure out how to tinker with the internals when things go down south. With Angular the effort seems too much, but that’s just personal taste really. Also I can’t deny that the major structural changes introduced in 2.0 were the last nail in the coffin.
I wanted to try something new, something that would enforce a solid architecture of our apps, letting me control the single cogs in the engine. React got a lot of good press in the past months, so I took the chance to dive in. In this three-part post you’ll find pretty much everything I learned by writing a frontend using React, with a vanilla Flux architecture, consuming an API written in Rails.

Choosing the backend

Given our experience, the obvious choice for us was Rails, but with a twist: rails-api. Rails-api is a stripped down version of Rails, where most of the ‘useless’ middleware is not included (but you can include it might you need it). Using Rails to serve JSON might seem overkill to most, but the Github page of rails-api has some really good points to counter this argument, and I think they are spot on.
TL;DR version: Rails is awesome, let’s take advantage of that.

The frontend technology

React is javascript library for building user interfaces built and open sourced by the Facebook’s engineers. Its major selling point is the ability to provide a dynamic and fast way to build isomorphic apps.
Isomorphic means that the app can be rendered with ease on both the server and the client, which helps with SEO.
Personally, I couldn’t care less about SEO, even if I understand how important it is… I was really sold on React by the Virtual DOM and how the data is organized and handled in React views.
The Virtual DOM is something that we’re going to see implemented in other JS frameworks (Ember does that already if I’m not mistaken). The views can be rendered on the server for the initial request, than the underlying tech is going to render subsequent pages in a Virtual DOM, that is then diffed with the actual DOM, and then only the differences are changes in the visible page. And it’s fast. Brilliant. This enables us to start writing frontend like we used way back: in a declarative way… we just specify how the UI should look, when data changes React takes care of the page refresh, changing only the parts that need to be changed.

Flux

This covers the backend and the views, we’re missing something in between, say, an architecture to follow. Flux is an architecture for building web UIs, and works really well in combination with React (but it can really be applied anywhere).

Here comes trouble

I never was a big fan of implementing web UI, CSS always gets messy, Javascript files become scary monoliths where crappy code goes to die, while developers test their spelunker skills and loose their sanity. Maybe I’m just crap, but even using Sass and Coffeescript never really solved my issues.
I was excited to try something really new, but I knew that getting started with such a young technology would end up being a major pain in the ass.
Case and point, learning and starting being productive (i.e.: writing usable code) took a fair bit of head scratching. There’s still no clear “best practice” to perform common tasks, nor a clear starting configuration. Let’s put it that way, if you come from the RoR world, where convention over configuration greatly reduces boilerplating and “forces” you to follow commonly established best practice, you’re going to struggle with Flux.
This post will cover the solutions we came up with, they may not be perfect, but I’m fairly sure there are no anti-patterns in there, and they are a solid starting point.

Getting it all toghether

Let’s start writing some code. We’ll go through a simple Rails app that will feature user signup and login, and the ability to post a story. Just like a tiny Medium. Let’s appropriately call it Small.

Feel free to skip the Railsy part if you’re only interested in Flux and React and jump to Part 2.

Rails API

A while ago I stumbled upon this article by Alan Peabody. I had a similar experience as him, you start working ona project, you use the right tools, you do your best to enforce good patterns, but in the end the frontend code just becomes scary, something no one wants to maintain. Let’s break up with the asset pipeline, as the title says, and work towards making Rails beautiful again.
We’ll be using the rails-api gem for this task. You can generate a new app with its CLI command, or you can integrate it later. I’ll do the later option, no reason really, just a habit.

rails new small

Next we’ll add rails-api, devise, active_model_serializers gems to our Gemfile, and while we are at it we can remove all the gems that generate assets or view content, jbuilder included. Our Gemfile should look like this (test section omitted):

Now we need to change the application controller so that it inherits from ActionController::API, and kiss the protect_from_forgery goodbye. Since we are serving only JSON, it makes sense to add

respond_to :json

to the applciation controller, helps DRYing all out. While we are at it, we might as well delete the assets and views folders, we won’t need them.

Authentication

Should I first define a resource? Maybe, but that’s trivial, let’s get the authentication out of the way. We are building an API, so no session will be involved, we have to authenticate the user in each request. I’ll be using Oauth2 Resource Owner Password Credentials Grant which sounds fancy, but it’s really just a token in the request header that authenticates the caller.
The gem Devise used to implement a token_authenticatable strategy, but it was pulled for security reason. There are gems that implement the strategy (like Doorkeeper), but since it’s fairly easy to implement I’ll do it for myself. Let’s install Devise first by adding it in the Gemfile and launching rails generate devise:install after a bundle install, then we create the user model:

rails generate devise User

Token authentication

Token authentication was removed from Devise a couple of years ago, this link explains why. We have to implement it for ourselves, but it’s quite easy. The token will be composed of two informations: the user’s id followed by the token itself, separated by a :. We’ll be using the user’s database id for this sample, for simplicity’s sake, but it’s obviously not a smart thing to do.
First things first, we’ll add an access_token to the user (and a username too):

Creating a resource

I won’t go in detail here, the task is just plain RoR. We’ll create a Story resource and a controller that will handle the user creation. You’ll find the complete rails app in this repo. Moving on.

CORS

It’s worth noting that the UI now will not be served by rails, it might even sit in a different server. There are solution that let us keep both UI and API on the same domain, but for now we will need to enable Cross-origin resource sharing (CORS). We can do this by adding the rack-cors gem to our Gemfile and then add this in our config/application.rb:

Next up

That’s it for the Rails part. It’s such a joy writing just the API in Rails. It’s easier to test, easier to maintain and it’s blazing fast. Now we’ll proceed with the frontend.
For readability’s sake I’ll split the article here, jump to Part 2 to start building the frontend.

]]>2014-07-01T20:47:00+02:00http://fancypixel.github.io/blog/2014/07/01/fun-with-ibeaconYou probably know already what iBeacon is, but just to reiterate, iBeacon is the Apple way of saying Bluetooth 4 Low Energy. At the cost of sounding like a mindless drone, by ‘the Apple way of’ I mean ‘it just works and shows a lot of potential’. An iBeacon is a simple B4LE device that keeps broadcasting its presence. Other B4LE devices can sense when they reach the beacon without draining the battery (hence the LE) and making the user scream in agony. “Oook, what do I do with it?”. The best thing you can do is locating a user without the GPS, which means locating a user inside a building. The cool thing is that it’s fast, it takes seconds to detect a beacon and to react to its vicinity (or lack there of), and it works within the reach of Bluetooth technology (let’s say around a 50 meters radius). I should also mention that it works fine with Android too.

This week an Estimote developer kit arrived in our offices, so we took the chance to play around with it.

I already tried my hand with iBeacons in the not so distant past. Using BeaconEmitter you can easily turn your Mac into a beacon, with no extra hardware required. When I experimented with iBeacons I had a couple of ideas on my mind, that involved being able to send a local notification to the user that enters in range of a device acting as a beacon. My dreams were crushed by the limits of the iOS 7.0 implementation, as I found out that:

you can’t react when the user’s screen is turned off

you can’t perform any action when your app is in background, even if you request the location background state

detecting when the user leaves a region takes quite a lot of time (at least 10/15 minutes)

The most exciting thing about playing around with the Estimote SDK, besides the nifty packaging and well designed piece of hardware, is that my devices now have iOS 7.1. It turns out that with version 7.1, iOS is way more flexible and it’s taking care of all the problems I faced with 7.0:

you can show a local notification when the screen is off

you can perform operations when the user enters a region (even if the app was killed)

it takes second to detect when the user is out of range

This turns everything around, iBeacons aren’t just a gimmick now, but an exciting tool to experiment with.

Building a sample

First thing that came to our mind was to build a simple system to automatically check people in and out of the office. Really, as simple as it gets, it took a couple of hours to build, but it works surprisingly well.

Rails backend

To check people in and out we need a backend and an authentication system. Rails makes it easy, a model, a basic API and the help of Devise for the authentication process.

The authentication is handled by Devise, and for simplicity we opted for HTTP Basic Authentication.

iOS Client

The iOS app needs to look for our trusty beacon, and once the user is in range of our region, it needs to make a POST call to our API. When the user walks out of the office the phone needs to do the same to the checkout API. The iOS APIs for handling beacons are inside CoreLocation, in this sample I’ll be using two main delegate methods:

The good guy calling these two methods is a CLLocationManager instance. The location manager needs an instance of CLBeaconRegion to start doing its magic though. We can define a region by specifying a UUDID, an identifier, a major and a minor. It might sound confusing at first, but all those things boil down to this:

UUDID: A unique identifier of our beacon network. It’s best practice to have one UUDID per App. Each beacon will share the same UUDID.

identifier: It’s a string representation of our network. It usually is the reverse URI of our App, something along the line of com.something.awesome.

major: It’s an integer that specifies the major group of our beacons. Think of it as a common number that can identify a bunch of beacons inside a building.

minor: It’s an integer that specifies the single beacon inside of a major group.

So our basic config would be one UUDID and identifier per App, one major per building, and one minor per beacon. For the purposes of this sample we only have a beacon, so we can either disregard this info, or just specify whatever major and minor that we want, as long as it matches the ones configured in the beacon itself.
Now that all that is out of the way, let’s get to the code:

As you can see, we’re just checking against our beacon, when we are in range or when we get out of range, we push a local notification and we perform a remote call to our Rails backend. You can find the full source on our Github account, don’t worry.