<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mattia Fochesato on Medium]]></title>
        <description><![CDATA[Stories by Mattia Fochesato on Medium]]></description>
        <link>https://medium.com/@mattia.fochesato?source=rss-519dc5be76f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*kg5P_hGrcWaJVTO8ZhH_Yw.jpeg</url>
            <title>Stories by Mattia Fochesato on Medium</title>
            <link>https://medium.com/@mattia.fochesato?source=rss-519dc5be76f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 08:46:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mattia.fochesato/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Async/Await in Vapor — How to create a weather API with Server-Side Swift]]></title>
            <link>https://medium.com/@mattia.fochesato/async-await-in-vapor-how-to-create-a-weather-api-with-server-side-swift-b305b646654e?source=rss-519dc5be76f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b305b646654e</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[vaporswift]]></category>
            <category><![CDATA[serverless]]></category>
            <dc:creator><![CDATA[Mattia Fochesato]]></dc:creator>
            <pubDate>Fri, 01 Apr 2022 08:53:08 GMT</pubDate>
            <atom:updated>2022-04-04T19:48:19.071Z</atom:updated>
            <content:encoded><![CDATA[<h3>Async/Await in Vapor — How to create a weather API with Server-Side Swift</h3><p>In this article, you will explore how to make <strong>external API calls</strong> and handle <strong>parallel concurrency</strong> with <strong>Vapor</strong>. It can be handy when your service needs to access <strong>external APIs</strong> that can add <strong>latency</strong> to your <strong>server response time</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NitnCbUNo8E9gL3HOtqeg.png" /></figure><h3>Vapor</h3><p><strong>Vapor</strong> is a framework written in Swift that allows you to create a fully-featured backend for your application with many advanced features like Authentication, Middleware, etc. Furthermore, you can deploy your Vapor package as a serverless function with <strong>Heroku</strong>, <strong>AWS</strong>, <strong>Google Cloud</strong>, or <strong>Docker</strong>.</p><h3>Project Overview</h3><p>You will discover how to fetch the weather from <strong>OpenWeatherMap</strong> (abbreviated to <strong>OWM</strong>) and combine it in a custom struct. The goal is to learn how to design and create an API Endpoint that needs to execute some tasks before returning the result to the client. It is straightforward thanks to the new async/await operators.</p><p>The final application will make <strong>two</strong> <strong>parallel</strong> GET requests to OWM to get <strong>detailed weather </strong>data, <strong>combine</strong> the results in a single struct and <strong>return</strong> it to the client as JSON data.</p><p>Of course, OpenWeatherMap already has an API Endpoint (One Call) that gives all those information but as said before, the goal of this article is to <strong>learn</strong> how to work with <strong>concurrency with Vapor</strong>.</p><h4>Install Vapor</h4><p>To install Vapor, you have to have <a href="https://brew.sh/"><strong>homebrew</strong></a> installed on your Mac and execute this command in the Terminal:</p><pre>brew install vapor</pre><h4>Create the Vapor project</h4><p>Once Vapor has been installed, <strong>navigate to the folder</strong> in which you want to create your Vapor project and execute this command (<strong>remember to change the</strong> ProjectName):</p><pre>vapor new ProjectName -n</pre><p>Now that you have created the project <strong>change the directory</strong> withcd ProjectName and then <strong>open the project with Xcode</strong> using this command:</p><pre>open Package.swift</pre><h4>Getting OWM API Key</h4><p>Before you start coding the server, since you will need forecast information, you need to <strong>register to OpenWeatherMap</strong>. They provide some <strong>free</strong> APIs to get the <strong>current weather</strong> and the <strong>forecast for the next five days</strong>.</p><p>First, you need to <strong>register</strong> at <a href="https://home.openweathermap.org/users/sign_up">openweathermap.com</a>.</p><p>Follow the registration instructions, and after that, open the &quot;<strong>My API keys</strong>&quot; page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/566/1*OKpf-Tj9g2t-ebDLYCAxaQ.png" /><figcaption>Here is where you can find the &quot;My API Keys&quot; page</figcaption></figure><p>On this page, you can find your <strong>API Key</strong>. <strong>Note</strong> it somewhere since you are going to use it <strong>later</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h2RT8p-n_LGWh4-ziJ4FoQ.png" /><figcaption>An example of how the API Key should look like</figcaption></figure><h4>Setting up the Xcode project</h4><p>To make Vapor being able to find the Public folder and other files, you have to specify to Xcode the <strong>working directory</strong>. Open the <strong>scheme selector</strong> and click &quot;<strong>Edit scheme.</strong>&quot;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*44HgP8yjIilpAcFXjVwgwg.png" /><figcaption>The scheme selector</figcaption></figure><p>Once the window opens, select<strong> &quot;Run&quot;</strong> from the <strong>sidebar</strong>, open the &quot;<strong>Options</strong>&quot; <strong>page</strong> and <strong>pick the working directory</strong>. You have to put the path of the <strong>root folder of your project</strong>. That folder should contain the Package.swift file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3SprlXMukJelh4vA7A4JQ.png" /><figcaption>Set the working directory on Xcode</figcaption></figure><p><strong>Setting environment API key</strong></p><p>To ensure that you have access to the <strong>API Key</strong> in <strong>every part of your code</strong>, you must set the key as an <strong>Environment Variable</strong>. It is straightforward: from the <strong>scheme editor</strong> (the same page as before), open the &quot;<strong>Arguments</strong>&quot; tab and add the key in the &quot;<strong>Environment Variables</strong>&quot; section. You can choose the name that you want but make sure to remember it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EcD781zxlv_cbkK4wYXyYQ.png" /><figcaption>Add a new Environment Variable on Xcode</figcaption></figure><p><strong>⚠️ WARNING! </strong>If you are going to <strong>deploy the code on a server</strong>, you have to add your environment variables to the .env file. You can find more information <a href="https://docs.vapor.codes/4.0/environment/#env-dotenv">here</a>.</p><h3>Creating the Weather Backend</h3><p>OpenWeatherMap exposes two useful APIs:</p><ul><li><strong>Current Weather Data</strong>: &quot;Access current weather data for any location.&quot;</li><li><strong>5 Day / 3 Hour Forecast</strong>: &quot;5-day forecast with a 3-hour step for any location on the globe&quot;</li></ul><p>Since the user may hurry to know the weather, you should fetch all the data in <strong>parallel</strong>, <strong>optimizing the loading time</strong>. Let&#39;s talk about this later.</p><h4>Fetching weather from OpenWeatherMap</h4><p>Before creating your API endpoint, you must <strong>fetch</strong> and <strong>decode</strong> the weather from OpenWeatherMap. So let&#39;s see the code used to fetch and serialize the current weather from OWM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/16782be9c1afdbfcacb40146acf9bd40/href">https://medium.com/media/16782be9c1afdbfcacb40146acf9bd40/href</a></iframe><p>As you can see, the code is pretty straightforward. The function getCurrentWeather() <strong>tries</strong> to <strong>fetch</strong> the JSON from the API and tries to serialize it with the <a href="https://developer.apple.com/documentation/foundation/jsondecoder">JSONDecoder</a> :</p><ul><li>let apiKey = Environment.get(“OWM_KEY”) tries to retrieve the <strong>API Key</strong> from the <strong>environment values</strong></li><li>let url = URL(string: ...) creates the URL object that will be passed to the <strong>URLSession</strong></li><li>let (data, _) = try await URLSession.shared.data(from: url) attempts to retrieve the <strong>JSON data</strong> from the URL <strong>asynchronously</strong></li><li>JSONDecoder().decode(CurrentWeather.self, from: data) <strong>serializes</strong> the JSON data into a CurrentWeather object</li></ul><p><strong>Note</strong> that the function getCurrentWeather() is async throw:</p><ul><li>Since it will be used inside a TaskGroupthe async operator tells Swift that the function needs to be executed inside a <strong>Task</strong>.</li><li>The URLSession <strong>can fail</strong> for any reason, so having the throw operator makes <strong>error handling</strong> very easy with Vapor.</li></ul><p>The steps for fetching the daily forecast are the same. You have only to create the correct object (in this case, it is called DailyWeather) to serialize since the JSON structure is slightly different. You can find the source code on GitHub: don&#39;t worry!</p><h4>Combining all the weather information</h4><p>Since the goal of this weather backend is to provide a <strong>single</strong> API Endpoint to get all the possible weather information, you should combine all the data that the previous code fetched into a single object: CompleteWeather.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QfkkEaJRO9prVne7TP-IA.png" /><figcaption>Expected result</figcaption></figure><p>The idea is to create a list of CompleteWeatherItem objects where each object has the weather information for a given timestamp.</p><p>The <strong>first</strong> item on the list is the current weather; the other items are the future weather: the timestamp value tells the DateTime of the forecast.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ec4c3864dc7e27ca32af185d04bb80c/href">https://medium.com/media/2ec4c3864dc7e27ca32af185d04bb80c/href</a></iframe><p>The CompleteWeather object needs the CurrentWeather and DailyWeather objects to generate all the necessary information.</p><p>First of all, it checks if there was an API error. If not, start to add the CompleteWeatherItem to the forecast list.</p><p>The code is pretty long, but it only checks that all the variables are set.</p><h4>Creating the API endpoint</h4><p>One last step before creating the endpoint is to write the function that will be executed when the endpoint is called.</p><p>Since you need to fetch the data from 2 different API endpoints, it is better to make the requests <strong>parallelly</strong>. To accomplish this task, you are going to need to use the <strong>withThrowingTaskGroup</strong> function, which uses the new<strong> </strong><strong>TaskGroup</strong> of Swift 5.5</p><p>You can find more about the withThrowingTaskGroup in this article:</p><p><a href="https://medium.com/@mattia.fochesato/advanced-swift-concurrency-how-to-create-multiple-parallel-tasks-6ed30755bdf3">Advanced Swift Concurrency — How to create multiple parallel Tasks</a></p><p>This code <strong>creates</strong> a <strong>TaskGroup</strong> for fetching the weather data from OpenWeatherMap <strong>asynchronously</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60a50a3a67bb49610ecdd5dd9b5283b9/href">https://medium.com/media/60a50a3a67bb49610ecdd5dd9b5283b9/href</a></iframe><p>As you can see, <strong>two tasks are added to the TaskGroup</strong>, <strong>and they will be executed in parallel</strong>:</p><ul><li>getCurrentWeather fetches the <strong>current weather </strong>from one OWM endpoint</li><li>getDailyForecast fetches the <strong>daily forecast</strong> from another OWM endpoint</li></ul><p>After the tasks have been created, you have to wait for their execution to finish. To do it, you can use <strong>for try await</strong> weatherData <strong>in</strong> group { … } that starts to loop all the results after all the tasks have been executed.</p><p>Since, in this case, there are <strong>different result types</strong>, you have to extract the data with this boilerplate code (lines 34 to 49).</p><p>After checking that all the data has been fetched, terminate the TaskGroup returning the CompleteWeather object <strong>initialized</strong> with the <strong>forecast</strong>.</p><p>Now that you have all the necessary functions, you can construct your API endpoint. Open the <em>routes.swift</em> file and add the /weather endpoint. Since it is a <strong>GET</strong> Method, use app.get(“weather”) which listens for GET /weather requests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e049244994760d7477c76286e3d27fb/href">https://medium.com/media/3e049244994760d7477c76286e3d27fb/href</a></iframe><p>Specifying req -&gt; CompleteWeather you are telling Vapor that it will receive a CompleteWeather object. Since CompleteWeather is a <strong>Codable</strong> object, it will be <strong>automatically encoded into a JSON string</strong> and returned to the client.</p><p>You can specify your <strong>custom</strong> latitude and longitude to the query by adding ?lat=10&amp;lon=40 to the request, and then you can get the value with let lat = req.query[Double.self, at: “lat”] .</p><p><strong>Warning! The query value can also be nil</strong>, so you have to ensure that it has been set. Since, in this case, they are necessary, you can create <strong>custom exceptions</strong> that will tell the client more information about what is wrong. For example: trying to call this endpoint without the lat query set will show this <strong>error</strong> to the client:</p><pre>{&quot;error&quot;:true,&quot;reason&quot;:&quot;Missing &#39;lat&#39; parameter&quot;}</pre><p>After the checks, you can <strong>call</strong> the getWeather() function with the try await <strong>operators</strong>. Vapor will <strong>automatically handle the async function and any possible error</strong> that the function can throw! <strong>Very easy!</strong></p><p><strong>Done</strong> 🎉! You can now <strong>run</strong> the project and <strong>navigate</strong> to <a href="http://127.0.0.1:8080/weather?lat=40.851799&amp;lon=14.268120">http://127.0.0.1:8080/weather?lat=40.851799&amp;lon=14.268120</a> to see the forecast for Naples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T3-4Y9horccVA-QPTi9XKA.png" /><figcaption>The final result</figcaption></figure><h3>Useful information</h3><p>Having your API exposed without any limit <strong>can cost you a lot of money</strong>. It would be best to protect your API by using a <strong>rate-limiting</strong> middleware like Gatekeeper. Check it out here:</p><p><a href="https://github.com/nodes-vapor/gatekeeper">GitHub - nodes-vapor/gatekeeper: Rate limiting middleware for Vapor 👮</a></p><p>Here you can find the complete source to get your weather API server up and running.</p><p><a href="https://github.com/MattiaFochesato/VaporWeatherServer">MattiaFochesato/VaporWeatherServer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b305b646654e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advanced Swift Concurrency — How to create multiple parallel Tasks]]></title>
            <link>https://medium.com/@mattia.fochesato/advanced-swift-concurrency-how-to-create-multiple-parallel-tasks-6ed30755bdf3?source=rss-519dc5be76f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6ed30755bdf3</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Mattia Fochesato]]></dc:creator>
            <pubDate>Fri, 25 Mar 2022 09:21:18 GMT</pubDate>
            <atom:updated>2022-03-25T10:21:50.987Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to run multiple parallel tasks with Swift — Concurrency with Swift</h3><p>The <strong>withThrowingTaskGroup</strong> function in Swift is handy to execute <strong>multiple parallel tasks in the background, combine</strong> all the results, and present them to the user. This article will explain how it works and how to use it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGdP9UyM1X2GIMzpShsnKw.png" /></figure><h3>Task</h3><p>Let&#39;s start with the basics. A task is a single unit of asynchronous work. Tasks can be started immediately after the creation or later when is needed, and the app should cancel them if the result is not required anymore. But, of course, the app can also wait to complete the task before executing other things.</p><h3>TaskGroup</h3><p>As Apple&#39;s Documentations says:</p><blockquote>A TaskGroup is a group that contains dynamically created child tasks</blockquote><p>The TaskGroup can spawn multiple tasks simultaneously, wait for the completion, and return the result only after all the child tasks have finished the execution. The <strong>withThrowingTaskGroup</strong>function can do all of this. It requires a result type (of: String.self) that specifies the type of the result of the function.</p><p>Inside the closure, the function group.addTask { return await myFunction() } adds the asynchronous task to the list of tasks to execute.</p><p>After that the TaskGroup have created all the tasks, the application can wait for them to complete and collect the results by using for try await item in group { ... } and at the end, you have to return the result.</p><p>This example shows how to create a basic TaskGroup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec2fa10c55406c2f72726ef6aa8104a0/href">https://medium.com/media/ec2fa10c55406c2f72726ef6aa8104a0/href</a></iframe><p><strong>Some info about the TaskGroup:</strong></p><ul><li>All the tasks are independent of each other, and the app cannot control the execution order.</li><li>All the tasks of TaskGroup are concurrent, and they start automatically.</li><li>The TaskGroup returns the result only after all the tasks have completed their execution.</li></ul><h4>The API problem</h4><p>The demo application shows the departing trains from a specified station. The &quot;problem&quot; with the API is that you need to make multiple API calls to retrieve all the required information about the departing trains.</p><p>The primary endpoint gives only an array of tuples containing the code and the destination of the departing train. Therefore, we need to make other API calls to get the details about a specific train.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ug_Y9oQ4KdBHhErYK1iwHA.png" /><figcaption>The primary endpoint exposes only the destination and the code of the train.</figcaption></figure><p>Since we need to get more information before showing the user the results, we have to create a task for every train that gets more data, which is possible thanks to TaskGroup.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41319cc36976e5d2722c69f47a90dcb3/href">https://medium.com/media/41319cc36976e5d2722c69f47a90dcb3/href</a></iframe><p>The function loadTrainList(station: from: ) retrieves the list of departing trains from a selected station (taken from the TrainAPIManager class), but we only have the train code and the train&#39;s destination. However, we also need additional information, such as intermediary stops.</p><p>Ok, since we need to handle the additional train data, we have to extend the Train struct and create other structs. The new struct <strong>TrainInfo </strong>contains all the detailed information about the train.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gwJS_3AWGvGP2YzjNIJFoA.png" /><figcaption>We can get detailed info about a specific train thanks to another endpoint</figcaption></figure><p>The async function inside the <strong>Train </strong>struct calls the <strong>TrainAPIManager </strong>to get the detailed train data (returning a <strong>TrainInfo</strong> object). This function is going to be useful later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed23d14d58ccdc0e0962ecc235884924/href">https://medium.com/media/ed23d14d58ccdc0e0962ecc235884924/href</a></iframe><p>Once it has retrieved the list of codes of the trains that will depart, the application can make an <strong>async</strong> <strong>GET</strong> request to fetch the data (ex: next stops).</p><p>So thanks to withThrowingTaskGroup the app can call multiple endpoints simultaneously and wait for the requests to execute. After that, it stores the result and updates the UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93f1a0d0d4c9cd866a6659c5019b2fbc/href">https://medium.com/media/93f1a0d0d4c9cd866a6659c5019b2fbc/href</a></iframe><p>Since thetrainList variable is a @Published object, the SwiftUI view will automatically update, showing the new data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYPQ8u0Xp9NpFiH1VxOOCA.png" /><figcaption>The SwiftUI shows the result of all the API calls</figcaption></figure><h3>Wrap Up</h3><p>The TaskGroup is very easy to implement and use, but it may have some limited use-cases. Nevertheless, it can be handy, and it is a good thing to know when developing an application.</p><p>The demo application is available on GitHub!</p><p><a href="https://github.com/MattiaFochesato/TrainConcurrency">MattiaFochesato/TrainConcurrency</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ed30755bdf3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dismiss search programmatically in SwiftUI]]></title>
            <link>https://medium.com/@mattia.fochesato/dismiss-search-programmatically-in-swiftui-96a000383fdc?source=rss-519dc5be76f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/96a000383fdc</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Mattia Fochesato]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 17:41:02 GMT</pubDate>
            <atom:updated>2022-03-09T13:31:30.570Z</atom:updated>
            <cc:license>https://creativecommons.org/publicdomain/mark/1.0/</cc:license>
            <content:encoded><![CDATA[<p>I developed an application in <strong>SwiftUI</strong> using the new <strong>.searchable(text:)</strong> function.</p><p>The search results view was a <strong>separate view</strong>, and I needed to <strong>cancel the search</strong> when the user clicked on a list item, but I couldn&#39;t find anything about that.</p><p>After some deep research into the Apple documentation, I finally found the answer: <a href="https://developer.apple.com/documentation/swiftui/environmentvalues/dismisssearch"><strong>dismissSearch</strong></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0ABNDcLukQ0MSML4PCGpYQ.png" /></figure><p>Here is an example of how to use it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/434003c34bc21fc6f82e03d7437a4317/href">https://medium.com/media/434003c34bc21fc6f82e03d7437a4317/href</a></iframe><p>Calling dismissSearch() sets <strong>isSearching</strong> to <strong>false</strong>, <strong>clears</strong> the search text and <strong>removes focus</strong>.</p><p>To use the dismissSearch() function, you have to add this environment value:</p><pre>@Environment(\.dismissSearch) private var dismissSearch</pre><p>Then you have to call the dimissSearch() function!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=96a000383fdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>