<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.8.7">Jekyll</generator><link href="https://mikemikina.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://mikemikina.com/" rel="alternate" type="text/html" /><updated>2025-02-03T10:34:23+01:00</updated><id>https://mikemikina.com/feed.xml</id><title type="html">Mike Mikina</title><subtitle>This blog is mostly about software development, Swift, iOS, machine learning, algorithms and other software development related topics.</subtitle><author><name>Mike Mikina</name></author><entry><title type="html">Tutorial: Building a Facebook bot with Vapor 3 and Swift, part I</title><link href="https://mikemikina.com/blog/tutorial-building-a-facebook-bot-with-vapor-3-and-swift-part-1/" rel="alternate" type="text/html" title="Tutorial: Building a Facebook bot with Vapor 3 and Swift, part I" /><published>2019-06-25T20:01:32+02:00</published><updated>2019-06-25T20:01:32+02:00</updated><id>https://mikemikina.com/blog/tutorial-building-a-facebook-bot-with-vapor-3-and-swift-part-1</id><content type="html" xml:base="https://mikemikina.com/blog/tutorial-building-a-facebook-bot-with-vapor-3-and-swift-part-1/">&lt;style&gt;
header.masthead .overlay {
  opacity: 0.1 !important;
}
&lt;/style&gt;

&lt;p&gt;Bots are everywhere! They are not taking over the world yet, but can definitely do a lot. Facebook has built a great ecosystem around Messenger. You can play with and use a lot of different Facebook bots, some of them are really useful, some of them are there just for fun 😉. Today I would like to show you how to build your own Messenger bot using Swift and Vapor framework. In part 1, I will start with a small simple bot that can just echo commands. In part 2, I will dive deep into the Facebook API and create a more interesting chat bot.&lt;/p&gt;

&lt;p&gt;Let’s get started 🚀&lt;/p&gt;

&lt;!--more--&gt;

&lt;h4 id=&quot;getting-started-with-chatbots-&quot;&gt;Getting started with chatbots 🤖&lt;/h4&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;p&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/exploreMessenger.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Facebook Messenger bots&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/exploreMessenger.png&quot; class=&quot;img-responsive center-block border&quot; width=&quot;375&quot; height=&quot;667&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;p&gt;You probably have seen bots on the Messenger platform. If not, go to the Messenger app on your smartphone and explore the &lt;code class=&quot;highlighter-rouge&quot;&gt;Discover&lt;/code&gt; tab.&lt;/p&gt;

&lt;p&gt;There are basically three different types of chatbots:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Simple notification chatbots - these can, for example, provide information about your package shipping.&lt;/li&gt;
  &lt;li&gt;Process flow chatbots - these can guide you through the process of, for example, ordering a pizza.&lt;/li&gt;
  &lt;li&gt;Conversational chatbots - these can help you resolve issues using NLP (Natural Language Processing).&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;In this tutorial I will focus on a simple notification chatbot, which will just echo all received messages.&lt;/p&gt;

&lt;h4 id=&quot;how-does-the-facebook-platform-looks-like&quot;&gt;How does the Facebook platform looks like?&lt;/h4&gt;

&lt;p&gt;To create a &lt;code class=&quot;highlighter-rouge&quot;&gt;Messenger Bot&lt;/code&gt; first of all you need to create a &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook app&lt;/code&gt;. This app has to be connected to a &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook page&lt;/code&gt;.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/facebook-platform.jpg&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Create a Page&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/facebook-platform.jpg&quot; class=&quot;img-responsive center-block&quot; width=&quot;656&quot; height=&quot;371&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Let’s start with the &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook Page&lt;/code&gt;. It will be used as the identity of your &lt;code class=&quot;highlighter-rouge&quot;&gt;Bot&lt;/code&gt;. You have to keep in mind that a Facebook bot is just an app which is handling messages for you. When people chat with a &lt;code class=&quot;highlighter-rouge&quot;&gt;Bot&lt;/code&gt; they will see the Page name and the Page profile picture.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/create-a-page.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Create a Page&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/create-a-page.png&quot; class=&quot;img-responsive center-block border&quot; width=&quot;564&quot; height=&quot;337&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;To create a new &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook page&lt;/code&gt;, &lt;a href=&quot;https://www.facebook.com/pages/creation/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;go to this address&lt;/a&gt;. Choose &lt;code class=&quot;highlighter-rouge&quot;&gt;Business or brand&lt;/code&gt; and click &lt;code class=&quot;highlighter-rouge&quot;&gt;Get started&lt;/code&gt;. Enter &lt;code class=&quot;highlighter-rouge&quot;&gt;Page name&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Category&lt;/code&gt;. For now you can skip the &lt;code class=&quot;highlighter-rouge&quot;&gt;Add a profile picture&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Add a cover photo&lt;/code&gt; steps.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/business-or-brand.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Business or brand&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/business-or-brand.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;280&quot; height=&quot;273&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Your &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook page&lt;/code&gt; is ready. Now it’s time to create the &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook app&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To create a new &lt;code class=&quot;highlighter-rouge&quot;&gt;Facebook app&lt;/code&gt; you will need a Facebook Developer Account. It is very easy to get one and if you have ever done anything with the Facebook api chances are you already have one. You can create a new developer account on the &lt;a href=&quot;https://developers.facebook.com/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Facebook for Developers&lt;/a&gt; website.&lt;/p&gt;

&lt;p&gt;Now open the &lt;a href=&quot;https://developers.facebook.com/apps/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;apps page&lt;/a&gt; and click the &lt;code class=&quot;highlighter-rouge&quot;&gt;+ Add a New App&lt;/code&gt; button.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/create-new-app.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Create a New App ID&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/create-new-app.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;530&quot; height=&quot;242&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Enter a &lt;code class=&quot;highlighter-rouge&quot;&gt;Display Name&lt;/code&gt; and your &lt;code class=&quot;highlighter-rouge&quot;&gt;Contact Email&lt;/code&gt; and click &lt;code class=&quot;highlighter-rouge&quot;&gt;Create App ID&lt;/code&gt;. After creating an app you will be redirected to the app settings.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/app-settings.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;App settings&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/app-settings.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;773&quot; height=&quot;308&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;On the left sidebar, click the &lt;code class=&quot;highlighter-rouge&quot;&gt;PRODUCTS +&lt;/code&gt; button, it will redirect you to the &lt;code class=&quot;highlighter-rouge&quot;&gt;Add a Product&lt;/code&gt; page.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/add-a-product.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Add a product&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/add-a-product.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;722&quot; height=&quot;247&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;On this page click the &lt;code class=&quot;highlighter-rouge&quot;&gt;Set Up&lt;/code&gt; button on the &lt;code class=&quot;highlighter-rouge&quot;&gt;Messenger&lt;/code&gt; card. Messenger will be added to your app and you will be redirected to the settings page.&lt;/p&gt;

&lt;p&gt;Inside the settings page look for the &lt;code class=&quot;highlighter-rouge&quot;&gt;Access Tokens&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/access-tokens.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Access Tokens&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/access-tokens.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;535&quot; height=&quot;169&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Select your Facebook page and then click the &lt;code class=&quot;highlighter-rouge&quot;&gt;Edit Permissions&lt;/code&gt; button. Follow the creator, at the end you will see that your app has been linked: &lt;code class=&quot;highlighter-rouge&quot;&gt;You've now linked Test to Facebook&lt;/code&gt;. Now you can access your &lt;code class=&quot;highlighter-rouge&quot;&gt;Page Access Token&lt;/code&gt;. Copy it and save it; you will need it later.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/webhooks.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Webhooks&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/webhooks.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;722&quot; height=&quot;166&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Next look for the &lt;code class=&quot;highlighter-rouge&quot;&gt;Webhooks&lt;/code&gt; section and click &lt;code class=&quot;highlighter-rouge&quot;&gt;Setup Webhooks&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/new-page-subscription.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;New page subscription&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/new-page-subscription.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;591&quot; height=&quot;368&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;On this page you need to provide a &lt;code class=&quot;highlighter-rouge&quot;&gt;Callback URL&lt;/code&gt; for your the messenger app. This url will be used to send information back to your Vapor app. Before you create it let me explain what exactly it is.&lt;/p&gt;

&lt;h4 id=&quot;what-is-a-webhook&quot;&gt;What is a Webhook&lt;/h4&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/webhook.jpg&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Create a Page&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/webhook.jpg&quot; class=&quot;img-responsive center-block&quot; width=&quot;666&quot; height=&quot;185&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Webhook provides a mechanism for the Facebook platform to notify your application when a new event has occurred on the server. It is an easy way of communicating with the Facebook platform. Instead of constantly checking if there is a new message from the user, Facebook will call your app whenever a new message arrives or other event occurs.&lt;/p&gt;

&lt;p&gt;Inside &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt;, a webhook is simply just a route which you can name as you want. For a Messenger bot you will have to create an endpoint with two types of &lt;code class=&quot;highlighter-rouge&quot;&gt;HTTP&lt;/code&gt; methods: &lt;code class=&quot;highlighter-rouge&quot;&gt;GET&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;POST&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Webhook with &lt;code class=&quot;highlighter-rouge&quot;&gt;GET&lt;/code&gt; method: will only be used once for a request validation when you create a new page subscription during the webhook setup on the Facebook platform.&lt;/li&gt;
  &lt;li&gt;Webhook with &lt;code class=&quot;highlighter-rouge&quot;&gt;POST&lt;/code&gt; method: this is the heart of your app. The Facebook platform will send all of the notifications here.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Before creating a webhook inside &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; there is one more thing to consider. In order to test the Messenger bot on your Macbook you need to expose your machine to the outside connections. The simplest solution is to use tools like &lt;code class=&quot;highlighter-rouge&quot;&gt;Ngrok&lt;/code&gt; or other similar apps that will create public URLs to your local web server. For more details how to setup and use &lt;code class=&quot;highlighter-rouge&quot;&gt;Ngrok&lt;/code&gt; you can go &lt;a href=&quot;https://ngrok.com/product&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Just remember that default port for &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; is &lt;code class=&quot;highlighter-rouge&quot;&gt;8080&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ ./ngrok http 8080&lt;/code&gt;&lt;/pre&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/ngrok.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Ngrok&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/ngrok.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;628&quot; height=&quot;293&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h4 id=&quot;setting-up-your-webhook&quot;&gt;Setting Up Your Webhook&lt;/h4&gt;

&lt;p&gt;Now it’s time for the fun part, let’s create the Vapor app 🎉&lt;/p&gt;

&lt;p&gt;Create a new Vapor project:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ vapor new Facebook-bot-with-Vapor-3&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Set &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift 5.0&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor 3.3.0&lt;/code&gt; inside &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.swift&lt;/code&gt;, you can also clean up and remove &lt;code class=&quot;highlighter-rouge&quot;&gt;FluentSQLite&lt;/code&gt; from your dependencies, as it won’t be needed. You can check what &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.swift&lt;/code&gt; should look like &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/305944e1fff09252bd49ea10852bdb3161460dfd/Package.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Generate the Xcode project file and open it:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ vapor xcode -y&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To verify the webhook, create a controller file with the &lt;code class=&quot;highlighter-rouge&quot;&gt;verify&lt;/code&gt; function. To know what kind of data Facebook will send during the verification, check &lt;a href=&quot;https://developers.facebook.com/docs/messenger-platform/getting-started/webhook-setup&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;FB documentation&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Create the controller file: &lt;code class=&quot;highlighter-rouge&quot;&gt;App/Controllers/BotController.swift&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor

final class BotController {
  
  let FacebookVerifyToken = Environment.get(&amp;#x22;FBVERIFYTOKEN&amp;#x22;)

  func verify(_ req: Request) throws -&amp;#x3E; Future&amp;#x3C;String&amp;#x3E; {
    let mode = try req.query.get(String.self, at: &amp;#x22;hub.mode&amp;#x22;)
    let token = try req.query.get(String.self, at: &amp;#x22;hub.verify_token&amp;#x22;)
    let challenge = try req.query.get(String.self, at: &amp;#x22;hub.challenge&amp;#x22;)
    
    if mode == &amp;#x22;subscribe&amp;#x22; &amp;#x26;&amp;#x26; FacebookVerifyToken == token {
      return req.eventLoop.newSucceededFuture(result: challenge)
    }
    else {
      throw Abort(.forbidden)
    }
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;From the request query you need to get three parameters: &lt;code class=&quot;highlighter-rouge&quot;&gt;hub.mode&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;hub.verify_token&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;hub.challenge&lt;/code&gt;.&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;hub.mode&lt;/code&gt; is not described inside the documentation so I’m not sure if other options instead of &lt;code class=&quot;highlighter-rouge&quot;&gt;subscribe&lt;/code&gt; are available. But to be sure just check if &lt;code class=&quot;highlighter-rouge&quot;&gt;hub.mode&lt;/code&gt; is equal to &lt;code class=&quot;highlighter-rouge&quot;&gt;subscribe&lt;/code&gt;.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;hub.challenge&lt;/code&gt; is a random text sent by the Facebook platform which you have to return during webhook verification.&lt;/p&gt;
  &lt;/li&gt;
  &lt;li&gt;
    &lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;hub.verify_token&lt;/code&gt; is the token that you set during webhook setup. It’s a good idea to pass it as an environment variable instead of hardcoding it.&lt;/p&gt;
  &lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Remember to set &lt;code class=&quot;highlighter-rouge&quot;&gt;FBVERIFYTOKEN&lt;/code&gt; as an environment variable inside the Xcode scheme:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/environment-variables.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Ngrok&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/environment-variables.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;609&quot; height=&quot;343&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;or if you are running your app from the Terminal:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ FBVERIFYTOKEN=bot123 ./Run serve --hostname 127.0.0.1 --port 8080 --env development&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;verify&lt;/code&gt; function will be used for request validation. Remember to add missing routes inside &lt;code class=&quot;highlighter-rouge&quot;&gt;App/routes.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor

public func routes(_ router: Router) throws {
  let botController = BotController()
  router.get(&amp;#x22;webhook&amp;#x22;, use: botController.verify)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run the &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; project and inside the Terminal execute this &lt;code class=&quot;highlighter-rouge&quot;&gt;curl&lt;/code&gt; command:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ curl -X GET &quot;localhost:8080/webhook?hub.verify_token=bot123&amp;amp;hub.challenge=CHALLENGE_ACCEPTED&amp;amp;hub.mode=subscribe&quot;

CHALLENGE_ACCEPTED%&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As a result of the &lt;code class=&quot;highlighter-rouge&quot;&gt;curl&lt;/code&gt; inside the Terminal, you should see the following printed text: &lt;code class=&quot;highlighter-rouge&quot;&gt;CHALLENGE_ACCEPTED&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Let’s also write a simple test for this function.&lt;/p&gt;

&lt;p&gt;To simplify all of the tests, copy the Vapor &lt;a href=&quot;https://github.com/vapor/vapor/blob/3.3.0/Tests/VaporTests/ApplicationTests.swift#L816-L933&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;➡️ helper&lt;/a&gt; and paste it inside: &lt;code class=&quot;highlighter-rouge&quot;&gt;Tests/AppTests/TestsHelper.swift&lt;/code&gt; file. Don’t forget to make the extension &lt;code class=&quot;highlighter-rouge&quot;&gt;public&lt;/code&gt; so other tests can see it. Then create the test file &lt;code class=&quot;highlighter-rouge&quot;&gt;Tests/AppTests/WebhookTests.swift&lt;/code&gt; and put the &lt;code class=&quot;highlighter-rouge&quot;&gt;testWebhook&lt;/code&gt; function inside:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;func testWebhook() throws {
  
  let expectation = self.expectation(description: &amp;#x22;Webhook&amp;#x22;)
  var responseData: Response?
  var challenge: String?
  
  try app?.test(.GET, &amp;#x22;/webhook?hub.mode=subscribe&amp;#x26;hub.verify_token=test&amp;#x26;hub.challenge=CHALLENGE_ACCEPTED&amp;#x22;) { response in
    responseData = response
    challenge = String(decoding: response.http.body.data!, as: UTF8.self)
    expectation.fulfill()
  }
  
  waitForExpectations(timeout: 5, handler: nil)
  
  XCTAssertEqual(responseData?.http.status, .ok)
  XCTAssertEqual(responseData?.http.contentType, MediaType.plainText)
  XCTAssertEqual(challenge, &amp;#x22;CHALLENGE_ACCEPTED&amp;#x22;)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;Application.test&lt;/code&gt; function will create a request and call the webhook endpoint. The body will be assigned to the &lt;code class=&quot;highlighter-rouge&quot;&gt;challenge&lt;/code&gt; variable. Don’t forget to create an expectation and fulfill it inside the closure. You can check the whole test file here: &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/305944e1fff09252bd49ea10852bdb3161460dfd/Tests/AppTests/WebhookTests.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;WebhookTests.swift&lt;/a&gt;. Set &lt;code class=&quot;highlighter-rouge&quot;&gt;FBVERIFYTOKEN&lt;/code&gt; as an environment variable also for test scheme.&lt;/p&gt;

&lt;p&gt;It’s time to connect your webhook with the Facebook platform. To do this go back to the Facebook page and look for &lt;code class=&quot;highlighter-rouge&quot;&gt;Setup Webhooks&lt;/code&gt; inside the settings page.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;p&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/new-page-subscription-options.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;New page subscription&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/new-page-subscription-options.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;591&quot; height=&quot;368&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;ul&gt;
  &lt;li&gt;Callback URL - put your Ngrok public url (or any other that you are using) here, don’t forget to add the &lt;code class=&quot;highlighter-rouge&quot;&gt;/webhook&lt;/code&gt; route to the address.&lt;/li&gt;
  &lt;li&gt;Verify Token - here you need to enter verification token that will be sent back to the webhook. You can name it as you want, &lt;code class=&quot;highlighter-rouge&quot;&gt;test&lt;/code&gt;, &lt;code class=&quot;highlighter-rouge&quot;&gt;bot123&lt;/code&gt; etc.&lt;/li&gt;
  &lt;li&gt;Subscription Fields - here you can select different types of webhook events that will be delivered to the webhook. For now just select &lt;code class=&quot;highlighter-rouge&quot;&gt;messages&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;messaging_postbacks&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Confirm it by clicking &lt;code class=&quot;highlighter-rouge&quot;&gt;Verify and Save&lt;/code&gt;. Don’t forget to run the Vapor app! After your webhook has been verified you can now move to message handling.&lt;/p&gt;

&lt;h4 id=&quot;receiving-the-messages&quot;&gt;Receiving the messages&lt;/h4&gt;

&lt;p&gt;It’s time to create a function that will take care of the incoming messages via webhook &lt;code class=&quot;highlighter-rouge&quot;&gt;POST&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;To better understand what kind of structure will be there, check out the Facebook documentation: &lt;a href=&quot;https://developers.facebook.com/docs/messenger-platform/reference/webhook-events&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Webhook Events Reference&lt;/a&gt;. I have already created the file with a Facebook webhook response struct. Download it from &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/master/Sources/App/Models/BotStructure.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Github&lt;/a&gt; and put it in &lt;code class=&quot;highlighter-rouge&quot;&gt;Models/BotStructure.swift&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Inside &lt;code class=&quot;highlighter-rouge&quot;&gt;BotController.swift&lt;/code&gt; add a function that will be responsible for receiving the messages from the Messenger platform:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;func message(_ req: Request) throws -&amp;#x3E; Future&amp;#x3C;Response&amp;#x3E; {
  // #1
  let data = try req.content.decode(FBResponseWrapper.self)
  
  // #2
  let botService = try req.make(BotServiceProtocol.self)
  let messagesService = try req.make(MessagesServiceProtocol.self)
  
  return data.flatMap { result in
    // #3
    guard let messageInput = result.entry.last?.messaging.last else {
      // Beware that in some cases Facebook response may not contain any messages. 
      throw Abort(.badRequest)
    }

    // #4
    let fbMessage = try messagesService.createMessage(for: messageInput)
    return try botService.sendFBMessage(req, message: fbMessage, recipient: messageInput.sender)
  }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s go through this code step by step:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#1&lt;/code&gt;: Content of the request will be decoded to the &lt;code class=&quot;highlighter-rouge&quot;&gt;FBResponseWrapper&lt;/code&gt; struct. You can find this struct in the &lt;code class=&quot;highlighter-rouge&quot;&gt;Models/BotStructure.swift&lt;/code&gt; file.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#2&lt;/code&gt;: Then create the bot service, which will be responsible for sending messages, and the messages service which will be responsible for handling the messages logic. Remember to use protocols, this way it will be easier to switch those dependencies inside tests. You can read more about it in my previous blog post: &lt;a href=&quot;/blog/using-the-dependency-injection-framework-for-testing-in-vapor-3-and-swift/&quot; target=&quot;_blank&quot;&gt;Using the dependency injection framework for testing in Vapor 3 and Swift&lt;/a&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#3&lt;/code&gt;: Get the incoming message. There can be more messages inside the request body, but for now just get the last one.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#4&lt;/code&gt;: Bot will echo all of the incoming messages back to the user. Using the messages service, create a response message and send it back to the user using the bot service.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Don’t forget to add all missing routes inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;App/routes.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor

public func routes(_ router: Router) throws {
    let botController = BotController()
    router.get(&amp;#x22;webhook&amp;#x22;, use: botController.verify)
    router.post(&amp;#x22;webhook&amp;#x22;, use: botController.message)
}
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Caveat:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;As you may have noticed, the &lt;code class=&quot;highlighter-rouge&quot;&gt;message&lt;/code&gt; function is not checking the source of the input, so anyone who knows the webhook address can send malicious requests and pretend to be a Messenger bot. There is a simple solution to this issue. Messenger is providing a signed signature of the body that you can access from header: &lt;code class=&quot;highlighter-rouge&quot;&gt;X-Hub-Signature&lt;/code&gt;. An attacker would need your personal app secret to spoof the request. Read more in the documentation: &lt;a href=&quot;https://developers.facebook.com/docs/messenger-platform/webhook#security&quot; target=&quot;_blank&quot;&gt;Validating Webhook Events&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;I will write how to secure your webhook in part two of this tutorial.&lt;/p&gt;

&lt;h4 id=&quot;create-a-new-message&quot;&gt;Create a new message&lt;/h4&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;The Facebook messenger&lt;/code&gt; platform offers additional settings for the initial conversation. This means that you can set a greeting message and a &lt;code class=&quot;highlighter-rouge&quot;&gt;Get started&lt;/code&gt; button. Using the &lt;code class=&quot;highlighter-rouge&quot;&gt;Get started&lt;/code&gt; button will help your bot initialize conversation and set a different first response. To set the &lt;code class=&quot;highlighter-rouge&quot;&gt;Get started&lt;/code&gt; button you need to setup an additional payload for the get started action. To do this, simply send it to the Facebook API in a Terminal:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;curl -X POST -H &amp;#x22;Content-Type: application/json&amp;#x22; -d &amp;#x27;{
  &amp;#x22;get_started&amp;#x22;: { &amp;#x22;payload&amp;#x22;: &amp;#x22;START&amp;#x22; },
  &amp;#x22;greeting&amp;#x22;:[{ &amp;#x22;locale&amp;#x22;:&amp;#x22;default&amp;#x22;, &amp;#x22;text&amp;#x22;:&amp;#x22;Hello &amp;#x1F44B;&amp;#x22; }]
}&amp;#x27; &amp;#x22;https://graph.facebook.com/v2.6/me/messenger_profile?access_token=[PUT YOUR FB TOKEN HERE]&amp;#x22;
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can read more about &lt;a href=&quot;https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/get-started-button&quot; target=&quot;_blank&quot;&gt;Get started button&lt;/a&gt; and &lt;a href=&quot;https://developers.facebook.com/docs/messenger-platform/reference/messenger-profile-api/greeting&quot; target=&quot;_blank&quot;&gt;Greeting Text&lt;/a&gt; in the Messenger documentation.&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;p&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/initial-conversation.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Initial conversation&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/initial-conversation.png&quot; class=&quot;img-responsive center-block border&quot; width=&quot;375&quot; height=&quot;667&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;p&gt;Now let’s create a messages service: &lt;code class=&quot;highlighter-rouge&quot;&gt;Models/MessagesService.swift&lt;/code&gt;. Start with a protocol: &lt;code class=&quot;highlighter-rouge&quot;&gt;MessagesServiceProtocol&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;protocol MessagesServiceProtocol {
  func createMessage(for input: FBMessagingDetails) throws -&amp;#x3E; FBMessage
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then create a class that conforms to the &lt;code class=&quot;highlighter-rouge&quot;&gt;MessagesServiceProtocol&lt;/code&gt; and the &lt;code class=&quot;highlighter-rouge&quot;&gt;Service&lt;/code&gt; protocol:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;class MessagesService: MessagesServiceProtocol, Service {
  func createMessage(for input: FBMessagingDetails) throws -&amp;#x3E; FBMessage {
    if input.postback?.payload == &amp;#x22;START&amp;#x22; {
      // #1
      return FBMessage(text: &amp;#x22;Hi &amp;#x1F44B; I&amp;#x27;m Echo Bot, I will send back everything you write to me &amp;#x1F604;&amp;#x22;)
    }
    else if let message = input.message {
      // #2
      return FBMessage(text: &amp;#x22;Echo: \(message.text ?? &amp;#x22;This format is not supported yet, sorry &amp;#x1F607;&amp;#x22;)&amp;#x22;)
    }
    else {
      throw Abort(.badRequest)
    }
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;createMessage&lt;/code&gt; function has a very simple logic:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#1&lt;/code&gt;: If there is a payload value and it matches with the predefined payload value it means that this is the initial conversation. The user has just clicked the &lt;code class=&quot;highlighter-rouge&quot;&gt;Get Started&lt;/code&gt; button. In this case say hi to the user.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#2&lt;/code&gt;: If there is a message inside, create an echo message. Also remember to check if there is &lt;code class=&quot;highlighter-rouge&quot;&gt;text&lt;/code&gt; inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;FBMessage&lt;/code&gt; struct. Text is optional, the user can send a sticker or any other type of message. In that case &lt;code class=&quot;highlighter-rouge&quot;&gt;text&lt;/code&gt; will be &lt;code class=&quot;highlighter-rouge&quot;&gt;nil&lt;/code&gt;.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To use the &lt;code class=&quot;highlighter-rouge&quot;&gt;MessagesService&lt;/code&gt; don’t forget to register it as a &lt;code class=&quot;highlighter-rouge&quot;&gt;MessagesServiceProtocol&lt;/code&gt; inside the app configuration file &lt;code class=&quot;highlighter-rouge&quot;&gt;App/configure.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block bottom-separator-20&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;services.register(MessagesServiceProtocol.self) { container in
  return MessagesService()
}&lt;/code&gt;&lt;/pre&gt;

&lt;h4 id=&quot;sending-the-messages&quot;&gt;Sending the messages&lt;/h4&gt;

&lt;p&gt;You are almost there! The messages service is ready. Now let’s create the &lt;code class=&quot;highlighter-rouge&quot;&gt;FBService&lt;/code&gt; which will handle the communication with the Messenger platform.&lt;/p&gt;

&lt;p&gt;Create &lt;code class=&quot;highlighter-rouge&quot;&gt;Models/BotService.swift&lt;/code&gt; and start with the protocol &lt;code class=&quot;highlighter-rouge&quot;&gt;BotServiceProtocol&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;protocol BotServiceProtocol {
  func sendFBMessage(_ req: Request, message: FBMessage, recipient: FBUserID) throws -&amp;#x3E; EventLoopFuture&amp;#x3C;Response&amp;#x3E;
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;sendFBMessage&lt;/code&gt; function requires &lt;code class=&quot;highlighter-rouge&quot;&gt;Request&lt;/code&gt; to get access to the &lt;code class=&quot;highlighter-rouge&quot;&gt;Client&lt;/code&gt; object, which will allow you to send HTTP requests. Then create the class &lt;code class=&quot;highlighter-rouge&quot;&gt;FBService&lt;/code&gt; that conforms to the &lt;code class=&quot;highlighter-rouge&quot;&gt;BotServiceProtocol&lt;/code&gt; and the &lt;code class=&quot;highlighter-rouge&quot;&gt;Service&lt;/code&gt; protocol:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;class FBService: BotServiceProtocol, Service {
  let FacebookAPIToken = Environment.get(&amp;#x22;FBAPITOKEN&amp;#x22;)
  
  func sendFBMessage(_ req: Request, message: FBMessage, recipient: FBUserID) throws -&amp;#x3E; EventLoopFuture&amp;#x3C;Response&amp;#x3E; {
    // #1
    var fbMessagesAPI = URLComponents(string: &amp;#x22;https://graph.facebook.com/v2.6/me/messages&amp;#x22;)!
    fbMessagesAPI.queryItems = [URLQueryItem(name: &amp;#x22;access_token&amp;#x22;, value: FacebookAPIToken)]
    
    // #2
    return try req.client().post(fbMessagesAPI.url!, headers: HTTPHeaders.init([(&amp;#x22;Content-Type&amp;#x22;, &amp;#x22;application/json&amp;#x22;)])) { body in
      try body.content.encode(json: FBSendMessage(message: message, recipient: recipient))
    }
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Sending the message to the Facebook platform is pretty straightforward:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#1&lt;/code&gt;: Prepare the API url, add &lt;code class=&quot;highlighter-rouge&quot;&gt;access_token&lt;/code&gt;.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#2&lt;/code&gt;: Send &lt;code class=&quot;highlighter-rouge&quot;&gt;POST&lt;/code&gt; request using the &lt;code class=&quot;highlighter-rouge&quot;&gt;Client&lt;/code&gt; object. Inside the closure you can set the body of the request. All you have to do is to send a &lt;code class=&quot;highlighter-rouge&quot;&gt;FBSendMessage&lt;/code&gt; struct with a message and a recipient.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;To use the &lt;code class=&quot;highlighter-rouge&quot;&gt;FBService&lt;/code&gt; don’t forget to register it as a &lt;code class=&quot;highlighter-rouge&quot;&gt;BotServiceProtocol&lt;/code&gt; inside the app configuration file &lt;code class=&quot;highlighter-rouge&quot;&gt;App/configure.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;services.register(BotServiceProtocol.self) { container in
  return FBService()
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let’s create two additional tests to fully test the second webhook endpoint.&lt;/p&gt;

&lt;p&gt;First of all, you need to create the &lt;code class=&quot;highlighter-rouge&quot;&gt;FBService&lt;/code&gt; mock. You don’t want to send actual data to Facebook during testing. Create file &lt;code class=&quot;highlighter-rouge&quot;&gt;Tests/AppTests/BotManagerMock.swift&lt;/code&gt;. Details of this file you can find &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/master/Tests/AppTests/BotManagerMock.swift&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. Then modify &lt;code class=&quot;highlighter-rouge&quot;&gt;setUp&lt;/code&gt; function to register &lt;code class=&quot;highlighter-rouge&quot;&gt;BotServiceProtocol&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;MessagesServiceProtocol&lt;/code&gt;, inside the test file &lt;code class=&quot;highlighter-rouge&quot;&gt;Tests/AppTests/WebhookTests.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;override func setUp() {
  super.setUp()
  self.fbServiceMock = FBServiceMock()
  
  app = try! Application.makeTest(configure: { (config, services) in
    services.register(BotServiceProtocol.self) { container in
      return self.fbServiceMock!
    }
    
    services.register(MessagesServiceProtocol.self) { container in
      return MessagesService()
    }
  }, routes: routes)
}

let testsURL: URL = {
  let directory = DirectoryConfig.detect()
  let workingDirectory = URL(fileURLWithPath: directory.workDir)
  return workingDirectory.appendingPathComponent(&amp;#x22;Tests&amp;#x22;, isDirectory: true)
}()

override func tearDown() {
  super.tearDown()
  
  app = nil
  fbServiceMock = nil
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now create a test for the initial message:&lt;/p&gt;

&lt;pre class=&quot;code-block bottom-separator-20&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;func testInitialMessage() throws {
  
  let expectation = self.expectation(description: &amp;#x22;Webhook&amp;#x22;)
  var responseData: Response?
  // #1
  let jsonData = try Data(contentsOf: testsURL.appendingPathComponent(&amp;#x22;FB-request-1.json&amp;#x22;))
  self.fbServiceMock!.response = HTTPResponse(status: .ok, body: &amp;#x22;{}&amp;#x22;)
  // #2
  try app?.test(HTTPRequest(method: .POST, url: URL(string: &amp;#x22;/webhook&amp;#x22;)!), beforeSend: { request in
    request.http.headers = HTTPHeaders.init([(&amp;#x22;Content-Type&amp;#x22;, &amp;#x22;application/json&amp;#x22;)])
    // #3
    request.http.body = HTTPBody(data: jsonData)
  }, afterSend: { response in
    responseData = response
    expectation.fulfill()
  })
  
  waitForExpectations(timeout: 5, handler: nil)
  
  XCTAssertEqual(responseData?.http.status, .ok)
  // #4
  XCTAssertEqual(self.fbServiceMock?.responseMessage, &amp;#x22;Hi &amp;#x1F44B; I&amp;#x27;m Echo Bot, I will send back everything you write to me &amp;#x1F604;&amp;#x22;)
}&lt;/code&gt;&lt;/pre&gt;

&lt;ul&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#1&lt;/code&gt;: Load the content of the &lt;code class=&quot;highlighter-rouge&quot;&gt;FB-request-1.json&lt;/code&gt; file, you can get this file from &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/master/Tests/FB-request-1.json&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. This is the request which Facebook will send to your webhook after the user clicks the &lt;code class=&quot;highlighter-rouge&quot;&gt;Get Started&lt;/code&gt; button.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#2&lt;/code&gt;: &lt;code class=&quot;highlighter-rouge&quot;&gt;Application.test&lt;/code&gt; function will create a POST request to the webhook.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#3&lt;/code&gt;: Inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;beforeSend&lt;/code&gt; closure you can set the body of the request, simply assign the json data loaded earlier.&lt;/li&gt;
  &lt;li&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;#4&lt;/code&gt;: Check if &lt;code class=&quot;highlighter-rouge&quot;&gt;FBService&lt;/code&gt; mock has a proper message value.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;You can check the whole test file &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3/blob/master/Tests/AppTests/WebhookTests.swift&quot; target=&quot;_blank&quot;&gt;here&lt;/a&gt;. It also has the second test for the echo message.&lt;/p&gt;

&lt;p&gt;It’s time to play with your bot 😄. To find your Messenger Link, go to your fanpage: &lt;code class=&quot;highlighter-rouge&quot;&gt;Settings &amp;gt; Messenger Platform&lt;/code&gt; and look for &lt;code class=&quot;highlighter-rouge&quot;&gt;Your Messenger Link&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;p&gt;&lt;a href=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/messenger-link.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Your Messenger Link&quot; src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/messenger-link.png&quot; class=&quot;img-responsive center-block border&quot; width=&quot;591&quot; height=&quot;368&quot; /&gt;&lt;/a&gt;&lt;/p&gt;&lt;/div&gt;

&lt;p&gt;Don’t forget to run the &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; project and set a proper webhook address. Copy your messenger link into &lt;code class=&quot;highlighter-rouge&quot;&gt;Safari&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;video-container&quot;&gt;
  &lt;video class=&quot;video-center border&quot; preload=&quot;auto&quot; poster=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/demo-bot.jpg&quot; width=&quot;375&quot; muted=&quot;&quot; controls=&quot;&quot; style=&quot;max-width: 375px;&quot;&gt;
    &lt;source src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/demo-bot.webm&quot; type=&quot;video/webm&quot; /&gt;
    &lt;source src=&quot;/assets/facebook-bot-with-vapor-3-and-swift-part-1/demo-bot.mp4&quot; type=&quot;video/mp4&quot; /&gt;
  &lt;/video&gt;
&lt;/div&gt;

&lt;h4 id=&quot;summary-&quot;&gt;Summary ✅&lt;/h4&gt;

&lt;p&gt;As you can see, this Facebook bot is pretty simple. The goal of this post is to help you to understand the basics of the Messenger API and how to use it. You can check the repository with the entire project on &lt;a href=&quot;https://github.com/mikina/Facebook-bot-with-Vapor-3&quot; target=&quot;_blank&quot;&gt;Github&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;On the next blog post I will show you more interesting functions that are available on the platform. I will also talk about how to secure the webhook and prevent it from being accessed by anyone who knows its address.&lt;/p&gt;

&lt;p&gt;What do you think of the Messenger platform? Have you tried to create your own bot? Did you have any difficulties with the API? Let me know - along with your questions, comments or feedback - on Twitter &lt;a href=&quot;https://twitter.com/mikemikina&quot; target=&quot;_blank&quot;&gt;@mikemikina&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Happy coding 😊&lt;/p&gt;</content><author><name>Mike Mikina</name></author><summary type="html"></summary></entry><entry><title type="html">Using the dependency injection framework for testing in Vapor 3 and Swift</title><link href="https://mikemikina.com/blog/using-the-dependency-injection-framework-for-testing-in-vapor-3-and-swift/" rel="alternate" type="text/html" title="Using the dependency injection framework for testing in Vapor 3 and Swift" /><published>2019-04-10T20:12:12+02:00</published><updated>2019-04-10T20:12:12+02:00</updated><id>https://mikemikina.com/blog/using-the-dependency-injection-framework-for-testing-in-vapor-3-and-swift</id><content type="html" xml:base="https://mikemikina.com/blog/using-the-dependency-injection-framework-for-testing-in-vapor-3-and-swift/">&lt;p&gt;In my previous blogpost, &lt;a href=&quot;/blog/how-to-test-controllers-by-mocking-dependencies-in-vapor-3-and-swift/&quot;&gt;How to test controllers by mocking dependencies in Vapor 3 and Swift&lt;/a&gt;, I injected dependencies into the controller using a constructor, but it turns out that there is a better way to do it. Vapor 3 introduces a dependency injection framework, which allows you to register, configure, and create your application’s dependencies in a maintainable way.&lt;/p&gt;

&lt;p&gt;Show me the code ☀️&lt;/p&gt;

&lt;!--more--&gt;

&lt;h4 id=&quot;why-should-you-use-the-dependency-injection-framework-&quot;&gt;Why should you use the dependency injection framework? 🤔&lt;/h4&gt;

&lt;p&gt;I was a little skeptical when I first read about it in the &lt;a href=&quot;https://docs.vapor.codes/3.0/getting-started/services/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;documentation&lt;/a&gt;. My main concern was that it would be hard to mock inside the tests. It turns out that it’s not.&lt;/p&gt;

&lt;p&gt;The Service (&lt;a href=&quot;https://github.com/vapor/service&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;vapor/service&lt;/a&gt;) framework provides you with a couple of interesting features:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Easy access to the collection of registered services&lt;/li&gt;
  &lt;li&gt;Configure preferences for certain services over others&lt;/li&gt;
  &lt;li&gt;Initialize one object and reuse it everywhere or create a new one for each call&lt;/li&gt;
  &lt;li&gt;Register different services depending on the environment&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Creating a new service in your controller is very simple, just call &lt;code class=&quot;highlighter-rouge&quot;&gt;.make(_:)&lt;/code&gt; on the &lt;code class=&quot;highlighter-rouge&quot;&gt;request&lt;/code&gt; and pass the type you want.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let availabilityChecker = try request.make(AvailabilityCheckerProtocol.self)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You have to remember that the class that conforms to registered protocol has to conform to the &lt;code class=&quot;highlighter-rouge&quot;&gt;Service&lt;/code&gt; protocol. You can achieve this by creating extension:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;extension AvailabilityChecker: Service {}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The service protocol is just an empty protocol for declaring types that can be registered as a service.&lt;/p&gt;

&lt;h4 id=&quot;how-to-use-it-inside-the-tests-&quot;&gt;How to use it inside the tests? 🛠&lt;/h4&gt;

&lt;p&gt;The key to this is using protocols instead of the concrete implementation.&lt;/p&gt;

&lt;p&gt;If you create a service using the class that implements your protocol, for example, like this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let availabilityChecker = try request.make(AvailabilityChecker.self)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inside the tests it will be impossible to switch &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityChecker&lt;/code&gt; for a mock object like &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityCheckerMock&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;So initializing the service as a protocol allows you to register different implementations for the application and for testing.&lt;/p&gt;

&lt;p&gt;For the application, your &lt;code class=&quot;highlighter-rouge&quot;&gt;configure.swift&lt;/code&gt; file will look like this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;services.register(AvailabilityCheckerProtocol.self) { container in
  return AvailabilityChecker()
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;For testing, when you will use Vapor &lt;a href=&quot;https://github.com/vapor/vapor/blob/3.3.0/Tests/VaporTests/ApplicationTests.swift#L816-L933&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;➡️ helper&lt;/a&gt;, you can simply register mock in the configure closure like this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;final class AvailabilityTests: XCTestCase {
  
  var app: Application?
  
  override func setUp() {
    super.setUp()
    app = try! Application.makeTest(configure: { (config, services) in
      services.register(AvailabilityCheckerProtocol.self) { container in
        return AvailabilityCheckerMock()
      }
    }, routes: testRoutes)
  }&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Source code with those examples is available here: ⚙️&lt;a href=&quot;https://github.com/mikina/Mocking-Dependencies-Vapor3&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Mocking-Dependencies-Vapor3&lt;/a&gt;.&lt;/p&gt;

&lt;h4 id=&quot;summary-&quot;&gt;Summary ✅&lt;/h4&gt;

&lt;p&gt;As you can see, when creating services it’s much better to use protocols over the concrete implementation. When using protocols it’s very easy to mock all of the dependencies inside tests.&lt;/p&gt;

&lt;p&gt;It’s definitely worth playing around and experimenting with the service framework. If you haven’t yet you should give it a try 👍&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What do you think? Did you have any issues with testing while using services? Let me know - along with your questions, comments or feedback - on Twitter &lt;a href=&quot;https://twitter.com/mikemikina&quot; target=&quot;_blank&quot;&gt;@mikemikina&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Happy coding 😊&lt;/p&gt;</content><author><name>Mike Mikina</name></author><summary type="html">In my previous blogpost, How to test controllers by mocking dependencies in Vapor 3 and Swift, I injected dependencies into the controller using a constructor, but it turns out that there is a better way to do it. Vapor 3 introduces a dependency injection framework, which allows you to register, configure, and create your application’s dependencies in a maintainable way.</summary></entry><entry><title type="html">How to test controllers by mocking dependencies in Vapor 3 and Swift</title><link href="https://mikemikina.com/blog/how-to-test-controllers-by-mocking-dependencies-in-vapor-3-and-swift/" rel="alternate" type="text/html" title="How to test controllers by mocking dependencies in Vapor 3 and Swift" /><published>2019-03-19T20:11:05+01:00</published><updated>2019-03-19T20:11:05+01:00</updated><id>https://mikemikina.com/blog/testing</id><content type="html" xml:base="https://mikemikina.com/blog/how-to-test-controllers-by-mocking-dependencies-in-vapor-3-and-swift/">&lt;p&gt;Testing controllers with external dependencies, especially ones involving HTTP requests, is very tricky. That’s because sending actual requests would create a test that you could not rely on and is very slow. But there is a very simple technique that you are probably familiar with: using protocols and injecting dependencies into controllers. Recently I ran into an issue when I was trying to get parameters from routes inside unit tests. So today I would like to show you how easily you can also pass proper routes into testing functions in Vapor 3.&lt;/p&gt;

&lt;p&gt;Let’s get started 🚀&lt;/p&gt;

&lt;!--more--&gt;

&lt;h4 id=&quot;why-do-you-even-want-to-test-controllers-&quot;&gt;Why do you even want to test controllers? 🤔&lt;/h4&gt;

&lt;p&gt;Imagine an online store. On the product details page users can check how many items are available. The thing is that availability system is an external service, so each time a user wants to check product status, an external service has to be called.&lt;/p&gt;

&lt;p&gt;Because the external service may be down or items that users are looking for are no longer available, the controller has to return the proper information.&lt;/p&gt;

&lt;h4 id=&quot;mocking-external-dependencies-️&quot;&gt;Mocking external dependencies ⚙️&lt;/h4&gt;

&lt;p&gt;You can’t check if an external service is working or not, but you can check if the controller is returning proper status codes by mocking the external service.&lt;/p&gt;

&lt;p&gt;You’ve probably done this before, the idea is simple:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Use protocol for external dependency&lt;/li&gt;
  &lt;li&gt;Inject it inside controller, ex: inside &lt;code class=&quot;highlighter-rouge&quot;&gt;init&lt;/code&gt; method&lt;/li&gt;
  &lt;li&gt;Inside test suite use mock object that conforms to the protocol&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Let’s define simple protocol - &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityCheckerProtocol&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;protocol AvailabilityCheckerProtocol {
  func checkProduct(id: UUID, quantity: Int) throws -&amp;#x3E; ProductDetailsResponse
  var req: Request? { get set }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have added &lt;code class=&quot;highlighter-rouge&quot;&gt;var req: Request?&lt;/code&gt; to the protocol just because it’s easy to use &lt;code class=&quot;highlighter-rouge&quot;&gt;client().get()&lt;/code&gt; method and get status from external service inside the implementation.&lt;/p&gt;

&lt;p&gt;Now create a controller that will have &lt;code class=&quot;highlighter-rouge&quot;&gt;checkAvailability&lt;/code&gt; function:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor
import Foundation

final class AvailabilityController {
  
  var availabilityChecker: AvailabilityCheckerProtocol
  
  init(availabilityChecker: AvailabilityCheckerProtocol) {
    self.availabilityChecker = availabilityChecker
  }
  
  func checkAvailability(_ req: Request) throws -&amp;#x3E; Future&amp;#x3C;Response&amp;#x3E; {
    let promise = req.eventLoop.newPromise(Response.self)
    availabilityChecker.req = req
    
    let productID = try req.parameters.next(UUID.self)
    let quantity = try req.parameters.next(Int.self)
    
    DispatchQueue.global().async {
      do {
        let productDetails = try self.availabilityChecker.checkProduct(id: productID, quantity: quantity)
        
        _ = productDetails.encode(status: (productDetails.quantity &amp;#x3E;= quantity ? .ok : .notFound), for: req).map {
          promise.succeed(result: $0)
        }
      }
      catch {
        promise.fail(error: error)
      }
    }
    
    return promise.futureResult
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Standard route for this will be &lt;code class=&quot;highlighter-rouge&quot;&gt;routes.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor

public func routes(_ router: Router) throws {
  let availabilityController = AvailabilityController(availabilityChecker: AvailabilityChecker())
  router.get(&amp;#x22;status&amp;#x22;, UUID.parameter, Int.parameter, use: availabilityController.checkAvailability)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you would like, you can check the implementation of &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityChecker()&lt;/code&gt; &lt;a href=&quot;https://github.com/mikina/Mocking-Dependencies-Vapor3/blob/master/Sources/App/Models/AvailabilityChecker.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;here&lt;/a&gt;. It is a simple class that conforms to &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityCheckerProtocol&lt;/code&gt; protocol and gets data using &lt;code class=&quot;highlighter-rouge&quot;&gt;req.client().get()&lt;/code&gt;.&lt;/p&gt;

&lt;h4 id=&quot;writing-the-test-&quot;&gt;Writing the test 🛠&lt;/h4&gt;

&lt;p&gt;The trick is that when writing the test you have to initialize controller using &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; app instance, otherwise the router will not be available. Since the parameters are taken from &lt;code class=&quot;highlighter-rouge&quot;&gt;req.parameters&lt;/code&gt;, you need to inject a special test router into the &lt;code class=&quot;highlighter-rouge&quot;&gt;Application&lt;/code&gt; instance.&lt;/p&gt;

&lt;p&gt;To do this you can use some of the extensions that are used to test &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; itself. You can find those &lt;a href=&quot;https://github.com/vapor/vapor/blob/3.3.0/Tests/VaporTests/ApplicationTests.swift#L816-L933&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;➡️ here&lt;/a&gt;. Don’t forget to make the extension public so other tests can see it.&lt;/p&gt;

&lt;p&gt;Take a look at the &lt;code class=&quot;highlighter-rouge&quot;&gt;makeTest(configure:routes:)&lt;/code&gt; function. This function is getting &lt;code class=&quot;highlighter-rouge&quot;&gt;Router&lt;/code&gt; as an input parameter. Instead of providing &lt;code class=&quot;highlighter-rouge&quot;&gt;routes(_ router: Router)&lt;/code&gt; from &lt;a href=&quot;https://github.com/mikina/Mocking-Dependencies-Vapor3/blob/master/Sources/App/routes.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;routes.swift&lt;/a&gt; file, all you need to do is to create your own routes with mocked dependencies and pass it just for testing.&lt;/p&gt;

&lt;p&gt;Create XCTest file &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityTests.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import XCTest
@testable import Vapor
@testable import App

final class AvailabilityTests: XCTestCase {
  
  var app: Application?
  
  override func setUp() {
    super.setUp()
    
    app = try! Application.makeTest(routes: testRoutes)
  }
  
  override func tearDown() {
    super.tearDown()
    
    app = nil
  }
  
  private func testRoutes(_ router: Router) throws {
    let availabilityVC = AvailabilityController(availabilityChecker: AvailabilityCheckerMock())
    router.get(&amp;#x22;status&amp;#x22;, UUID.parameter, Int.parameter,
               use: availabilityVC.checkAvailability)
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;As you can see &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityController&lt;/code&gt; now has injected mock object &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityCheckerMock()&lt;/code&gt;. It is simulating responses from server:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import XCTest
@testable import Vapor
@testable import App

class AvailabilityCheckerMock: AvailabilityCheckerProtocol {
  var req: Request?
  
  private let products = [
    ProductDetails(id: UUID(uuidString: &amp;#x22;32AAEE05-C84C-4B6D-94F8-78648323807E&amp;#x22;)!, quantity: 10),
    ProductDetails(id: UUID(uuidString: &amp;#x22;596CFCC7-63D8-4123-BF8B-2C598739DB53&amp;#x22;)!, quantity: 50)
  ]
  
  func checkProduct(id: UUID, quantity: Int) throws -&amp;#x3E; ProductDetailsResponse {
    guard let product = products.filter({$0.id == id}).first else {
      return ProductDetailsResponse(quantity: 0, status: .unavailable)
    }
    
    guard product.quantity &amp;#x3E;= quantity else {
      return ProductDetailsResponse(quantity: product.quantity, status: .unavailable)
    }
    
    return ProductDetailsResponse(quantity: product.quantity, status: .available)
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let’s say you would like to check if the controller is returning &lt;code class=&quot;highlighter-rouge&quot;&gt;404&lt;/code&gt; code and status &lt;code class=&quot;highlighter-rouge&quot;&gt;.unavailable&lt;/code&gt; when user asks for too many products with id &lt;code class=&quot;highlighter-rouge&quot;&gt;596CFCC7-63D8-4123-BF8B-2C598739DB53&lt;/code&gt;.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;func testCheckProductAvailabilityNotEnough() throws {
  
  let expectation = self.expectation(description: &amp;#x22;Availability&amp;#x22;)
  var responseData: Response?
  var productDetails: ProductDetailsResponse?
  
  try app?.test(.GET, &amp;#x22;/status/596CFCC7-63D8-4123-BF8B-2C598739DB53/51&amp;#x22;) { response in
    responseData = response
    let decoder = JSONDecoder()
    productDetails = try decoder.decode(ProductDetailsResponse.self, from: response.http.body.data!)
    
    expectation.fulfill()
  }
  
  waitForExpectations(timeout: 5, handler: nil)
  
  XCTAssertEqual(responseData?.http.status, .notFound)
  XCTAssertEqual(responseData?.http.contentType, MediaType.json)
  XCTAssertEqual(productDetails?.quantity, 50)
  XCTAssertEqual(productDetails?.status, .unavailable)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;⚠️ Don’t forget to use &lt;code class=&quot;highlighter-rouge&quot;&gt;expectations&lt;/code&gt; and fulfill it inside the closure.&lt;/p&gt;

&lt;p&gt;This test will try to reach the url: &lt;code class=&quot;highlighter-rouge&quot;&gt;/status/596CFCC7-63D8-4123-BF8B-2C598739DB53/51&lt;/code&gt;. Still, &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityController&lt;/code&gt; will respond to this call, but instead of &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityChecker()&lt;/code&gt; the mocked version &lt;code class=&quot;highlighter-rouge&quot;&gt;AvailabilityCheckerMock()&lt;/code&gt; will be used.&lt;/p&gt;

&lt;p&gt;For more tests and the overall picture take a look at &lt;a href=&quot;https://github.com/mikina/Mocking-Dependencies-Vapor3/blob/master/Tests/AppTests/AvailabilityTests.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;➡️AvailabilityTests.swift&lt;/a&gt; file.&lt;/p&gt;

&lt;h4 id=&quot;summary-&quot;&gt;Summary ✅&lt;/h4&gt;

&lt;p&gt;Remember, you are not checking whether an external service is working, you are checking if controller is responding correctly. By providing the data from a different source, you can simply test the behavior of the controller. Think of this as switching the &lt;code class=&quot;highlighter-rouge&quot;&gt;datasource&lt;/code&gt; in iOS 😊&lt;/p&gt;

&lt;p&gt;Please keep in mind that this is a very simple example just to show how easily you can inject different routes in Vapor. In a normal situation you may consider moving logic from controllers to models and testing those models.&lt;/p&gt;

&lt;p&gt;The whole sample app is available &lt;a href=&quot;https://github.com/mikina/Mocking-Dependencies-Vapor3&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;➡️here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;What do you think? Have you been testing controllers in your projects? Do you have any tips or advice that you would like to share? Let me know - along with your questions, comments or feedback - on Twitter &lt;a href=&quot;https://twitter.com/mikemikina&quot; target=&quot;_blank&quot;&gt;@mikemikina&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Happy coding 😊&lt;/p&gt;</content><author><name>Mike Mikina</name></author><summary type="html">Testing controllers with external dependencies, especially ones involving HTTP requests, is very tricky. That’s because sending actual requests would create a test that you could not rely on and is very slow. But there is a very simple technique that you are probably familiar with: using protocols and injecting dependencies into controllers. Recently I ran into an issue when I was trying to get parameters from routes inside unit tests. So today I would like to show you how easily you can also pass proper routes into testing functions in Vapor 3.</summary></entry><entry><title type="html">Watermarking photos with ImageMagick, Vapor 3 and Swift on macOS and Linux</title><link href="https://mikemikina.com/blog/watermarking-photos-with-imagemagick-vapor-3-and-swift-on-macos-and-linux/" rel="alternate" type="text/html" title="Watermarking photos with ImageMagick, Vapor 3 and Swift on macOS and Linux" /><published>2018-12-06T17:27:36+01:00</published><updated>2018-12-06T17:27:36+01:00</updated><id>https://mikemikina.com/blog/watermarking-photos-with-imagemagick-vapor-3-and-swift-on-macos-and-linux</id><content type="html" xml:base="https://mikemikina.com/blog/watermarking-photos-with-imagemagick-vapor-3-and-swift-on-macos-and-linux/">&lt;p&gt;Back in the days (you remember web 2.0? 😉) I used to do a lot of programming around photos. Resizing, scaling, rotating and converting between formats. Recently, I had to create a web service that generates watermarked images using &lt;a href=&quot;https://vapor.codes/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Vapor&lt;/a&gt;. It turns out that there are not very many libraries for image manipulation yet, so this simple task became an interesting problem to research.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;There are two major image manipulation libraries: &lt;a href=&quot;https://libgd.github.io/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;GD&lt;/a&gt; and &lt;a href=&quot;https://www.imagemagick.org/script/index.php&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;ImageMagick&lt;/a&gt;. ImageMagick is a bit of an advanced library so I decided to go with this one first. There is an interesting Swift wrapper for ImageMagick called &lt;a href=&quot;https://github.com/naithar/MagickWand&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;MagickWand&lt;/a&gt;. Unfortunately, it doesn’t support text manipulation at all so I had to dig deeper. I couldn’t find anything useful so I thought “why not to just use some ImageMagick C functions in Swift?” It turns out that this is quite easy to do!&lt;/p&gt;

&lt;p&gt;If you are just interested in one particular topic, feel free to use links below:&lt;/p&gt;

&lt;div class=&quot;toc&quot;&gt;
  &lt;ul&gt;
    &lt;li&gt;&lt;a href=&quot;#install-imagemagick&quot;&gt;Install ImageMagick&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#wrapping-imagemagick-into-a-swift-package&quot;&gt;Wrapping ImageMagick into a Swift Package&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#how-to-use-imagemagick-with-swift&quot;&gt;How to use ImageMagick with Swift&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#serving-watermarked-photos-in-vapor&quot;&gt;Serving watermarked photos in Vapor&lt;/a&gt;&lt;/li&gt;
    &lt;li&gt;&lt;a href=&quot;#summary&quot;&gt;Summary&lt;/a&gt;&lt;/li&gt;
  &lt;/ul&gt;
&lt;/div&gt;

&lt;h4 id=&quot;install-imagemagick&quot;&gt;Install ImageMagick&lt;/h4&gt;

&lt;p&gt;In the &lt;a href=&quot;https://www.imagemagick.org/script/develop.php&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;develop&lt;/a&gt; section on ImageMagick website you can find documentation for &lt;a href=&quot;https://www.imagemagick.org/script/magick-wand.php&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;MagickWand&lt;/a&gt; and &lt;a href=&quot;https://www.imagemagick.org/script/magick-core.php&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;MagickCore&lt;/a&gt;. Those are the interfaces written in C for interacting with ImageMagick processing libraries. Wrapping it in a Swift package is very easy, but first let’s install ImageMagick.&lt;/p&gt;

&lt;p&gt;Let’s start with macOS. You can compile ImageMagick by yourself but for macOS it’s easier just to use &lt;a href=&quot;https://brew.sh/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Homebrew&lt;/a&gt;.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ brew install imagemagick@6&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;If you don’t specify &lt;code class=&quot;highlighter-rouge&quot;&gt;@6&lt;/code&gt; it will install the latest version by default. I had issues with version 7 on Linux so I decided to use older versions for both macOS and Linux.&lt;/p&gt;

&lt;p&gt;After the installation you will notice that homebrew is not creating symlinks (more information about: &lt;a href=&quot;https://docs.brew.sh/How-to-build-software-outside-Homebrew-with-Homebrew-keg-only-dependencies&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;keg-only dependencies&lt;/a&gt;). This part is important in order to get information that you need about ImageMagick:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;For pkg-config to find imagemagick@6 you may need to set:
export PKG_CONFIG_PATH=&quot;/usr/local/opt/imagemagick@6/lib/pkgconfig&quot;&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;You can just add &lt;code class=&quot;highlighter-rouge&quot;&gt;PKG_CONFIG_PATH&lt;/code&gt; in terminal before each &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt; command but it’s easier to add it permanently, if you are using &lt;a href=&quot;https://ohmyz.sh/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;zsh&lt;/a&gt; just run:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ echo 'export PKG_CONFIG_PATH=&quot;/usr/local/opt/imagemagick@6/lib/pkgconfig:$PKG_CONFIG_PATH&quot;' &amp;gt;&amp;gt; ~/.zshrc&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;For Linux I’m using &lt;code class=&quot;highlighter-rouge&quot;&gt;Ubuntu 18.04&lt;/code&gt; with &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift 4.2&lt;/code&gt;. If you have pre installed ImageMagick it’s better to remove it before compiling:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ apt-get remove imagemagick &amp;amp;&amp;amp; apt-get autoremove&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;You can get ImageMagick package &lt;a href=&quot;https://www.imagemagick.org/download/&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ wget https://www.imagemagick.org/download/ImageMagick-6.9.10-12.tar.gz
➜ tar xzvf ImageMagick-6.9.10-12.tar.gz
➜ cd ImageMagick-6.9.10-12&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Inside ImageMagick source directory run:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ ./configure&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;When the configuration is finished, find the section called &lt;code class=&quot;highlighter-rouge&quot;&gt;Delegate Library Configuration&lt;/code&gt; and check if &lt;code class=&quot;highlighter-rouge&quot;&gt;JPEG&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;PNG support&lt;/code&gt; is there. If you see &lt;code class=&quot;highlighter-rouge&quot;&gt;no&lt;/code&gt; on the third column you probably don’t have required dependencies like &lt;code class=&quot;highlighter-rouge&quot;&gt;libpng12-dev&lt;/code&gt; and &lt;code class=&quot;highlighter-rouge&quot;&gt;libjpeg-dev&lt;/code&gt;. You can easily install those using apt-get.&lt;/p&gt;

&lt;p&gt;If the configuration is alright, just compile the source:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ make&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;and install:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ make install&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;To confirm that installation finished correctly just run:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ convert --version&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;If you see this error:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;convert: error while loading shared libraries: libMagickCore-6.Q16.so.6: cannot open shared object file: No such file or directory&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Just run:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ ldconfig /usr/local/lib/&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;ImageMagick has been installed. Now we can start with the fun part 😄&lt;/p&gt;

&lt;h4 id=&quot;wrapping-imagemagick-into-a-swift-package&quot;&gt;Wrapping ImageMagick into a Swift Package&lt;/h4&gt;

&lt;p&gt;To use &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; inside Swift code you need to wrap it into a Swift system module package. By exposing header files your Swift code will be able to use all of &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; functions.&lt;/p&gt;

&lt;p&gt;Let’s begin by creating a new directory called &lt;code class=&quot;highlighter-rouge&quot;&gt;SwiftImageMagick&lt;/code&gt; and initialize new Swift system module using Swift package manager:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ mkdir SwiftImageMagick
➜ cd SwiftImageMagick
➜ swift package init --type system-module&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Open &lt;code class=&quot;highlighter-rouge&quot;&gt;module.modulemap&lt;/code&gt; file. You should see code generated by SPM:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;module SwiftImageMagick [system] {
  header &quot;/usr/include/SwiftImageMagick.h&quot;
  link &quot;SwiftImageMagick&quot;
  export *
}&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;Let’s start with macOS first. Change the name of the module to &lt;code class=&quot;highlighter-rouge&quot;&gt;SwiftImageMagick&lt;/code&gt; &amp;gt; &lt;code class=&quot;highlighter-rouge&quot;&gt;SwiftImageMagickMac&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now, in order to tell how to compile and link all of the packages, you need to use &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt; tool. You should already have it, if not just use brew to install it:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ brew install pkg-config&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;As I mentioned earlier you need to have &lt;code class=&quot;highlighter-rouge&quot;&gt;PKG_CONFIG_PATH&lt;/code&gt; set so &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt; can find &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt;.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜ pkg-config --list-all | grep -i Magick&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;You should see a couple of packages:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜  ~ pkg-config --list-all | grep -i Magick
Magick++              Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
Wand-6.Q16            MagickWand - MagickCore - C API for ImageMagick (ABI Q16)
ImageMagick++         ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
MagickWand            MagickWand - MagickWand - C API for ImageMagick (ABI Q16)
ImageMagick           ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16)
MagickCore-6.Q16      MagickCore - MagickCore - C API for ImageMagick (ABI Q16)
Magick++-6.Q16        Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
Wand                  MagickWand - MagickCore - C API for ImageMagick (ABI Q16)
MagickWand-6.Q16      MagickWand - MagickWand - C API for ImageMagick (ABI Q16)
ImageMagick++-6.Q16   ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
ImageMagick-6.Q16     ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16)
MagickCore            MagickCore - MagickCore - C API for ImageMagick (ABI Q16)&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;To find the header file path for &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
&lt;code class=&quot;language-bash&quot;&gt;➜  ~ pkg-config --cflags-only-I MagickWand       
-I/usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6&lt;/code&gt;
&lt;/pre&gt;

&lt;p&gt;In this directory &lt;code class=&quot;highlighter-rouge&quot;&gt;/usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6&lt;/code&gt; you will find headers for MagickWand: &lt;code class=&quot;highlighter-rouge&quot;&gt;wand/MagickWand.h&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And the linker flags:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜  ~ pkg-config --libs MagickWand
-L/usr/local/Cellar/imagemagick@6/6.9.10-12/lib -lMagickWand-6.Q16 -lMagickCore-6.Q16&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Once again, open &lt;code class=&quot;highlighter-rouge&quot;&gt;module.modulemap&lt;/code&gt;, add header and link:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;module SwiftImageMagickMac [system] {
  header &quot;/usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6/wand/MagickWand.h&quot;
  link &quot;MagickWand-6.Q16&quot;
  link &quot;MagickCore-6.Q16&quot;
  export *
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s do the same for Linux. You should also have &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt; on your linux machine, if not just use:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ apt-get install pkg-config&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s check what &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt; sees:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;pkg-config --list-all | grep -i Magick

root@8cc05b6015fc:~# pkg-config --list-all | grep -i Magick
Wand-6.Q16            MagickWand - MagickCore - C API for ImageMagick (ABI Q16)
ImageMagick++-6.Q16   ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
MagickWand-6.Q16      MagickWand - MagickWand - C API for ImageMagick (ABI Q16)
ImageMagick           ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16)
Wand                  MagickWand - MagickCore - C API for ImageMagick (ABI Q16)
ImageMagick-6.Q16     ImageMagick - ImageMagick - convert, edit, and compose images (ABI Q16)
MagickCore            MagickCore - MagickCore - C API for ImageMagick (ABI Q16)
Magick++-6.Q16        Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
MagickWand            MagickWand - MagickWand - C API for ImageMagick (ABI Q16)
ImageMagick++         ImageMagick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
Magick++              Magick++ - Magick++ - C++ API for ImageMagick (ABI Q16)
MagickCore-6.Q16      MagickCore - MagickCore - C API for ImageMagick (ABI Q16)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Start with the headers:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;root@8cc05b6015fc:~# pkg-config --cflags-only-I MagickWand
-I/usr/local/include/ImageMagick-6&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And the linker flags:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;root@8cc05b6015fc:~# pkg-config --libs MagickWand
-L/usr/local/lib -lMagickWand-6.Q16 -lMagickCore-6.Q16&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To the &lt;code class=&quot;highlighter-rouge&quot;&gt;module.modulemap&lt;/code&gt; below macOS part add linux module:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;module SwiftImageMagickMac [system] {
  header &quot;/usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6/wand/MagickWand.h&quot;
  link &quot;MagickWand-6.Q16&quot;
  link &quot;MagickCore-6.Q16&quot;
  export *
}

module SwiftImageMagickLinux [system] {
  header &quot;/usr/local/include/ImageMagick-6/wand/MagickWand.h&quot;
  link &quot;MagickWand-6.Q16&quot;
  link &quot;MagickCore-6.Q16&quot;
  export *
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Remember to remove the dependencies section from &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.swift&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;// swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: &quot;SwiftImageMagick&quot;
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now when everything is in place don’t forget to create a git repository and commit your changes.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ git init
➜ git add .
➜ git commit -m &quot;Initial commit.&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now our package is ready. Let’s use it 😄&lt;/p&gt;

&lt;h4 id=&quot;how-to-use-imagemagick-with-swift&quot;&gt;How to use ImageMagick with Swift&lt;/h4&gt;

&lt;p&gt;Now let’s create simple test app that will import the ImageMagick library and create 100x100px image filled with a red background, just to be sure that our package is working.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ mkdir MagicTest
➜ cd MagicTest
➜ swift package init --type executable

Creating executable package: MagicTest
Creating Package.swift
Creating README.md
Creating .gitignore
Creating Sources/
Creating Sources/MagicTest/main.swift
Creating Tests/
Creating Tests/LinuxMain.swift
Creating Tests/MagicTestTests/
Creating Tests/MagicTestTests/MagicTestTests.swift
Creating Tests/MagicTestTests/XCTestManifests.swift&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;SPM will create the basic structure for you; &lt;code class=&quot;highlighter-rouge&quot;&gt;--type executable&lt;/code&gt; will tell SPM to create a command line tool.&lt;/p&gt;

&lt;p&gt;First of all, you need to add &lt;code class=&quot;highlighter-rouge&quot;&gt;SwiftImageMagick&lt;/code&gt; as a dependency to &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.swift&lt;/code&gt;. You can add it as path to your local git repository:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;// swift-tools-version:4.2
// The swift-tools-version declares the minimum version of Swift required to build this package.

import PackageDescription

let package = Package(
    name: &quot;MagicTest&quot;,
    dependencies: [
        .package(url: &quot;../SwiftImageMagick&quot;, .branch(&quot;master&quot;)),
    ],
    targets: [
        .target(
            name: &quot;MagicTest&quot;,
            dependencies: []),
        .testTarget(
            name: &quot;MagicTestTests&quot;,
            dependencies: [&quot;MagicTest&quot;]),
    ]
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Compile it to be sure that your dependency is reachable:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜  MagicTest swift build
Fetching /Users/mike/Documents/projects/playground/SwiftImageMagick
Completed resolution in 0.35s
Cloning /Users/mike/Documents/projects/playground/SwiftImageMagick
Resolving /Users/mike/Documents/projects/playground/SwiftImageMagick at master
'SwiftImageMagick' /Users/mike/Documents/projects/playground/MagicTest/.build/checkouts/SwiftImageMagick-2878331876767139303: warning: system packages are deprecated; use system library targets instead
Compile Swift Module 'MagicTest' (1 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/MagicTest&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you are using &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift 4.2&lt;/code&gt; you will also see the following: &lt;code class=&quot;highlighter-rouge&quot;&gt;warning: system packages are deprecated; use system library targets instead&lt;/code&gt; - this is related to &lt;a href=&quot;https://github.com/apple/swift-evolution/blob/master/proposals/0208-package-manager-system-library-targets.md&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;System Library Targets&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Then, inside main file of your app (&lt;code class=&quot;highlighter-rouge&quot;&gt;./Sources/MagicTest/main.swift&lt;/code&gt;) remove everything and import &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; library.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;#if os(Linux)
import SwiftImageMagickLinux
#else
import SwiftImageMagickMac
#endif&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can tell if you program is running on Linux or on macOS by using &lt;a href=&quot;https://github.com/apple/swift-evolution/blob/master/proposals/0075-import-test.md&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Swift build configuration import test&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now to compile the app you also need to provide the path to headers and linker, the same one that you got last time using &lt;code class=&quot;highlighter-rouge&quot;&gt;pkg-config&lt;/code&gt;. It’s also a good idea to check if there are any other flags that you need to provide:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜  MagicTest pkg-config --cflags-only-other ImageMagick
-DMAGICKCORE_HDRI_ENABLE=0 -DMAGICKCORE_QUANTUM_DEPTH=16&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Let’s add them all up:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ swift build -Xswiftc -I/usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6 -Xlinker -L/usr/local/Cellar/imagemagick@6/6.9.10-12/lib -Xlinker -lMagickWand-6.Q16 -Xlinker -lMagickCore-6.Q16 -Xcc -DMAGICKCORE_HDRI_ENABLE=0 -Xcc -DMAGICKCORE_QUANTUM_DEPTH=16
Fetching /Users/mike/Documents/projects/playground/SwiftImageMagick
Completed resolution in 0.35s
Cloning /Users/mike/Documents/projects/playground/SwiftImageMagick
Resolving /Users/mike/Documents/projects/playground/SwiftImageMagick at master
'SwiftImageMagick' /Users/mike/Documents/projects/playground/MagicTest/.build/checkouts/SwiftImageMagick--9014361064470696861: warning: system packages are deprecated; use system library targets instead
Compile Swift Module 'MagicTest' (1 sources)
Linking ./.build/x86_64-apple-macosx10.10/debug/MagicTest&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Success! 😄 Library is working, now let’s create an Xcode project file and add some code.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ swift package generate-xcodeproj&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run &lt;code class=&quot;highlighter-rouge&quot;&gt;./MagicTest.xcodeproj&lt;/code&gt; using Xcode 10.&lt;/p&gt;

&lt;p&gt;When you try to compile it using Xcode you will see the same error as you had in the terminal:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/magick-config-not-found.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;magick-config.h not found&quot; src=&quot;/assets/imagemagick-vapor-3/magick-config-not-found.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1492&quot; height=&quot;252&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;It’s actually very easy to fix. Just open Build settings and find &lt;code class=&quot;highlighter-rouge&quot;&gt;Header search path&lt;/code&gt; and add the path:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/header-search-path.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Header search path&quot; src=&quot;/assets/imagemagick-vapor-3/header-search-path.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1920&quot; height=&quot;550&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Do the same for &lt;code class=&quot;highlighter-rouge&quot;&gt;Library search path&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/library-search-path.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Library search path&quot; src=&quot;/assets/imagemagick-vapor-3/library-search-path.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1928&quot; height=&quot;496&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Don’t forget to add &lt;code class=&quot;highlighter-rouge&quot;&gt;Other Swift Flags&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/other-swift-flags.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Other Swift Flags&quot; src=&quot;/assets/imagemagick-vapor-3/other-swift-flags.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1852&quot; height=&quot;504&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Hit &lt;code class=&quot;highlighter-rouge&quot;&gt;Cmd + R&lt;/code&gt; and everything should compile and run without any warnings.&lt;/p&gt;

&lt;p&gt;Of course, all of these changes will be gone when you would like to regenerate &lt;code class=&quot;highlighter-rouge&quot;&gt;xcodeproj&lt;/code&gt; again in the future. You can use &lt;code class=&quot;highlighter-rouge&quot;&gt;xcconfig&lt;/code&gt; to store them but be aware that there are some weird issues with &lt;code class=&quot;highlighter-rouge&quot;&gt;Xcode 10&lt;/code&gt; (bug reported on &lt;a href=&quot;https://openradar.appspot.com/40873121&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;radar&lt;/a&gt;).&lt;/p&gt;

&lt;p&gt;Create a new file: &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.xcconfig&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;LIBRARY_SEARCH_PATHS = /usr/local/Cellar/imagemagick@6/6.9.10-12/lib
HEADER_SEARCH_PATHS = /usr/local/Cellar/imagemagick@6/6.9.10-12/include/ImageMagick-6
OTHER_SWIFT_FLAGS = -Xcc -DMAGICKCORE_HDRI_ENABLE=0 -Xcc -DMAGICKCORE_QUANTUM_DEPTH=16&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Then generate the xcode project file:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;➜ swift package generate-xcodeproj --xcconfig-overrides Package.xcconfig&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The project should now compile without any errors or warnings.&lt;/p&gt;

&lt;p&gt;When you have a properly working xcode project, open once again: &lt;code class=&quot;highlighter-rouge&quot;&gt;Sources/MagicTest/main.swift&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Below &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick import&lt;/code&gt; add this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickWandGenesis()

let wand = NewMagickWand()
let pixel = NewPixelWand()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;MagickWandGenesis&lt;/code&gt; initializes the MagickWand environment. You also need to terminate the environment after you finish work. &lt;code class=&quot;highlighter-rouge&quot;&gt;NewMagickWand&lt;/code&gt; creates new wand resource that represents a structure which contains image. &lt;code class=&quot;highlighter-rouge&quot;&gt;NewPixelWand&lt;/code&gt; creates new pixel wand which is responsible for color manipulation.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;PixelSetColor(pixel, &quot;red&quot;)
MagickSetBackgroundColor(wand, pixel)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;PixelSetColor&lt;/code&gt; will set the color of the pixel wand. Use name - &lt;code class=&quot;highlighter-rouge&quot;&gt;&quot;red&quot;&lt;/code&gt;, hex value &lt;code class=&quot;highlighter-rouge&quot;&gt;#FF0000&lt;/code&gt; or rbg - &lt;code class=&quot;highlighter-rouge&quot;&gt;rgb(255,0,0)&lt;/code&gt;. You can even use “transparent” to make a transparent background if you save it as png.&lt;/p&gt;

&lt;p&gt;Now, when color is applied to the wand, just create a new image and save it:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickNewImage(wand, 100, 100, pixel)
MagickWriteImage(wand, &quot;test.jpg&quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can also provide the absolute path to the image, but if you don’t do so remember that the file will be created in &lt;code class=&quot;highlighter-rouge&quot;&gt;Xcode DerivedData&lt;/code&gt; catalog.&lt;/p&gt;

&lt;p&gt;It’s almost done: just release memory for the wand, pixel and terminate the environment:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;DestroyMagickWand(wand)
DestroyPixelWand(pixel)
MagickWandTerminus()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now run the application. I have uploaded the whole sample app to the &lt;a href=&quot;https://github.com/mikina/MagicTest&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;GitHub&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;If you didn’t provide the absolute path for the file, you can just open &lt;code class=&quot;highlighter-rouge&quot;&gt;Products&lt;/code&gt;, select program name and click &lt;code class=&quot;highlighter-rouge&quot;&gt;Show in Finder&lt;/code&gt;. You will find &lt;code class=&quot;highlighter-rouge&quot;&gt;test.jpg&lt;/code&gt; there:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/show-in-finder.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Show in finder&quot; src=&quot;/assets/imagemagick-vapor-3/show-in-finder.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;670&quot; height=&quot;246&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;The &lt;code class=&quot;highlighter-rouge&quot;&gt;test.jpg&lt;/code&gt; should looks like this:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/test.jpg&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;test.jpg&quot; src=&quot;/assets/imagemagick-vapor-3/test.jpg&quot; class=&quot;img-responsive center-block&quot; width=&quot;100&quot; height=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;So the ImageMagick is working fine. Let’s create new Vapor app and add watermark text 😄&lt;/p&gt;

&lt;p&gt;At the beginning of this post I thought that I would create a helper library for image manipulation but this post is already too long so let’s just keep it simple and use ImageMagick commands inside Vapor. Library for image manipulation will be a good topic for the next post 😉&lt;/p&gt;

&lt;h4 id=&quot;serving-watermarked-photos-in-vapor&quot;&gt;Serving watermarked photos in Vapor&lt;/h4&gt;

&lt;p&gt;This one will be pretty simple, just create a new Vapor project:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ vapor new WatermarkPhotos&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;By default, &lt;code class=&quot;highlighter-rouge&quot;&gt;vapor new&lt;/code&gt; will create a project based on the api template. Right now, you need to add the &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; wrapper dependency. It’s a good idea to update Swift version to &lt;code class=&quot;highlighter-rouge&quot;&gt;4.2&lt;/code&gt; and Vapor to &lt;code class=&quot;highlighter-rouge&quot;&gt;3.1.0&lt;/code&gt; if it’s still on &lt;code class=&quot;highlighter-rouge&quot;&gt;3.0.0&lt;/code&gt; in your &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.swift&lt;/code&gt; file:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;// swift-tools-version:4.2
import PackageDescription

let package = Package(
    name: &quot;WatermarkPhotos&quot;,
    dependencies: [
        // 💧 A server-side Swift web framework.
        .package(url: &quot;https://github.com/vapor/vapor.git&quot;, from: &quot;3.1.0&quot;),

        // 🔵 Swift ORM (queries, models, relations, etc) built on SQLite 3.
        .package(url: &quot;https://github.com/vapor/fluent-sqlite.git&quot;, from: &quot;3.0.0&quot;),

        // 🎨 ImageMagick wrapper
        .package(url: &quot;https://github.com/mikina/SwiftImageMagick&quot;, .branch(&quot;master&quot;))
    ],
    targets: [
        .target(name: &quot;App&quot;, dependencies: [&quot;FluentSQLite&quot;, &quot;Vapor&quot;]),
        .target(name: &quot;Run&quot;, dependencies: [&quot;App&quot;]),
        .testTarget(name: &quot;AppTests&quot;, dependencies: [&quot;App&quot;])
    ]
)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Generate the Xcode project file and open it:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ cd WatermarkPhotos/
➜ vapor xcode -y&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It may take a while as it has to fetch all of the dependencies.&lt;/p&gt;

&lt;p&gt;At this point you have everything you need to get started. Let’s write a very simple test. It’s hard to compare image to image, as it would make your tests flaky, so let’s just check if watermark endpoint response is:&lt;/p&gt;

&lt;ul&gt;
  &lt;li&gt;Returning status code &lt;code class=&quot;highlighter-rouge&quot;&gt;200 .ok&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Content type is set to &lt;code class=&quot;highlighter-rouge&quot;&gt;image/jpeg&lt;/code&gt;&lt;/li&gt;
  &lt;li&gt;Content length is greater than zero&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Create a new test file: &lt;code class=&quot;highlighter-rouge&quot;&gt;/Tests/AppTests/PhotoTests.swift&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import XCTest
@testable import Vapor
@testable import App

final class PhotoTests: XCTestCase {

}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Unfortunately, &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor 3.1&lt;/code&gt; doesn’t have any helpers for tests yet, but you can use some of the extensions that are used to test Vapor itself. You can find those &lt;a href=&quot;https://github.com/vapor/vapor/blob/3.1/Tests/VaporTests/ApplicationTests.swift#L692-L896&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Create a new tests helper: &lt;code class=&quot;highlighter-rouge&quot;&gt;/Tests/AppTests/TestsHelper.swift&lt;/code&gt; and copy this &lt;a href=&quot;https://github.com/vapor/vapor/blob/3.1/Tests/VaporTests/ApplicationTests.swift#L692-L896&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;private&lt;/a&gt; application extension. Don’t forget to make it public so other tests can see it. It should look like &lt;a href=&quot;https://github.com/mikina/WatermarkingPhotos/blob/master/Tests/AppTests/TestsHelper.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;this&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now go back to &lt;code class=&quot;highlighter-rouge&quot;&gt;PhotoTests.swift&lt;/code&gt; and add this simple test:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import XCTest
@testable import Vapor
@testable import App

final class PhotoTests: XCTestCase {
  func testGetWatermakedPhoto() throws {
    let app = try Application.makeTest(routes: routes)

    try app.test(.GET, &quot;/photos/show/barcelona&quot;) { response in
      XCTAssertEqual(response.http.status, .ok)
      XCTAssertEqual(response.http.contentType, MediaType.jpeg)
      let length = response.http.headers[&quot;content-length&quot;].first!
      XCTAssertGreaterThan(Int(length)!, 0)
    }
  }

  static let allTests = [
    (&quot;testGetWatermakedPhoto&quot;, testGetWatermakedPhoto)
  ]
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course, this test will fail right now because there is no photo controller yet, so let’s go and create one.&lt;/p&gt;

&lt;p&gt;Create file: &lt;code class=&quot;highlighter-rouge&quot;&gt;/Sources/App/Controllers/PhotoController.swift&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor
import Foundation

final class PhotoController {
  func show(_ req: Request) throws -&amp;gt; Response {
    return Response(using: req)
  }
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Also, add the route for it in: &lt;code class=&quot;highlighter-rouge&quot;&gt;/Sources/App/routes.swift&lt;/code&gt;&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;import Vapor

/// Register your application's routes here.
public func routes(_ router: Router) throws {
    // Photos controller
    let photoController = PhotoController()
    router.get(&quot;photos&quot;, &quot;show&quot;, String.parameter, use: photoController.show)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;If you are not familiar with routes, &lt;code class=&quot;highlighter-rouge&quot;&gt;String.parameter&lt;/code&gt; means that you can pass a string value inside the route and it will be available as request parameters inside the controller.&lt;/p&gt;

&lt;p&gt;Your photos url will looks like this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;http://localhost:8080/photos/show/barcelona&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;At this point it’s just responding with an empty page. Let’s go back to &lt;code class=&quot;highlighter-rouge&quot;&gt;/Sources/App/Controllers/PhotoController.swift&lt;/code&gt; and add some code.&lt;/p&gt;

&lt;p&gt;In a real life application you would keep a list of photos in a database and actual files inside external storage like &lt;code class=&quot;highlighter-rouge&quot;&gt;S3&lt;/code&gt; on &lt;code class=&quot;highlighter-rouge&quot;&gt;AWS&lt;/code&gt;. But for this demo let’s keep it simple, just create new directory called &lt;code class=&quot;highlighter-rouge&quot;&gt;photos&lt;/code&gt; inside the main project directory and add some photos there.&lt;/p&gt;

&lt;p&gt;Inside &lt;code class=&quot;highlighter-rouge&quot;&gt;PhotoController.swift&lt;/code&gt; add photos list:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;private let photosList = [&quot;barcelona.jpg&quot;, &quot;oslo.jpg&quot;, &quot;porto.jpg&quot;, &quot;rome.jpg&quot;]
private let photosDirectory = &quot;photos&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You can get the photo name from request &lt;code class=&quot;highlighter-rouge&quot;&gt;parameters&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let name = try req.parameters.next(String.self)
let filename = name.lowercased().appending(&quot;.jpg&quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Just check if the file is on the list:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;guard photosList.contains(filename) else {
  throw Abort(.notFound, reason: &quot;Photo not found&quot;)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Before adding the watermark to the photo, let’s just load it from the disk and send it as a response.&lt;/p&gt;

&lt;p&gt;In Vapor 3.1 there is a &lt;a href=&quot;https://github.com/vapor/core/blob/3.4.4/Sources/Core/DirectoryConfig.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;DirectoryConfig&lt;/a&gt; struct which can help you get the path to the working directory.&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let directory = DirectoryConfig.detect()
let workingDirectory = URL(fileURLWithPath: directory.workDir)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;strong&gt;&lt;em&gt;Caveat:&lt;/em&gt;&lt;/strong&gt;&lt;/p&gt;

&lt;p&gt;When you will be running the app through Xcode there is one thing that you need to do. If you have checked &lt;a href=&quot;https://github.com/vapor/core/blob/3.4.4/Sources/Core/DirectoryConfig.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;DirectoryConfig&lt;/a&gt; you probably saw that there is a function for directory detection: &lt;code class=&quot;highlighter-rouge&quot;&gt;detect()&lt;/code&gt;. There is a conditional compilation flag: &lt;code class=&quot;highlighter-rouge&quot;&gt;#if Xcode&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;You need to define it in &lt;code class=&quot;highlighter-rouge&quot;&gt;Active Compilation Conditions&lt;/code&gt;:&lt;/p&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/active-compilation-conditions.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Active Compilation Conditions&quot; src=&quot;/assets/imagemagick-vapor-3/active-compilation-conditions.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1482&quot; height=&quot;260&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;Or just add it to &lt;code class=&quot;highlighter-rouge&quot;&gt;Package.xcconfig&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;SWIFT_ACTIVE_COMPILATION_CONDITIONS[config=Debug] = Xcode&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And generate the &lt;code class=&quot;highlighter-rouge&quot;&gt;xcodeproject&lt;/code&gt; file:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;➜ swift package generate-xcodeproj --xcconfig-overrides=Package.xcconfig&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Of course it will not affect a linux build.&lt;/p&gt;

&lt;p&gt;You are almost there. Now create &lt;code class=&quot;highlighter-rouge&quot;&gt;Data&lt;/code&gt; with contents of the file and return it as jpeg response:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let data = try Data(contentsOf: workingDirectory.appendingPathComponent(photosDirectory, isDirectory: true).appendingPathComponent(filename))
return req.response(data, as: .jpeg)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;PhotoController&lt;/code&gt; at this point will look like this:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;func show(_ req: Request) throws -&amp;gt; Response {

  let name = try req.parameters.next(String.self)
  let filename = name.lowercased().appending(&quot;.jpg&quot;)

  guard photosList.contains(filename) else {
    throw Abort(.notFound, reason: &quot;Photo not found&quot;)
  }

  let directory = DirectoryConfig.detect()
  let workingDirectory = URL(fileURLWithPath: directory.workDir)

  let data = try Data(contentsOf: workingDirectory.appendingPathComponent(photosDirectory, isDirectory: true).appendingPathComponent(filename))
  return req.response(data, as: .jpeg)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Run the application in Xcode and open the url:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;http://localhost:8080/photos/show/barcelona&lt;/code&gt;&lt;/pre&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/sample-photo.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Load sample photo&quot; src=&quot;/assets/imagemagick-vapor-3/sample-photo.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1824&quot; height=&quot;1254&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;p&gt;It’s time for the final step: adding the watermark.&lt;/p&gt;

&lt;p&gt;Create the model file: &lt;code class=&quot;highlighter-rouge&quot;&gt;/Sources/App/Models/Photo.swift&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;Import Vapor, Foundation and ImageMagick headers as you did in sample project:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;#if os(Linux)
import SwiftImageMagickLinux
#else
import SwiftImageMagickMac
#endif

import Vapor
import Foundation&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You will probably see an error like:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;'magick/magick-config.h' file not found&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is the same error as you had in sample app. Just add &lt;a href=&quot;https://github.com/mikina/WatermarkingPhotos/blob/master/Package.xcconfig&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Package.xcconfig&lt;/a&gt; and regenerate xcode project file:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;swift package generate-xcodeproj --xcconfig-overrides=Package.xcconfig&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Create class Photo with a file property:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;final class Photo {
  private let file: URL

  init(file: URL) throws {

    guard FileManager.default.fileExists(atPath: file.path) else {
      throw Abort(.internalServerError, reason: &quot;Photo file not found&quot;)
    }

    self.file = file
  }&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It’s a good idea to check if the file exists, as error reporting from ImageMagick is not always the best.&lt;/p&gt;

&lt;p&gt;Now create a function that will return the watermarked photo:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;public func watermarked(with font: URL, and text: String) throws -&amp;gt; Data {

  guard FileManager.default.fileExists(atPath: font.path) else {
    throw Abort(.internalServerError, reason: &quot;Font file not found&quot;)
  }&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;It takes the url to the font file that will be used and the watermark text as input.&lt;/p&gt;

&lt;p&gt;Prepare magic stack:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickWandGenesis()

let wand = NewMagickWand()
let pixel = NewPixelWand()
let draw = NewDrawingWand()&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;I have already described those methods. What’s new here is the drawing wand: it will be used to draw on the image, or in this case to attach watermark text to the image.&lt;/p&gt;

&lt;p&gt;Load the image into Magick Wand:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickReadImage(wand, file.path)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;And prepare the drawing wand:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;PixelSetColor(pixel, &quot;white&quot;)
DrawSetFillColor(draw, pixel)
DrawSetFont(draw, font.path)
DrawSetFontSize(draw, 70)
DrawSetGravity(draw, CenterGravity)
DrawAnnotation(draw, 0, 0, text)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This is pretty straight forward; The pixel wand is being set to white color and attached to the drawing wand. Font, gravity parameter and size are also applied to the drawing wand. &lt;code class=&quot;highlighter-rouge&quot;&gt;DrawAnnotation&lt;/code&gt; is attaching watermark text to the drawing wand.&lt;/p&gt;

&lt;p&gt;What’s worth mentioning here is that you can set different gravity. Gravity is telling ImageMagick where it should put the drawing so you don’t have to calculate this. Using &lt;code class=&quot;highlighter-rouge&quot;&gt;CenterGravity&lt;/code&gt; will draw the watermark text in the center of an image. Setting it to &lt;code class=&quot;highlighter-rouge&quot;&gt;SouthWestGravity&lt;/code&gt; will draw the watermark in bottom left corner. There is no need to calculate the bounding box and positioning on the screen manually.&lt;/p&gt;

&lt;p&gt;Draw the watermark text:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickDrawImage(wand, draw)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;You also need to set the image format and compression quality before getting the data:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;MagickSetImageCompressionQuality(wand, 85)
MagickSetImageFormat(wand, &quot;jpg&quot;)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;To get the data from ImageMagick just call &lt;code class=&quot;highlighter-rouge&quot;&gt;MagickGetImageBlob&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;var length = 0

guard let image = MagickGetImageBlob(wand, &amp;amp;length) else {
  throw Abort(.internalServerError, reason: &quot;Can't get image from ImageMagick.&quot;)
}&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;&lt;code class=&quot;highlighter-rouge&quot;&gt;MagickGetImageBlob&lt;/code&gt; will return &lt;code class=&quot;highlighter-rouge&quot;&gt;UnsafeMutablePointer&amp;lt;UInt8&amp;gt;&lt;/code&gt; and all you have to do is create &lt;code class=&quot;highlighter-rouge&quot;&gt;Data&lt;/code&gt; using &lt;code class=&quot;highlighter-rouge&quot;&gt;bytes&lt;/code&gt;:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let data = Data(bytes: image, count: length)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Don’t forget to clean up and return the data:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;DestroyMagickWand(wand)
DestroyPixelWand(pixel)
DestroyDrawingWand(draw)
MagickRelinquishMemory(image)
MagickWandTerminus()

return data&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Your model is all good now. Let’s go back to the controller and use it.&lt;/p&gt;

&lt;p&gt;Before using your model, you need to download the font that will be used for creating the watermark. You can get a lot of different fonts from the &lt;code class=&quot;highlighter-rouge&quot;&gt;GoogleFont&lt;/code&gt; library. I’m using &lt;a href=&quot;https://fonts.google.com/specimen/Open+Sans&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;Open Sans&lt;/a&gt;. Just download the ttf file and put it inside the fonts directory inside your project.&lt;/p&gt;

&lt;p&gt;In &lt;code class=&quot;highlighter-rouge&quot;&gt;PhotoController.swift&lt;/code&gt;, add the property for the font directory and the property for the watermark text:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;final class PhotoController {

private let photosList = [&quot;barcelona.jpg&quot;, &quot;oslo.jpg&quot;, &quot;porto.jpg&quot;, &quot;rome.jpg&quot;]
private let photosDirectory = &quot;photos&quot;
private let fontsDirectory = &quot;fonts&quot;
private let watermarkText = &quot;ImageMagick\nVapor&quot;&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Inside the &lt;code class=&quot;highlighter-rouge&quot;&gt;show(_ req: Request)&lt;/code&gt; function, replace current photo loading with your Photo model:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-swift&quot;&gt;let file = workingDirectory.appendingPathComponent(photosDirectory, isDirectory: true).appendingPathComponent(filename)
let font = workingDirectory.appendingPathComponent(fontsDirectory, isDirectory: true).appendingPathComponent(&quot;OpenSans-Regular.ttf&quot;)

let photo = try Photo(file: file)
let watermarkedPhoto = try photo.watermarked(with: font, and: watermarkText)&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The whole &lt;code class=&quot;highlighter-rouge&quot;&gt;PhotoController&lt;/code&gt; should look like &lt;a href=&quot;https://github.com/mikina/WatermarkingPhotos/blob/master/Sources/App/Controllers/PhotoController.swift&quot; target=&quot;_blank&quot; rel=&quot;nofollow&quot;&gt;this&lt;/a&gt;.&lt;/p&gt;

&lt;p&gt;Now run the application in Xcode and open the url once again:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;&lt;code class=&quot;language-bash&quot;&gt;http://localhost:8080/photos/show/barcelona&lt;/code&gt;&lt;/pre&gt;

&lt;div class=&quot;photo&quot;&gt;&lt;a href=&quot;/assets/imagemagick-vapor-3/watermarked-photo.png&quot; target=&quot;_blank&quot;&gt;&lt;img alt=&quot;Watermarked photo&quot; src=&quot;/assets/imagemagick-vapor-3/watermarked-photo.png&quot; class=&quot;img-responsive center-block&quot; width=&quot;1690&quot; height=&quot;1114&quot; /&gt;&lt;/a&gt;&lt;/div&gt;

&lt;h4 id=&quot;summary&quot;&gt;Summary&lt;/h4&gt;

&lt;p&gt;When I recently tried to use &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; in my &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; project, I spent a couple of hours trying to figure out how to setup and wrap &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; into a Swift package. I had a lot of issues with missing files and linker errors. After resolving all of those issues, using &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt; turns out to be very simple and straightforward 😄&lt;/p&gt;

&lt;p&gt;&lt;em&gt;Where do we go from here?&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;I strongly encourage you to play with &lt;code class=&quot;highlighter-rouge&quot;&gt;ImageMagick&lt;/code&gt;. You can create a very handy and tailored library that you can re-use in your &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; projects.&lt;/p&gt;

&lt;p&gt;You should also try to run it on Linux if you haven’t tried it yet. I’m using &lt;code class=&quot;highlighter-rouge&quot;&gt;Docker&lt;/code&gt; for development and I will be writing how to use it with &lt;code class=&quot;highlighter-rouge&quot;&gt;Vapor&lt;/code&gt; in my next blog post.&lt;/p&gt;

&lt;p&gt;&lt;em&gt;How did you like it? Have you already tried using ImageMagick with Vapor? Did you run into any issues? Let me know - along with your questions, comments or feedback - on Twitter &lt;a href=&quot;https://twitter.com/mikemikina&quot; target=&quot;_blank&quot;&gt;@mikemikina&lt;/a&gt;&lt;/em&gt;&lt;/p&gt;

&lt;p&gt;Happy coding 😊&lt;/p&gt;</content><author><name>Mike Mikina</name></author><summary type="html">Back in the days (you remember web 2.0? 😉) I used to do a lot of programming around photos. Resizing, scaling, rotating and converting between formats. Recently, I had to create a web service that generates watermarked images using Vapor. It turns out that there are not very many libraries for image manipulation yet, so this simple task became an interesting problem to research.</summary></entry><entry><title type="html">Today I started my blog. But why?</title><link href="https://mikemikina.com/blog/today-i-started-my-blog-but-why/" rel="alternate" type="text/html" title="Today I started my blog. But why?" /><published>2018-04-09T22:17:26+02:00</published><updated>2018-04-09T22:17:26+02:00</updated><id>https://mikemikina.com/blog/today-i-started-my-blog-but-why</id><content type="html" xml:base="https://mikemikina.com/blog/today-i-started-my-blog-but-why/">&lt;p&gt;In this blog I will be writing mostly about software development, Swift, iOS, machine learning, algorithms and other interesting topics that I have learned so far.&lt;/p&gt;

&lt;!--more--&gt;

&lt;p&gt;There cannot be a programmer’s blog without hello world! So here you go:&lt;/p&gt;

&lt;pre class=&quot;code-block&quot;&gt;
  &lt;code class=&quot;language-swift line-numbers&quot;&gt;let hello = &quot;Hello World&quot;&lt;/code&gt;
&lt;/pre&gt;

&lt;div class=&quot;video-container video&quot;&gt;
  &lt;video class=&quot;video&quot; preload=&quot;auto&quot; poster=&quot;/assets/hello/hello.jpg&quot; width=&quot;818&quot; loop=&quot;&quot; muted=&quot;&quot; autoplay=&quot;autoplay&quot;&gt;
    &lt;source src=&quot;/assets/hello/hello.webm&quot; type=&quot;video/webm&quot; /&gt;
    &lt;source src=&quot;/assets/hello/hello.mp4&quot; type=&quot;video/mp4&quot; /&gt;
  &lt;/video&gt;
&lt;/div&gt;

&lt;p&gt;Of course in &lt;code class=&quot;highlighter-rouge&quot;&gt;Swift&lt;/code&gt; using Playgrounds 😉&lt;/p&gt;

&lt;p&gt;But why to start a new blog? Isn’t there enough blogs already? Couple of reasons 😉&lt;/p&gt;

&lt;p&gt;I wanted to start this blog in 2016. Actually I wrote two posts back then but I never published them. Posts were almost finished, blog was also almost finished. I just had other more urgent projects that needed to be taken care of. At least that’s what I have told to myself.&lt;/p&gt;

&lt;p&gt;So first lesson learned: &lt;code class=&quot;highlighter-rouge&quot;&gt;finish what you have started&lt;/code&gt;. No matter what, just finish it. I’ve been following this pattern for a while now.&lt;/p&gt;

&lt;p&gt;Second reason is much more important - &lt;code class=&quot;highlighter-rouge&quot;&gt;learning while blogging&lt;/code&gt;. It’s a very different thing when you want to explain what you have just learnt to someone else. Suddenly you realize that you are not sure how things are actually working under the hood.  In order to write a blog post about it, you need to dig deeper, read the documentation and gather more information. It’s all about learning.&lt;/p&gt;

&lt;p&gt;Third reason - &lt;code class=&quot;highlighter-rouge&quot;&gt;connecting with others&lt;/code&gt;. Blogging brings you closer to people. You will be surprised how other people would solve an issue that you are facing. Put yourself out there, let others see what you have to say.&lt;/p&gt;

&lt;p&gt;Reason number four - &lt;code class=&quot;highlighter-rouge&quot;&gt;give back to the community&lt;/code&gt;. I have been using open source libraries and learning from other blogs for ages. Now it’s time to contribute. Let the others learn from you. Exchange ideas, share the knowledge.&lt;/p&gt;

&lt;p&gt;Last but not least - &lt;code class=&quot;highlighter-rouge&quot;&gt;writing is hard&lt;/code&gt;. For engineers playing with code is a natural thing to do, playing with words is a hell of a different story. Good news is that every new blog post brings you closer to mastering this mysterious craft. You may know all of the technical stuff but communication is the key.&lt;/p&gt;

&lt;p&gt;Long story short - I really encourage all of you to start blogging, if you are not a blogger yet 😉&lt;/p&gt;

&lt;p&gt;Feel free to reach me on Twitter &lt;a href=&quot;https://twitter.com/mikemikina&quot; target=&quot;_blank&quot;&gt;@mikemikina&lt;/a&gt;. I like discussing and talking about different ideas 😊&lt;/p&gt;</content><author><name>Mike Mikina</name></author><summary type="html">In this blog I will be writing mostly about software development, Swift, iOS, machine learning, algorithms and other interesting topics that I have learned so far.</summary></entry></feed>