---
title: "#253: Watching Files with KZFileWatchers 📄👀"
url: https://littlebitesofcocoa.com/253-watching-files-with-kzfilewatchers
author: Jake Marsh
published: 2016-08-09
topics: ["Libraries","Foundation"]
description: "Today we'll look at a new library from Krzysztof Zabłocki called KZFileWatchers. It allows us to easily monitor local and remote files, running code when..."
---

# #253: Watching Files with KZFileWatchers 📄👀

By Jake Marsh, August 9, 2016. HTML: https://littlebitesofcocoa.com/253-watching-files-with-kzfilewatchers

Today we'll look at a new library from [Krzysztof Zabłocki](https://twitter.com/merowing_) called [KZFileWatchers](https://github.com/krzysztofzablocki/KZFileWatchers). It allows us to easily monitor **local** and **remote files**, running code when changes occur. Let's dive in.

Watching files for changes is a common technique used when creating "live" updating interfaces.

This is a popular technique among web developers. For example, it's now common to use a tool to <i>"live reload"</i> a web page whenever a **CSS** file is changed.

Live updating techniques can dramatically change how we work, allowing us to try out changes more rapidly.

[KZFileWatchers](https://github.com/krzysztofzablocki/KZFileWatchers) helps us build this type of functionality by providing two simple tools:

**FileWatcher.Local** is for observing local file changes. (It can even cross sandbox boundaries for debug simulator builds, think "config files on the desktop").

**FileWatcher.Remote** is for observe remote file changes. We can place a file on a server somewhere, and [KZFileWatchers](https://github.com/krzysztofzablocki/KZFileWatchers) will use the **Etag headers** and **Last-Modified-Date**. This even works with **Dropbox**. Neat.

Let's use a **FileWatcher.Local** to make a live updating **label**.

First we'll create a label:

``` swift
let textLabel = UILabel()
```

Then we'll create our file if it doesn't already exist:

``` swift
let filename = "label-content.txt"
let middle = FileWatcher.Local.simulatorOwnerUsername()
let path = "/Users/\(middle)/Desktop/\(filename)"

if FileManager.default.fileExists(atPath: path) == false {
  try! "Hello, world."
    .data(using: String.Encoding.utf8)?
    .write(to: NSURL.fileURL(withPath: path))
}
```

Finally, we'll wire up a watcher to our file's path, and update our label when the file changes:

``` swift
let watcher = FileWatcher.Local(path: path)

try! watcher?.start {
  switch $0 {
  case .updated(let data):
    textLabel.text = String(
      data: data,
      encoding: String.Encoding.utf8
    )
  default: break
  }
}
```

We can use this technique to drive all sorts of systems. With this we can easily enable/disable features, change content of labels in our UI, or build a full fledged theming system that updates in "real time".

More info about _KZFileWatchers_ can be found at [git.io/filewatchers](https://git.io/filewatchers)
