Now that there is a FoodServer as a backend for the FoodTracker app, it becomes possible to start building a web application that also provides users with access to the stored Meal data.
The steps below show how to start hosting a web application for the images in the Kitura server.
This tutorial follows on from the FoodTracker Application and server created by following the FoodTrackerBackend tutorial. If you have completed the FoodTracker Backend there are no further pre-requisites.
If you have not completed the FoodTrackerBackend tutorial go to the CompletedFoodTracker branch and follow the README instructions.
One approach to making the Meals available through a web application is to store copies of the images on the local file system, and serve them using Kitura's StaticFileServer.
-
Update the Kitura server application to add a StaticFileServer
- Open the
Sources/Application/Application.swift
source file that contains the REST API routes - Setup the file handler to write to the web hosting directory by adding the following under the
let cloudEnv = CloudEnv()
declaration:
private var fileManager = FileManager.default private var rootPath = StaticFileServer().absoluteRootPath
- Add a Static File Server by adding the following to the
postInit()
function:
router.get("/images", middleware: StaticFileServer())
This will serve the contents of a directory, defaulting to the projects
/public
directory, as web pages. - Open the
-
Save the images to the StaticFileServer directory
Update thestoreHandler()
function to save the images to the directory the Static File Server is using by adding the following:let path = rootPath + "/" + meal.name + ".jpg" fileManager.createFile(atPath: path, contents: meal.photo)
-
Create the
public
directory to store the images:cd ~/FoodTrackerBackend/FoodServer/ mkdir public
-
Re-build and re-run the server
Press the Run button or use the ⌘+R key shortcut. -
Rerun the FoodTracker iOS App and view the images
- Run the iOS app in XCode and add or remove a Meal entry.
This is required to trigger a new save of the data to the server. - Visit the web application to see the saved image at:
http://localhost:8080/images/Caprese Salad.jpg
- Run the iOS app in XCode and add or remove a Meal entry.
You can now view any of the saved images from the food tracker by going to: http://localhost:8080/images/<meal name>.jpg
These images can then be referenced in HTML using:
<img src="images/<meal name>.jpg">