<?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 Andrea Scuderi on Medium]]></title>
        <description><![CDATA[Stories by Andrea Scuderi on Medium]]></description>
        <link>https://medium.com/@andreascuderi73?source=rss-6690818517f1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*g5JdugfZEaYNF9lD.</url>
            <title>Stories by Andrea Scuderi on Medium</title>
            <link>https://medium.com/@andreascuderi73?source=rss-6690818517f1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 06:32:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andreascuderi73/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[How to Fix Greyed Icons on iOS Document Browser and Picker]]></title>
            <link>https://medium.com/better-programming/how-to-fix-greyed-icons-on-ios-document-browser-and-picker-8dea8a76d6e7?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8dea8a76d6e7</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Tue, 06 Oct 2020 01:51:28 GMT</pubDate>
            <atom:updated>2020-10-06T01:51:28.588Z</atom:updated>
            <content:encoded><![CDATA[<h4>UIDocumentBrowserViewController the right configuration for supported uniform type identifiers</h4><figure><img alt="Image showing three phone screens with grading levels of file thumbnail quality." src="https://cdn-images-1.medium.com/max/1024/1*0atJRZt46DshAKAN_SaNxw.png" /><figcaption>Image provided by the author.</figcaption></figure><p>As you may know, the apps installed on iOS, for security reasons, are confined to the App Sandbox. This means that from an iOS App, you can access only files generated by the app itself or included in the app folder.</p><p>To help the developers, UIKit provides two standard UI solutions on iOS to access files from the app folder and from Cloud providers:</p><ul><li>The <a href="https://developer.apple.com/documentation/uikit/uidocumentbrowserviewcontroller">UIDocumentBrowserViewController</a> is the apple standard View Controller to manage documents on iOS and navigate through cloud resources and performing actions on them.</li><li>The <a href="https://developer.apple.com/documentation/uikit/uidocumentpickerviewcontroller">UIDocumentPickerViewController</a> is the standard View and has been designed for importing, exporting, opening, or moving files.</li></ul><h3>Documentation and Tutorials</h3><p>Apple has provided very good examples on how to use them and I suggest you read the official documentation to learn how to use them:</p><p><strong>UIDocumentBrowserViewController</strong></p><ul><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/adding_a_document_browser_to_your_app">Adding a document browser to your app</a></li><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/adding_a_document_browser_to_your_app/setting_up_a_document_browser_app">Setting Up a Document Browser App</a></li><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/adding_a_document_browser_to_your_app/presenting_selected_documents">Presenting Selected Documents</a></li><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/adding_a_document_browser_to_your_app/enabling_document_sharing">Enabling Document Sharing</a></li><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/building_a_document_browser_app_for_custom_file_formats">Building a Document Browser App for Custom File Formats</a></li></ul><p><strong>UIDocumentPickerViewController</strong></p><ul><li><a href="https://developer.apple.com/documentation/uikit/view_controllers/providing_access_to_directories">Providing Access to Directories</a></li></ul><p><strong>WWDC</strong></p><p><a href="https://developer.apple.com/videos/play/wwdc2018/216/">https://developer.apple.com/videos/play/wwdc2018/216/</a></p><h3>My Use Case: GPX Track Viewer</h3><p>The classical use case for UIDocumentBrowserViewController is as a viewer for a specific file type.</p><p>For example, I used it to build an app called <a href="https://apps.apple.com/us/app/id1465569363">Trackyzer Pro</a>, a GPX viewer for cyclists with rich graphics for slope, speed, and altitude data. The app can save a workout as GPX or open any GPX file with a track using the Document Browser.</p><figure><img alt="Screenshot of app showing a cycling route on a map, with different colors, indicating speed and elevation." src="https://cdn-images-1.medium.com/max/1024/1*8uWKBaMT0gCLWbp3UOWRGA.png" /><figcaption>Trackyzer Pro — GPX Visualizer</figcaption></figure><h3>Greyed Icons</h3><p>I built my app following the best practices and tutorials provided by Apple and everything seemed correct until I installed my app in a real device.</p><p>Now, most of the cyclists have more than one app to import GPX files and the result is that on some occasions the Document Browser inside the app shows greyed icons.</p><p>Once the icons are greyed out in the Document Browser, the user cannot open any file from the app.</p><figure><img alt="Image of an iPhone showing greyed out files in a file browser." src="https://cdn-images-1.medium.com/max/1024/1*HWMZarQ-Rtivb8kPIISIDw.png" /><figcaption>Image provided by the author.</figcaption></figure><p>Digging a little bit more on the issue I came across <a href="https://developer.apple.com/forums/thread/118932">this post</a> on the support blog:</p><blockquote>“We understand that you are having issues with your type definition for .gpx files. At this time, there is no commonly-accepted Uniform Type Identifier for .gpx files and different developers have defined their .gpx declaration differently. This means that if two apps are installed on the same device that claim to open these files with different definitions, they won’t interact correctly: from the user’s point of view, only one of those apps, chosen seemingly at random, will be able to open these files.”</blockquote><p>The GPX format is defined <a href="https://www.topografix.com/gpx_manual.asp">here</a> and it’s an XML text file. So in different conditions, depending on which app the user has installed, iOS may display it as a Text icon, an XML icon, or a custom icon.</p><p>It seems there is no solution to the issue, but I found one.</p><h3>What is a Uniform Type Identifier?</h3><p>According to Apple <a href="https://developer.apple.com/library/archive/documentation/FileManagement/Conceptual/understanding_utis/understand_utis_conc/understand_utis_conc.html#//apple_ref/doc/uid/TP40001319-CH202-SW1">official documentation</a>, a Uniform Type Identifier:</p><blockquote>“is a string that uniquely identifies a class of entities considered to have a “type.” For example, for a file or other stream of bytes, “type” refers to the format of the data. For entities such as packages and bundles, “type” refers to the internal structure of the directory hierarchy.</blockquote><blockquote>Most commonly, a UTI provides a consistent identifier for data that all applications and services can recognize and rely upon, eliminating the need to keep track of all the existing methods of tagging data.”</blockquote><p>Examples of UTI for GPX as declared in Info.plist:</p><pre><strong>&lt;dict&gt;<br> &lt;key&gt;</strong>UTTypeConformsTo<strong>&lt;/key&gt;<br> &lt;array&gt;<br>  &lt;string&gt;</strong>public.content<strong>&lt;/string&gt;<br>  &lt;string&gt;</strong>public.data<strong>&lt;/string&gt;<br>  &lt;string&gt;</strong>public.xml<strong>&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;</strong>UTTypeDescription<strong>&lt;/key&gt;<br> &lt;string&gt;</strong>GPS Exchange Format (GPX)<strong>&lt;/string<br> &lt;key&gt;</strong>UTTypeIconFiles<strong>&lt;/key&gt;<br> &lt;array&gt;<br> &lt;string&gt;</strong>GPX.icns<strong>&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;</strong>UTTypeIdentifier<strong>&lt;/key&gt;<br> &lt;string&gt;</strong>com.topografix.gpx<strong>&lt;/string&gt;<br> &lt;key&gt;</strong>UTTypeReferenceURL<strong>&lt;/key<br> &lt;string&gt;</strong>http://www.topografix.com/GPX/1/1<strong>&lt;/string&gt;<br> &lt;key&gt;</strong>UTTypeTagSpecification<strong>&lt;/key&gt;<br> &lt;dict&gt;<br> &lt;key&gt;</strong>public.filename-extension<strong>&lt;/key&gt;<br> &lt;array&gt;<br> &lt;string&gt;</strong>gpx<strong>&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;key&gt;</strong>public.mime-type<strong>&lt;/key&gt;<br> &lt;array&gt;<br> &lt;string&gt;</strong>application/gpx+xml<strong>&lt;/string&gt;<br> &lt;/array&gt;<br> &lt;/dict&gt;<br>&lt;/dict&gt;</strong></pre><p>This essentially states that a GPX file could be:</p><ul><li>A file with the extension .gpx</li><li>A mime type application/gpx+xml</li><li>A document conforming to public.xml, public.text, public.data with the following reference url: <a href="http://www.topografix.com/GPX/1/1">http://www.topografix.com/GPX/1/1</a></li></ul><p><strong>… but anyone can define their own UTI. In this way, there is no easy way to get the owner of the type for an App.</strong></p><h3>How Do I Know if Another App Is Using My UTI?</h3><p>Apple provides a function to get the preferred UTI for a type <a href="https://developer.apple.com/documentation/coreservices/1448939-uttypecreatepreferredidentifierf">UTTypeCreatePreferredIdentifierForTag</a>:</p><pre><strong>func</strong> preferredUTI(ext: String) -&gt; String? {</pre><pre><strong>let</strong> theUTI = UTTypeCreatePreferredIdentifierForTag(</pre><pre>kUTTagClassFilenameExtension,</pre><pre>ext <strong>as</strong> CFString,</pre><pre><strong>nil</strong>)?.takeRetainedValue()</pre><pre><strong>return</strong> theUTI <strong>as</strong> String?</pre><pre>}</pre><p>If you’ll use it, you’ll discover that the icons are greyed out when there is a preferred UTI declared by another app.</p><p>It’s possible to know all the UTIs declared in your system by using the function <a href="https://developer.apple.com/documentation/coreservices/1447261-uttypecreateallidentifiersfortag">UTTypeCreateAllIdentifiersForTag</a>.</p><p>The following example implements a way to get all the UTI identifiers for a specific file extension:</p><pre><strong>func</strong> getUTTypeCreateAllIdentifiers(for tag: String) -&gt; [String] {</pre><pre><strong>let</strong> cfArray = UTTypeCreateAllIdentifiersForTag(<br>                 kUTTagClassFilenameExtension,<br>                 tag <strong>as</strong> CFString,<br>                 <strong>nil<br>              </strong>)?.takeRetainedValue()</pre><pre><strong>let</strong> utis:[String] = cfArray <strong>as</strong>? [String] ?? []</pre><pre><strong>return</strong> utis;</pre><pre>}</pre><p>Note: These functions are deprecated in iOS14, but there is a new type called <a href="https://developer.apple.com/documentation/uniformtypeidentifiers/uttypereference">UTTypeReference</a> in which you’ll find the equivalent methods.</p><h3>Greyed Out Icon: The Solution</h3><p>Now that we understand what’s going on, let’s find a solution.</p><p>Reading the documentation of the classes you’ll spot this on UIDocumentBrowserViewController:</p><blockquote>init(forOpeningFilesWithContentTypes allowedContentTypes: [<a href="https://developer.apple.com/documentation/swift/string">String</a>]?)</blockquote><blockquote>allowedContentTypes</blockquote><blockquote>An array of uniform type identifiers (UTIs). The document browser can open only the document types specified by these UTIs. If you pass nil, the browser uses the document types specified by the CFBundleDocumentTypes key in the app’s Info.plist file</blockquote><p>and for UIDocumentPickerViewController:</p><blockquote>init(documentTypes allowedUTIs: [<a href="https://developer.apple.com/documentation/swift/string">String</a>], in mode: <a href="https://developer.apple.com/documentation/uikit/uidocumentpickermode">UIDocumentPickerMode</a>)</blockquote><blockquote>allowedUTIs</blockquote><blockquote>An array of uniform type identifiers (UTIs). UTIs are strings that uniquely identify a file’s type.</blockquote><p>Apple examples are prepared with Storyboards, which means that the UIDocumentBrowserViewController is instantiated with a default implementation, meaning nil is passed as allowedContentTypes, this will filter the files only with the UTI you have declared, but not with the preferred UTI declared by another app.</p><p>If you pass all the UTIs in the init method the issue is solved, as the filter applied it’s not just what you defined in the CFBundleDocumentType , but also it includes all the UTIs registered.</p><pre>//UIDocumentViewController</pre><pre>let utis = <strong>func</strong> getUTTypeCreateAllIdentifiers(for: &quot;gpx&quot;)<br>let viewController = UIDocumentViewController(<em>forOpeningFilesWithContentTypes</em>: utis)</pre><pre>//UIDocumentPickerViewController</pre><pre>let viewController = UIDocumentPickerViewController(documentTypes: utis, in: .open)</pre><figure><img alt="Image of iPhone file browser with non-greyed out files available." src="https://cdn-images-1.medium.com/max/1024/1*Xlyjw7UTNoSUbbvp_JkEPA.png" /><figcaption>UIDocumentBrowserViewController — Greyed icon fixed</figcaption></figure><h3>Conclusions</h3><p>This article covered a specific issue that it’s not so evident by reading the official documentation.</p><p>The potential use of these two components is quite amazing, but the challenge is to configure them in the right way.</p><p>It’s possible to add specific actions and different styles, it’s possible to preview documents and share them. I leave to you the adventure of exploring more options.</p><p>Thanks for reading.</p><figure><img alt="Image of same non-greyed out files, but with thumbnails showing small overview of bike ride." src="https://cdn-images-1.medium.com/max/1024/1*2X5VXpAKKy7vemx0cdseDw.png" /><figcaption>Trackyzer Pro — UIDocumentBrowserViewController with Document Preview</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8dea8a76d6e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-fix-greyed-icons-on-ios-document-browser-and-picker-8dea8a76d6e7">How to Fix Greyed Icons on iOS Document Browser and Picker</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Create an AWS Serverless REST API in Swift]]></title>
            <link>https://medium.com/better-programming/how-to-create-an-aws-serverless-rest-api-in-swift-b8849352c52a?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8849352c52a</guid>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Wed, 24 Jun 2020 22:11:23 GMT</pubDate>
            <atom:updated>2020-06-24T22:11:23.192Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a REST API using the Apple Swift AWS Lambda Runtime</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w89_mgXQpmkinOpr0Qo8Sw.png" /></figure><p>The Apple Swift AWS Lambda Runtime is finally a reality, and it’s now officially supported (as <a href="https://forums.swift.org/t/announcing-swift-aws-lambda-runtime/37009">announced</a> May 29). The key fact that allowed this is the support for the Amazon Linux 2 with a custom Docker image maintained by <a href="https://swift.org/download/#releases">Swift</a>.</p><p>This article will show how to implement a basic REST API using the new Apple runtime to implement a serverless stack based on API Gateway, Lambda, and DynamoDB and deploying it using the Serverless Framework.</p><h3>Serverless API Rest Architecture</h3><p>This project uses the classic serverless architecture, which is based on:</p><ul><li>API Gateway: Acts as a proxy for the Lambda and exposes it to the internet</li><li>Lambda: The stateless computational layer. We defined a lambda for each API endpoint.</li><li>DynamoDB: The AWS NoSQL database providing data persistency</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*keb5fYRSv1YD-l7fRvXT_w.png" /><figcaption>REST API — serverless architecture</figcaption></figure><p>Advantages of a serverless architecture:</p><ul><li>Pay per use</li><li>No fixed costs</li><li>Autoscaling</li><li>DevOps</li></ul><p>The deployment file, serverless.yml, contains all of the details needed to deploy the example using the <a href="https://www.serverless.com/">Serverless Framework</a>.</p><h3>Project Setup</h3><p>We’re assuming you have followed the <a href="https://github.com/swift-sprinter/aws-serverless-swift-api-template">README</a> to set up all of the requirements:</p><ul><li>AWS CLI configured with your AWS account</li><li>Docker</li><li>Serverless</li><li>Make</li></ul><h3>Getting Started</h3><p>Clone the template project:</p><pre>git clone <a href="https://github.com/swift-sprinter/aws-serverless-swift-api-template.git">https://github.com/swift-sprinter/aws-serverless-swift-api-template.git</a></pre><pre>cd <a href="https://github.com/swift-sprinter/aws-serverless-swift-api-template.git">aws-serverless-swift-api-template.git</a></pre><p>Then, build the project:</p><pre>./build.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6gmDExsm_izR9FOMYLjczw.png" /></figure><pre>./deploy.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbrFPYJwGjTfkpWAXeXmLA.png" /></figure><p>Once the project is deployed on your AWS account, the endpoints are created.</p><p>If everything is correct, the Serverless Framework will output the API endpoints.</p><h3>API Testing With Postman</h3><p>Take note of the base URL of the endpoints:</p><pre>https://&lt;api_gtw_id&gt;.execute-api.&lt;aws_region&gt;.amazonaws.com/dev</pre><p>&lt;api_gtw_id&gt; is the identifier for the API gateway generated by the script in the region &lt;aws_region&gt;.</p><p>Import the file swagger.json with Postman, and edit the variable baseUrl with the one you got from your deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jpLJD5zfyRQtl8ERD1dUKg.png" /></figure><p>Test the API.</p><p>Once you’ve finished, you can remove the deployment by launching:</p><pre>./remove.sh</pre><h3>Code Review</h3><p>The Swift <a href="https://github.com/swift-sprinter/aws-serverless-swift-api-template">code</a> implements the lambdas using the Apple <a href="https://github.com/swift-server/swift-aws-lambda-runtime">Swift AWS Lambda Custom Runtime</a> and <a href="https://github.com/swift-aws/aws-sdk-swift">AWS SDK Swift</a>.</p><ul><li>main.swift runs the lambda</li><li>Product.swift is the Swift struct to define the data model:</li></ul><pre>public struct <em>Product</em>: Codable {<br>     public let sku: <em>String<br></em>     public let name: <em>String<br></em>     public let description: <em>String<br>     </em>public var createdAt: <em>String</em>?<br>     public var updatedAt: <em>String</em>?<br>}</pre><ul><li>ProductLambda.swift configures the DynamoDB client, which shares the httpClient instance with the Lambda Runtime</li><li>ProductLambdaHandler implements the code required by the lambdas. Each lambda run only the implementation specified by the lambda Handler converting the input APIGateway.SimpleRequest to an APIGateway.Response .</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCjO3QSzAPf4m7WBLyJX0A.png" /><figcaption>‘ReadLambdaHandler’</figcaption></figure><ul><li>The lambda handlers (Create, Read, Update, Delete List) are implemented to use the event payload and to return a result containing the desired response (or an error)</li><li>All the internal asynchronous calls are defined using the NIO <a href="https://apple.github.io/swift-nio/docs/current/NIO/Classes/EventLoopFuture.html">EventLoopFuture</a></li><li>ProductService abstracts the way the lambda interacts with the DynamoDB API, hiding details related to the underlying API</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L0azc_Y_JGniHrIOgTCHPA.png" /><figcaption>‘ProductService’</figcaption></figure><h3>Conclusion</h3><p>I hope to have generated some curiosity about server-side Swift and serverless. If you’re interested in the history of how this hard work started in December 2018, you can have a look at the <a href="https://forums.swift.org/t/aws-lambda-runtime-api/18498">Swift forums</a>.</p><p>Check out the <a href="https://github.com/swift-sprinter/aws-serverless-swift-api-template">GitHub</a> repository, and feel free to experiment. I look forward to seeing something nice!</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8849352c52a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-create-an-aws-serverless-rest-api-in-swift-b8849352c52a">How to Create an AWS Serverless REST API in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build a Serverless Webform With Server-Side Swift]]></title>
            <link>https://medium.com/better-programming/build-a-serverless-webform-with-server-side-swift-8acaeedde216?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8acaeedde216</guid>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Thu, 14 May 2020 15:00:57 GMT</pubDate>
            <atom:updated>2020-05-14T15:00:57.121Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to implement a web server with API Gateway, Lambda, DynamoDB, and Swift-Sprinter without a single line of JavaScript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fp5exO05xPbK5crL6EGoLA.png" /><figcaption>Photo by the author.</figcaption></figure><p>Is it possible to implement a web site in Swift without using JavaScript? Yes, it is.</p><p>The trick is quite old and consists of generating the HTML page on the server. The idea is to avoid the use of JavaScript on the client, style the HTML with CSS, generate the pages with AWS Lambda, and serve the content with API Gateway. The persistency layer will be implemented with DynamoDB. We are going to use the <a href="https://serverless.com/">Serverless</a> framework to deploy our project on AWS.</p><h3>Serverless Project Setup</h3><p>We’re assuming you have followed the <a href="https://github.com/swift-sprinter/aws-serverless-swift-sprinter-web-template#requirements">readme</a> to set up all the requirements:</p><ul><li>AWS cli configured with your AWS account</li><li>Docker</li><li>Serverless</li><li>Make</li></ul><p>Clone the template project:</p><pre>git clone <a href="https://github.com/Andrea-Scuderi/aws-serverless-swift-sprinter-template.git">https://github.com/Andrea-Scuderi/aws-serverless-swift-sprinter-template.git</a></pre><pre>cd <a href="https://github.com/Andrea-Scuderi/aws-serverless-swift-sprinter-template.git">aws-serverless-swift-sprinter-template</a></pre><p>Then build the project:</p><pre>./build.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tz-SC_vQnu4EEQIht4TPfg.png" /></figure><pre>./deploy.sh</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8QG8kFcd-TQi3d4RBSrBQg.png" /></figure><p>Once the project is deployed on your AWS account, the endpoint is created.</p><p>Browse the generated URL with a web browser. The webform is up and running!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*3kiXqhDeBNiCXJv11ISISw.png" /></figure><h3>How Does It Work?</h3><p>The Lambda provides a computational block in the AWS Serverless stack and interacts with DynamoDB to retrieve the data stored:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*wUuKWAGp6jXPQAuCZtSUgA.png" /><figcaption>Serverless cloud architecture</figcaption></figure><p>The HTML post content keeps track of the action sent from the browser and is translated by the Lambda to a CRUD (Create, Read, Update, Delete) command for DynamoDB.</p><p>After updating the DB, the content is presented in the response web page.</p><p>The API Gateway acts as a proxy publishing the Lambda content as a web server.</p><p>The Serverless framework deploys the stacks to AWS.</p><h4>Lambda in Swift</h4><p>The Lambda is coded in Swift using the following frameworks:</p><ul><li><a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter-nio-plugin">aws-lambda-swift-sprinter-nio-plugin</a>: Implements the AWS custom runtime using Swift NIO.</li><li><a href="https://github.com/swift-aws/aws-sdk-swift">aws-sdk-swift</a>: Interacts with DynamoDB.</li><li><a href="https://github.com/JohnSundell/Plot">Plot</a>: Renders the HTML.</li><li><a href="https://getbootstrap.com/">Bootstrap</a>: CSS for HTML pages (JavaScript disabled).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KOkkxkH0bAVZDD1jRroFIA.png" /></figure><p>The Lambda decodes the API Gateway proxy event and runs the WebController.</p><p>The WebController updates DynamoDB with the information received and renders the next HTML page.</p><p>The HTML page is returned as a response to the web client.</p><h4>Using Plot to render the HTML</h4><p>The WebController renders the HTML passing the record list to the presenter, which is responsible for rendering the right web page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDFIAQqBSxm9hHkLhjzP7g.png" /><figcaption>Hello/Sources/WebController/Presenter.swift</figcaption></figure><p>The present function renders the main page with the content generated and evaluates the stateless action posted by the HTML client.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*PqHvmXJVFJNouJqlzV_XRQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCMOdBD_1DPQNMEw1nGqPA.png" /><figcaption>Hello/Sources/WebController/Plot+Card.swift</figcaption></figure><p>The HTML is created by composing a small function implemented with the Plot framework. The picture above is an example of a card.</p><h4>Using aws-sdk-swift for DynamoDB</h4><p>aws-sdk-swift is a Swift client for AWS and contains the client for DynamoDB. Here are some code snippets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yszX1aq8zP1REdIK6Kg_gg.png" /><figcaption>Hello/Sources/ProductService/ProductService.swift</figcaption></figure><h3>Conclusion</h3><p>I hope to have generated some curiosity about server-side Swift and <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Swift-Sprinter</a>.</p><p>Check out the <a href="https://github.com/swift-sprinter/aws-serverless-swift-sprinter-web-template">GitHub repository</a> and feel free to experiment. I look forward to seeing something nice!</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8acaeedde216" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/build-a-serverless-webform-with-server-side-swift-8acaeedde216">Build a Serverless Webform With Server-Side Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift on AWS Lambda Performs Like Node and Python, Using Swift-Sprinter]]></title>
            <link>https://medium.com/better-programming/swift-on-aws-lambda-performs-like-node-and-python-using-swift-sprinter-d920521130f1?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/d920521130f1</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Sun, 01 Mar 2020 23:45:37 GMT</pubDate>
            <atom:updated>2020-03-01T23:45:37.495Z</atom:updated>
            <content:encoded><![CDATA[<h4>Benchmarking the AWS custom runtime for Swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8IGhrS0aCJJb4aNn7gQUw.png" /></figure><p>Performance tuning in a serverless environment is the key to keep your back end responsive and your bill low.</p><p>This article will go through several performance tests to understand the behavior of an AWS Lambda written in Swift using the framework <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Swift-Sprinter</a> and compares it to popular languages and different configurations and options.</p><h3>What Is a Lambda?</h3><p>Lambda is the AWS resource providing Function as a Service (FAAS) computing power. It acts as the building block of a broader category of services, well-known as <em>serverless</em>.</p><p>Like the other serverless blocks, it has the following features:</p><ul><li>It’s managed.</li><li>It’s autoscaling.</li><li>It’s highly available.</li><li>It’s pay-per-use.</li></ul><p>In addition to the common serverless features, Lambda:</p><ul><li>Contains the code required to run.</li><li>Is event-driven.</li><li>Supports multiple languages running on compatible Linux.</li><li>It runs for a maximum amount of time.</li></ul><h3>How AWS Lambda Works</h3><p>The AWS Lambda architecture, based on <a href="https://aws.amazon.com/blogs/aws/firecracker-lightweight-virtualization-for-serverless-computing/">Firecracker</a> on top of an EC2 VM, has been built to be auto-scalable.</p><h4><strong>Cold start</strong></h4><p>The first time the Lambda is invoked, a new worker instance is prepared by copying, initializing, and running the code.</p><p>This process is called <em>cold start </em>and it happens every time the Lambda environment adds a new worker instance to scale up. Once the worker starts, it receives the event, processes it and then executes the request for the next event remaining in a wait status.</p><h4><strong>Warm start</strong></h4><p>Once the Lambda worker has been started, the next execution is pure processing of the upcoming event as there is no more need to set up the worker.</p><p>Eventually, after many minutes, the worker doesn’t receive any events, it is being disposed to scale down and free up unused computing resources.</p><h4><strong>Computing performance</strong></h4><p>Lambda computing performance depends on the language/runtime used, the code, and the provisioned amount of memory which also determines the power of the underlying CPU.</p><p>Memory — The amount of memory available to the function during execution. Choose an amount <a href="https://docs.aws.amazon.com/lambda/latest/dg/limits.html">between 128 MB and 3,008 MB</a> in 64 MB increments.</p><p>Lambda allocates CPU power linearly in proportion to the amount of memory configured. At 1,792 MB, a function has the equivalent of one full vCPU (one vCPU-second of credits per second).</p><p>To perform performance evaluation under the same conditions, all the Lambdas have been set up with 256 MB of memory. This configuration gives the Lambda 1/7 of vCPU.</p><h4><strong>Provisioned concurrency</strong></h4><p>To reduce the number of cold starts, it is possible to take advantage of a new feature called <a href="https://docs.aws.amazon.com/lambda/latest/dg/configuration-concurrency.html#configuration-concurrency-provisioned"><em>provisioned concurrency</em></a> which keeps some Lambdas always warm.</p><h3>How to Evaluate Performance</h3><p>Lambda performances are really important as the service is sold as “pay-per-use”. Keeping the execution time and the memory amount usage low helps to reduce the on-going <a href="https://aws.amazon.com/lambda/pricing/">costs</a> of AWS Lambda.</p><p>Performance of languages on AWS Lambda is defined by:</p><ul><li>The size of the code to execute.</li><li>The amount of memory used.</li><li>The execution speed.</li></ul><p>The execution of a simple “Hello, World” gives a rough idea of how the language performs on a very basic task and it’s quite accurate in evaluating the AWS Lambda runtime for the language.</p><p>Heavy computational tasks may dramatically change the results of the “Hello, World” benchmark as, in this case, the test will advantage the language efficiency in dealing with computational complexity rather than the AWS Lambda runtime.</p><p>For simplicity, the article will consider only the “Hello, World” benchmark leaving the task of proofing the efficiency for other workloads to the reader.</p><h3>Code and Size</h3><p>To compare the performances to Swift, the Hello World example has been implemented in different languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wc9aAkHVQgz0b9NCjNqBDA.png" /></figure><p>In the table above are the configurations used for the test.</p><h4>Swift vs. other languages</h4><p>The first thing to notice is that AWS provides a runtime for Ruby, Node.js, Python, Java, <a href="https://golang.org/">Go</a>, and <a href="https://dotnet.microsoft.com/download/dotnet-core/2.1">.Net Core 2.1</a>. This gives these languages an advantage as they don’t have the overhead of a custom runtime with additional code to load.</p><p>The Hello World example is pretty basic, the code size can be totally different as the code adds more dependencies.</p><p>The code used for Node.js, Python, Go, Ruby, Java, C#, and <a href="https://www.rust-lang.org/">Rust</a> is the same provided by the article <a href="https://medium.com/the-theam-journey/benchmarking-aws-lambda-runtimes-in-2019-part-i-b1ee459a293d"><em>Benchmarking AWS Lambda runtimes 2019</em></a> with the addition of the Swift examples.</p><h4>Swift builds and runtimes</h4><p>Many versions of the Hello World code in Swift have been added to compare the performances of:</p><ul><li>Swift runtime with <a href="https://github.com/swift-server/async-http-client">AsyncHTTPClient</a> vs. <a href="https://curl.haxx.se/libcurl/">libcurl</a>.</li><li>AsyncHTTPClient vs. <a href="https://github.com/swift-server/async-http-client/pull/105">AsyncHTTPClient with connection pool</a>.</li><li><a href="https://github.com/swift-sprinter">Swift-Sprinter</a> vs. <a href="https://github.com/fabianfett/swift-lambda-runtime">Swift-Lambda-Runtime</a>.</li><li>Swift code built with <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Ubuntu</a> vs. <a href="https://fabianfett.de/amazonlinux-swift">Amazon Linux 2</a>.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8DAUQ7TNVscZNPSAkL4R9A.png" /><figcaption>benchmark-swift-NIO-hello — SwiftSprinter with NIO AsyncHTTPClient</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r5TGkX1kYGDrnJUfLQyI-w.png" /><figcaption>benchmark-swift-curl-hello — SwiftSprinter with libCURL</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ujXvUSp5aH9j2Q4tqRqQog.png" /><figcaption>benchmark-al-ffett-hello — LambdaSwiftRuntime with NIO</figcaption></figure><h3>Workload</h3><p>The workload has been prepared as in the articles referenced at the end.</p><p>The tool <a href="https://artillery.io/">Artillery</a> has been used to test the Lambdas. An API gateway has been configured to publish the Lambdas as HTTPS endpoints.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IAzfXNnHMY9TvAHV-0rcfw.png" /></figure><p>After the invocation, all the metrics are stored in <a href="https://aws.amazon.com/cloudwatch">AWS CloudWatch</a>.</p><h3>Cold Start Performances</h3><p>The cold start performances have been gathered using the <a href="https://github.com/lumigo-io/lumigo-CLI">lumigo-CLI</a>.</p><pre>lumigo-cli analyze-lambda-cold-starts</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eCGtAMgbLwZvf8YbmAlW9w.png" /><figcaption>Cold Start performances</figcaption></figure><ul><li>The best performance on cold start is given by Rust (~30ms) and Go (~75ms) followed by Ruby (124ms), Python (~127ms), and Node.js (~128).</li><li>A second group contains Swift built with Amazon Linux 2 (~190ms/~219ms) and C# .Net Core (~224ms).</li><li>The last group contains Swift built with Ubuntu (~329ms/~338ms) and Java (~358ms).</li><li>The difference between Swift built with Amazon Linux 2 and Ubuntu is about 20 MB of package size which pays around ~140 ms on cold start.</li></ul><h3>Warm Start Performances</h3><p>To show the warm start performances, we used a custom dashboard on CloudWatch:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Npvy5vfATd6iT9eTu5w6gA.png" /><figcaption>Java/Go/Ruby</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHEj1DlytAP05cXOY1V9Qw.png" /><figcaption>Python/Rust/C#</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yNdYuXj1sU_bT2Ol_PIm7g.png" /><figcaption>Swift Built with Amazon Linux 2</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o0cJwSluon54UGWVzAyj2Q.png" /><figcaption>C#/NodeJS/Swift built with Ubuntu</figcaption></figure><p>The best performance on average is given by C# .Net (~0.26 ms) and Go (~0.44 ms).</p><p>With performances of around 1 ms, we have Node.js (~1.06ms), Java (~1.16 ms), Rust (~1.17 ms), Swift with NIO and connection pooling built with Ubuntu (~1.19ms), Python (~1.34), Swift with NIO (~1.56 ms).</p><h4>Swift build comparison</h4><ul><li>Swift runtime with <a href="https://github.com/swift-server/async-http-client">AsyncHTTPClient</a> NIO performs better than Swift with libcurl with an advantage of ~0.65 ms.</li><li><a href="https://github.com/swift-server/async-http-client/pull/105">AsyncHTTPClient NIO with connection pool</a> is the best performer with an advantage of ~0.30 ms on the same version without pooling and overall performance of ~1.19ms, comparable to Node.js, Java, and Python.</li><li><a href="https://github.com/swift-sprinter">Swift-Sprinter</a> performs slightly better than <a href="https://github.com/fabianfett/swift-lambda-runtime">Swift-Lambda-Runtime</a> with a difference of ~0.20 ms.</li><li>Swift code built with <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Ubuntu</a> vs. <a href="https://fabianfett.de/amazonlinux-swift">Amazon Linux 2</a> performs with similar times at warm start.</li></ul><h3>Why Should I Use Swift on AWS Lambda?</h3><p>Swift was open-sourced in December 2015 by Apple and has grown from mobile development on iOS and Mac to Linux server platforms such as Ubuntu.</p><p>Anyone coming from iOS knows that the language is <a href="https://swift.org/about/">safe, fast, and expressive</a>. Compared to scripting languages such as Node.js and Python, Swift enhances security and performance, avoiding malicious side-effects due to language undefined behavior and the lack of type checking.</p><p>Compared to relatively new languages such as Go or Rust, Swift adds the advantage of a large community of mobile developers and enthusiasts.</p><p>The investments of Apple on <a href="https://github.com/apple/swift-nio/">Swift NIO</a> and the availability of the <a href="https://swift.org/package-manager/">Swift Package Manager</a> have fuelled the development of many <a href="https://swift.org/server/">server-side</a> projects and libraries including <a href="https://github.com/swift-server/async-http-client">HTTP Client</a>, <a href="https://github.com/vapor/nio-postgres">Postgres Client</a>, <a href="https://github.com/mordil/swift-redis-nio-client">Redis Client</a>, <a href="https://github.com/swift-aws/aws-sdk-swift">AWS SDK Swift</a>, <a href="https://github.com/mongodb/mongo-swift-driver">MongoDB Swift Driver</a>, <a href="https://github.com/grpc/grpc-swift/tree/nio">gRPC Swift</a>, … and more.</p><p>The <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Swift-Sprinter</a> repository provides an AWS Lambda custom runtime for Swift and is based on Ubuntu to guarantee the build process and a well-defined pipeline. The repository contains examples of usage and continuous integration.</p><p>For anyone wanting to experiment, the repository <a href="https://github.com/fabianfett/swift-lambda-runtime">Swift-Lambda-Runtime</a> provides a version of Swift built on top of Amazon Linux 2.</p><p>The availability of Swift on serverless frameworks like <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter-core">AWS</a>, <a href="https://github.com/apache/openwhisk-runtime-swift">OpenWhisk</a>, and <a href="https://github.com/SalehAlbuga/azure-functions-swift">Azure</a>, as well as traditional API/web frameworks such <a href="https://vapor.codes/">Vapor</a>, <a href="https://github.com/IBM-Swift/Kitura">Kitura</a>, and <a href="https://perfect.org/">Perfect</a> on VMs, Docker, Kubernetes, and on-premise HW has opened the road to full-stack Swift development.</p><p>This article doesn’t cover the choice of a specific cloud provider as this would depend on different business reasons rather than technical considerations.</p><p>The advantage of using Swift on AWS Lambda rather than containers is effective when the application built with it doesn’t have a constant workload and requires to be scalable while keeping costs low. Serverless and containers are not silver bullets and the choice needs to be evaluated per use case.</p><h3>Considerations</h3><p>The AWS Lambda runtime choice doesn’t depend only on performance considerations.</p><p>It’s always important to consider the total cost of ownership of a solution, taking into account not only the bare cost of the serverless but also reliability, maintainability, resilience, reusability, security, platform support, availability of third-party frameworks, developer community maturity, development tools, licenses, availability of development skills, and learning curve regarding the specific use case.</p><h3>References</h3><ul><li><a href="https://dev.to/sosnowski/anatomy-of-aws-lambda-1i1e">Anatomy of AWS Lambda</a></li><li><a href="https://medium.com/the-theam-journey/benchmarking-aws-lambda-runtimes-in-2019-part-i-b1ee459a293d">Benchmarking AWS Lambda runtimes in 2019 (part I)</a></li><li><a href="https://read.acloud.guru/comparing-aws-lambda-performance-when-using-node-js-java-c-or-python-281bef2c740f">Comparing AWS Lambda performance when using Node.js, Java, C# or Python</a></li><li><a href="https://aws.amazon.com/blogs/compute/new-for-aws-lambda-predictable-start-up-times-with-provisioned-concurrency/">New for AWS Lambda - Predictable start-up times with Provisioned Concurrency | Amazon Web Services</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d920521130f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/swift-on-aws-lambda-performs-like-node-and-python-using-swift-sprinter-d920521130f1">Swift on AWS Lambda Performs Like Node and Python, Using Swift-Sprinter</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s New in Server-Side Swift?]]></title>
            <link>https://medium.com/better-programming/whats-new-in-server-side-swift-3834e70d2281?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/3834e70d2281</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[server-side-swift]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 04:20:54 GMT</pubDate>
            <atom:updated>2019-11-06T10:02:03.596Z</atom:updated>
            <content:encoded><![CDATA[<h4>A look at the talks and presentations at ServerSide.swift 2019</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BqLFQ4fxNL1UnY2vNguLyw.jpeg" /><figcaption>The panel discussion @ ServerSide.swift 2019 — Photo Andrea Scuderi</figcaption></figure><p>Last week, I had the privilege to be at the two-days <a href="https://www.serversideswift.info/">ServerSide.swift conference</a> 2019, held in the beautiful Danish capital, Copenhagen.</p><p>The conference worked as a fantastic space to gather people from all over the world with a passion for <a href="https://developer.apple.com/swift/">Swift</a>, to share ideas, practices, innovations, and tools around <a href="https://swift.org/">SwiftLang</a> on server-side.</p><p>The event was organized in the inspiring building of Blox, the Danish Architecture Centre and the conference was surrounded by the exhibition of the Danish Architect Bjarke Ingels.</p><p>Although it might seem unusual for some of you to celebrate a technical conference in an architecture center, I actually found it fascinating as it was a reminder that we are architects too, in a different way, as our art is writing software, but architects nonetheless.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ubWgDLqbPx0q-jXdouYeFA.jpeg" /><figcaption>Bjarke Ingels exhibition at DAC — Photo Andrea Scuderi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0ndJkLYPk9CPhYhlJpgzA.jpeg" /><figcaption>Copenhagen sight from BLOX DAC — Photo Andrea Scuderi</figcaption></figure><p>The objective of the conference was to learn and share a number of different related topics with those who, like me, have a true passion for server-side Swift.</p><p>It has also shown the incredible opportunity available for Swift developers in the back-end panorama. The new <a href="https://github.com/apple/swift-nio">swiftNIO 2</a> and the <a href="https://github.com/swift-server/async-http-client">async-http-client</a> have opened plenty of possibilities for Swift in the back end.</p><p>In this article, you will find a short and sweet summary of the most relevant talks and key takeaways I brought home from each of them.</p><p>My objective is to give you a taste of what the conference was, and if you are curious like me, it might even work as a starting point to get involved in the fascinating server-side Swift world.</p><p>For those new to the topic, server-side Swift means the use of the <a href="https://github.com/apple/swift">Swift</a> language, open-sourced by Apple in 2015, to develop server applications based not only on macOS but also on Linux.</p><h3>SSWG — Swift Server Work Group</h3><p>Talk by Logan Wright, co-founder at Vapor.</p><p>The Swift <a href="https://swift.org/server/">Server</a> Work Group is an independent steering group with the goal to eventually recommend libraries and tools for server application development with Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*smEP7scEWcPgKVaJqjSeOg.jpeg" /><figcaption>Logan Wright at Vapor — Photo Andrea Scuderi</figcaption></figure><p>The incubation process was explained at the conference, revealing the below tools, available for the community.</p><p>Swift NIO: Event-driven network application framework for high-performance protocol servers and clients, non-blocking.</p><ul><li>Logging API: A logging API for Swift.</li><li>Metrics API: A metrics API for Swift.</li><li>PostgresNIO: Non-blocking, event-driven Swift client for <a href="https://www.postgresql.org/">PostgreSQL</a>.</li><li>Redis Client: Non-blocking, event-driven Swift client for <a href="https://redis.io/">Redis</a>.</li><li>HTTP client: HTTP client library built on SwiftNIO.</li><li>APNS Client: An HTTP/2 APNS library built on swift-nio.</li><li>Statsd Client: Metrics back end for swift-metrics that uses the <a href="https://github.com/statsd/statsd">statsd</a> protocol.</li><li>SwiftPrometheus: Client-side <a href="https://prometheus.io/">Prometheus</a> library in Swift.</li></ul><p>In particular, the Swift NIO 2.0 framework has reached the graduated status, meaning that it:</p><ul><li>Adopts all SSWG-graduation requirements.</li><li>Has committers from at least two organizations.</li><li>Receives a supermajority vote from the SSWG to move to graduation stage.</li></ul><p>The work of Swift NIO development is sustained by Apple and opened plenty of opportunity for server-side SDKs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k6qRC8gy6QnfarJ6jiN4MA.jpeg" /><figcaption>Cory Benfield at Apple — Photo Andrea Scuderi</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mw6GYQuv81-IrH6mN7JxSg.jpeg" /><figcaption>Johannes Weiss at Apple — Photo Andrea Scuderi</figcaption></figure><p>Very interesting insight into Building State Machines in Swift by Cory Benfield from Apple, used to implement the SwiftNIO and <em>Testing SwiftNIO Systems</em> by Johannes Weiss from Apple.</p><p>It’s strongly recommended to study the implementation of SwiftNIO.</p><h3>Static Site Generation in Swift</h3><p>By John Sundell.</p><p>Next on my list is John Sundell’s talk on how he has developed his blog in Swift without using JavaScript.</p><p>He used his provocative disclaimer “Generated using Swift. 100% JavaScript-free”, explaining that removing JavaScript helped his blog with SEO. He presented very elegant code with a hot-reloading live demo and he anticipated that the tool will be available open-source by the end of the year.</p><p>The tool is composed of three packages called: <em>Ink, Plot, Publish</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cD27GnbtToLrvJM7o5-sw.jpeg" /><figcaption>John Sundell — Photo Andrea Scuderi</figcaption></figure><h3>Kitura</h3><p>By Ian Partrige from IBM.</p><p>Moving onto frameworks, there was a talk about <a href="https://www.kitura.io/">Kitura</a>, a web framework and web server that is created for web services written in Swift.</p><p>The evolution of the project was presented, explaining that the tool fully supports SwiftNIO 2.0 since version 2.7. A big improvement comes with version 2.9 with <a href="https://swagger.io/docs/specification/about/">OpenAPI</a> support.</p><p>A new tool called <a href="https://appsody.dev/">Appsody</a> allows for the deployment of Kitura solutions with <a href="https://kubernetes.io/">Kubernetes</a> using Prometheus and <a href="https://grafana.com/">Grafana</a> for the metrics.</p><p>A <a href="https://github.com/IBM/Kitura-SOS-Workshop">very good tutorial</a> has been released.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*evzgX6FA9mksgLYtYD_50A.jpeg" /><figcaption>Ian Partridge at IBM— Photo Andrea Scuderi</figcaption></figure><h3>Vapor</h3><p><a href="https://vapor.codes/">Vapor</a>, the well-known server-side Swift web framework, has introduced, in the 4.0 version, support for SwiftNIO 2.0 and the HTTP/2 protocol. A lot of presentations around Vapor and how it has been used in production:</p><p><a href="https://speakerdeck.com/calebkleveter/resilient-microservices-in-vapor"><em>Building Microservices</em></a> by Ralph Küpper from Skelpo and <em>Resilient Micro-Services with Vapor</em> by Caleb Kleveter from Skelpo on how to design microservices with Vapor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jt6EaUVoBjz2nd0f50d_YQ.jpeg" /><figcaption>Ralph Küpper @ Skelpo — Photo Andrea Scuderi</figcaption></figure><p><em>Let’s Go Serverless with Swift using Vapor</em> by Timirah James from Cloudinary. A <a href="https://github.com/timirahj/Server-Side-Swift-using-Vapor-Talk">tutorial</a> is available.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GbM95lIE-EdDg723LParVA.jpeg" /><figcaption>Timirah James @ Cloudinary — Photo Andrea Scuderi</figcaption></figure><p><em>Getting Started with Vapor</em> by the Vapor co-founder, Tanner Nelson.</p><p><em>Swift development on Linux</em> by Jonas Schwartz.</p><p>A very passionate talk on using Linux as development platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPH7uobhLcJovayq2CLJHQ.jpeg" /><figcaption>Jonas Schwartz — Photo Andrea Scuderi</figcaption></figure><h3>gRPC</h3><p><a href="https://github.com/grpc/grpc-swift">Talk</a> by Daniel Alm from TimingApp.</p><p>This talk on <a href="https://timingapp.com/grpc"><em>Supercharging your Web APIs with gRPC</em></a> introduced the open-source gRPC, a messaging system based on Google’s internal API architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wUWa_4QapwUb7ncvojc2og.jpeg" /><figcaption>Daniel Alm from TimingApp — Photo Andrea Scuderi</figcaption></figure><h3>MongoDB</h3><p>Talk by Kaitlin Mahar from <a href="https://github.com/mongodb/mongo-swift-driver">MongoDB</a>.</p><p>Very interesting insight into the commitment of MongoDB in creating and supporting the Swift-MongoDB Client: <a href="https://speakerdeck.com/kmahar/maintaining-a-library-in-a-swiftly-moving-ecosystem"><em>Maintaining a Library in a Swiftly Moving Ecosystem</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qDGHQ8IxwzAEbNf0Z2hMZg.jpeg" /><figcaption>Kaitlin Mahar from MongoDB — Photo Andrea Scuderi</figcaption></figure><h3>AWSSDKSwift</h3><p>Talk by Joe Smith from Slack.</p><p>This talk about <em>Fluently NoSQL: Creating FluentDynamoDB</em> revealed the <a href="https://github.com/swift-aws/aws-sdk-swift">AWSSDKSwift</a>, an open-source, community-maintained framework for interacting with<a href="https://aws.amazon.com/"> Amazon Web Services</a> and the implementation of <a href="https://github.com/gonsuke/fluent-plugin-dynamodb">FluentDynamoDB</a>.</p><p>AWSSDKSwift allows you to consume AWS services from Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pzVUL63N9EFxtyvwe-cVLA.jpeg" /><figcaption>Joe Smith from Slack — Photo Andrea Scuderi</figcaption></figure><h3>SmokeFramework</h3><p>Talk by Simon Pilkington from Amazon Web Services.</p><p>A light-weight server-side service framework written in the Swift programming language.</p><p>In <em>Building the next version of the Smoke Framework</em>, it was explained how the <a href="https://github.com/amzn/smoke-framework">tool</a> can generate the code from a Swagger/OpenAPI definition and the evolution of the framework, now supporting SwiftNIO 2.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eHprCwHVTZQQ5nopJ2oCxw.jpeg" /><figcaption>Simon Pilkington from Amazon Web Services — Photo Andrea Scuderi</figcaption></figure><h3>Server-Side Swift in Production</h3><p>Plenty of use cases in production were described while talking with all the participants. I found the following presentations very relevant:</p><p><em>How we Vapor-ized our Mac app</em> by Matias Piipari from ManuscriptsApp.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nCHC7_uySKuk1z_yTFs_8g.jpeg" /><figcaption>Matias Piipari @ ManuscriptsApp — Photo Andrea Scuderi</figcaption></figure><p><em>Full stack Swift development: how and why</em> by Ivan Andriollo from EqualExpertsGermany.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WrrR_FF30s_tMTRP6mFaCw.jpeg" /><figcaption>Ivan Andriollo from EqualExperts Germany — Photo Andrea Scuderi</figcaption></figure><p><em>Building high-tech robots with Swift — a story from the front lines</em> by Gerwin de Haan and Mathieu Barnachon from StyleShoots.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x3ofCALUJUGlUi5XoPg9tQ.jpeg" /><figcaption>Gerwin de Haan &amp; Mathieu Barnachon @ StyleShoots — Photo Andrea Scuderi</figcaption></figure><p><em>Breaking into tech</em> by Heidi Hermann from NodesAgency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iCIrIY-zgwynFpUkQ2W9ug.jpeg" /><figcaption>Heidi Hermann fromNodesAgency — Photo Andrea Scuderi</figcaption></figure><p>My tool to run AWS Lambda in Swift, <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">Swift-Sprinter</a> was mentioned at the panel discussion. The tool, by using other libraries such as AWSSDKSwift, SwiftNIO 2, and HTTPClient, allows you to use serverless architecture on AWS.</p><p>I’ll not reveal the full content of the panel discussion as the recording will be available soon.</p><h3>Conclusion</h3><p>The Swift ecosystem on server-side is growing very fast and it starts to be appealing to innovators and new production projects.</p><p>The enthusiasm and the competence of the people involved in developing the tools are very high and given the references of the Swift community in open-source, we can bet it will grow more and more in the immediate future.</p><p>A big thanks to all the organizers, <a href="https://instagram.com/martin_lasek">Martin J. Lasek</a>, <a href="https://twitter.com/0xTim">Tim Condon</a>, <a href="https://twitter.com/steffendsommer">Steffen D. Sommer</a> and Olivia Lippmanm who have excelled in the event organization. See you next year!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3834e70d2281" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/whats-new-in-server-side-swift-3834e70d2281">What’s New in Server-Side Swift?</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Work with AWS Lambda in Swift]]></title>
            <link>https://medium.com/better-programming/how-to-work-with-aws-lambda-in-swift-28326c5cc765?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/28326c5cc765</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[server-side-swift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Mon, 30 Sep 2019 17:50:17 GMT</pubDate>
            <atom:updated>2019-09-30T17:50:17.510Z</atom:updated>
            <content:encoded><![CDATA[<h4>Introducing Swift-Sprinter, an open-source library for Swift with AWS Serverless</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*myGuDEbX3iJt-Ye3F8fSPQ.jpeg" /><figcaption>The Power of Swift to AWS Lambda</figcaption></figure><h3>Introduction</h3><p>This story starts some years ago when, as an iOS developer at BJSS, I was involved in delivering an iOS mobile app for a government agency in the UK with an AWS Serverless backend. I had an exciting time learning about Lambda, S3, DynamoDB, SNS, Cognito, API Gateway, IAM, and friends. At the end my proof of concept of for an <em>AWS Serverless</em> backend and the mobile <em>iOS Swift native</em> app went to alpha, beta, and now production.</p><p>I realised that building this backend for a mobile app with Serverless is <em>inexpensive and scalable</em> from day one and requires very little maintenance compared to a containerised solution or virtual machines. The Serverless approach is quite effective when the backend load cannot be predicted.</p><p>The <em>pay per use</em> model introduced with Serverless could be useful in validating a startup idea or a small project.</p><p>Only one thing disappointed me — as an iOS developer, I would have written it in my beloved language Swift but at that time it wasn&#39;t supported by AWS. So I handed over the PoC of the backend to a developer skilled in the other language and I developed the iOS app.</p><p>So I started research in my spare time to make my dream become reality…</p><p>A month ago, I came across some half-working solutions that all had a big issue: HTTPS calls were not working.</p><p>After I while I developed a working solution with HTTPS and made an open-source framework called <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">swift-sprinter</a>.</p><p>With this framework it’s possible to consume AWS services from the Lambda written in Swift 5.0 and 5.1. If you’re curious of how to use swift-sprinter to get an object from an S3 bucket, read <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter/blob/master/Examples/S3Test/README.md">this</a>.</p><h3>Demo HTTPS API Request from Swift Lambda</h3><p>To keep the things simple, in this article, I’ll show how to write an AWS Lambda to query the <a href="https://dog.ceo/dog-api/">dog-api</a>.</p><p>The goal is to retrieve a JSON with a list of images URL from this API by passing our favourite breed:</p><pre>https://dog.ceo/api/breed/hound/afghan/images</pre><p>Then retrieving a JSON like this:</p><pre>{<br>    &quot;message&quot;: [<br>        &quot;https://images.dog.ceo/breeds/hound-afghan/n02088094_1003.jpg&quot;,<br>        &quot;https://images.dog.ceo/breeds/hound-afghan/n02088094_1007.jpg&quot;<br>    ],<br>    &quot;status&quot;: &quot;success&quot;<br>}</pre><p>You need:</p><ul><li><a href="https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/">AWS Account</a></li><li>Admin permissions on AWS or the policies required to deploy Lambda</li><li><a href="https://www.docker.com/products/docker-desktop">Docker</a></li><li><a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">AWS Command Line Interface</a></li></ul><p>I suggest taking a look at the <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter/blob/master/README.md">README</a> on GitHub before you continue the reading to prepare your mac with the requirements.</p><h3>Development Workflow</h3><p>From the command line:</p><pre>git clone <a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter.git">https://github.com/swift-sprinter/aws-lambda-swift-sprinter.git</a></pre><pre>cd aws-lambda-swift-sprinter/Examples/HTTPSRequest</pre><p>Generate the Xcode project and open it with Xcode:</p><pre>swift package generate-xcodeproj</pre><p>Open XCode and Navigate to the file main.swift and inspect it.</p><p>The Event is correct — we want to send a URL as an input event.</p><pre><strong>struct</strong> Event: Codable {<br>    <strong>let</strong> url: String<br>}</pre><p>The HTTPSRequest lambda example will give a Response with url and content when the execution is complete — this is not good for our purposes:</p><pre><strong>struct</strong> Response: Codable {<br>   <strong>let</strong> url: String<br>   <strong>let</strong> content: String<br>}</pre><p>We change the response to reflect the JSON we want to receive:</p><pre><strong>struct</strong> Response: Codable {<br>   <strong>let</strong> message: [String]<br>   <strong>let</strong> status: String<br>}</pre><p>We now receive message with an Array of String and a status with a String.</p><p>Now to return the Response we need fix the lambda code return type with the new one:</p><pre>...</pre><pre>  <strong>let</strong> decoder = JSONDecoder()<br>  <strong>let</strong> output = <strong>try</strong> decoder.decode(Response.<strong>self</strong>, from: data)<br>  <strong>return</strong> output<br>}</pre><p>The previous code encodes the data received to Response and returns it as Lambda output.</p><p>This is the final output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LviJsycnasPJyQbX7NVCWg.png" /></figure><p>Now open aws-lambda-swift-sprinter/Makefile</p><pre>cd ../../ &amp;&amp; open Makefile</pre><p>Comment the following lines:</p><pre># HelloWorld Example Configuration<br># SWIFT_EXECUTABLE=HelloWorld<br># SWIFT_PROJECT_PATH=Examples/HelloWorld<br># LAMBDA_FUNCTION_NAME=HelloWorld<br># LAMBDA_HANDLER=$(SWIFT_EXECUTABLE).helloWorld</pre><p>Then un-comment the line after:</p><pre># HTTPSRequest Example Configuration<br>SWIFT_EXECUTABLE=HTTPSRequest<br>SWIFT_PROJECT_PATH=Examples/HTTPSRequest<br>LAMBDA_FUNCTION_NAME=HTTPSRequest<br>LAMBDA_HANDLER=$(SWIFT_EXECUTABLE).getHttps</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J-z4zve0ZoaxYN_V1NOa1Q.png" /></figure><p>Save and close the file.</p><h3>Lambda Building</h3><p>Lambda runs on a custom version of Amazon Linux. To build Lambdayou need a Swift custom docker image.</p><p>To build the image use this command:</p><pre>make docker_build</pre><p>Now test the build from the command line:</p><pre>make build_lambda</pre><p>This will take a few minutes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*baVxpn7ZSFmLs4OjwyK77w.png" /></figure><p>Great! The code works on Swift docker too, that means it’s ready to be deployed.</p><h3>AWS Deployment</h3><p>To complete this step you must have the <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-install.html">AWS Command Line interface</a> installed and have registered your <a href="https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html">configuration and credentials</a>.</p><p>Now we need to build the custom runtime:</p><pre>make package_layer</pre><p>We have to upload the lambda layer:</p><pre>make upload_lambda_layer</pre><p>Under the .build folder, list a zip file called swift-lambda-runtime-5.1.zip and a file called nio-swift-lambda-runtime-5-1-arn.txt.</p><pre>make create_lambda</pre><p>This command will create the Lambda on AWS after rebuilding the code.</p><p>After the command complete, go to the AWS console and inspect the HTTPSRequest lambda.</p><h3>Lambda Invocation</h3><p>To invoke the Lambda we need to set up the event:</p><pre>open Examples/HTTPSRequest/event.json</pre><p>Ùpdate it with this:</p><pre>{</pre><pre>&quot;url&quot;: &quot;https://dog.ceo/api/breed/hound/afghan/images&quot;</pre><pre>}</pre><p>Now run the Lambda invocation:</p><pre>make invoke_lambda</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dkFNZ5HWD7iYf9KMPAR5aw.png" /></figure><h3>Conclusion</h3><p>Working with Swift on AWS is becoming a reality, even if at this early stage the solution seems quite promising. If you are interested to get involved in the open-source development of Swift Sprinter the project is open for contributions.</p><p>I hope you liked it! Thanks for reading.</p><h3>References</h3><ul><li><a href="https://github.com/swift-sprinter/aws-lambda-swift-sprinter">swift-sprinter/aws-lambda-swift-sprinter</a></li><li><a href="https://medium.com/@danilop/agile-development-for-serverless-platforms-978bf38e82b7">Agile Development for Serverless Platforms</a></li><li><a href="https://aws.amazon.com/serverless/">Serverless Computing</a></li><li><a href="https://medium.com/capital-one-tech/serverless-computing-with-swift-f515ff052919">Serverless Computing with Swift</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=28326c5cc765" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/how-to-work-with-aws-lambda-in-swift-28326c5cc765">How To Work with AWS Lambda in Swift</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Unit Test a DataTaskPublisher With URLProtocol]]></title>
            <link>https://medium.com/better-programming/swift-unit-test-a-datataskpublisher-with-urlprotocol-2fbda186758e?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fbda186758e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Tue, 03 Sep 2019 22:40:15 GMT</pubDate>
            <atom:updated>2019-09-03T22:40:15.352Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to implement the unit test for a DataTaskPublisher using URLProtocol</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*hnIGzvz7VDpQFpYa" /><figcaption>Photo by <a href="https://unsplash.com/@alinnnaaaa?utm_source=medium&amp;utm_medium=referral">Alina Grubnyak</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/better-programming/upgrade-your-swift-api-client-with-combine-4897d6e408a0">my last article</a>, I went through the implementation of a data publisher with the Combine API and URLSession, and how to use it as an API client.</p><p>This time, we’ll create a Swift package for our API client and we’ll implement the unit test for it.</p><p>Last time, we proved the API client works by doing some integration testing against a Docker instance.</p><p>This time, by implementing the unit tests, we complete our code so we can maintain the library in the future and prove we didn’t miss relevant use cases.</p><p>A full unit test of our API client will require us to prove that the client works correctly, not only when the server is available and provides the correct response and data, but also when the response is not valid or the data is corrupted, or there is a network failure.</p><p>Note: you need Xcode 11 to complete this tutorial.</p><h3>Swift Package Preparation</h3><blockquote>“The Swift Package Manager is a tool for managing the distribution of Swift code. It’s integrated with the Swift build system to automate the process of downloading, compiling, and linking dependencies.” — <a href="https://swift.org/package-manager/">Swift Package Manager documentation</a></blockquote><p>With Swift Package Manager, we will create a custom library and the unit tests for it.</p><h4>Create a new package</h4><p>From the command line, create a directory, in our case CombineAPIDemo:</p><pre>mkdir CombineAPIDemo<br>cd CombineAPIDemo</pre><p>Initialize your new package:</p><pre>swift package init</pre><p>The package init will create the project scaffolding for a library:</p><pre>Creating library package: CombineAPIDemo</pre><pre>Creating Package.swift<br>Creating README.md<br>Creating .gitignore<br>Creating Sources/<br>Creating Sources/CombineAPIDemo/CombineAPIDemo.swift<br>Creating Tests/<br>Creating Tests/LinuxMain.swift<br>Creating Tests/CombineAPIDemoTests/<br>Creating Tests/CombineAPIDemoTests/CombineAPIDemoTests.swift<br>Creating Tests/CombineAPIDemoTests/XCTestManifests.swift</pre><p>Now, we generate the Xcode project:</p><pre>swift package generate-xcodeproj</pre><p>And we’ll open it:</p><pre>open CombineAPIDemo.xcodeproj</pre><p>Great! Your first package is ready! Now, you need to add the code.</p><h4>Add the code to the package</h4><p>Overwrite CombineAPIDemo.swift with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/284e54876b92f89e08a33a0cd85795a2/href">https://medium.com/media/284e54876b92f89e08a33a0cd85795a2/href</a></iframe><p>I refactored some classes that we discussed in the <a href="https://medium.com/better-programming/upgrade-your-swift-api-client-with-combine-4897d6e408a0">previous article</a>, so it will be possible to build a DataTaskPublisher with a custom session, which will be injected during the unit test.</p><p>Our APIDemo.publisher is now based on the APIDataTaskPublisher protocol, implemented by the class APISessionDataTaskPublisher. This will allow us to change the URLSession inside the publisher by using a mock for our responses.</p><p>Inside the APIDemo class we have three different types of static functions:</p><ul><li>Public: The functions we want to show to the package consumer.</li><li>Internal: The functions we need to unit test.</li><li>Private: The functions used as utilities, used by the internal functions. We cannot test it directly as they are not accessible by the unit test class, but they will be tested as part of the test of the internal functions.</li></ul><p>Great! Now we have the code to unit test. Try to build it, to check that it builds correctly.</p><h3>Let’s Dive Into the Unit Tests</h3><h4>Internal functions returning a DataTaskPublisher</h4><p>The unit test of the internal functions returning a DataTaskPublisher will test that the request created is correct.</p><pre><strong>func</strong> testPostUserDTP() {<br>   <strong>let</strong> future = <strong>try</strong>? APIDemo.postUserDTP(user: <strong>self</strong>.mocks.user)<br>   <strong>let</strong> request =  future?.request<br>   XCTAssertEqual(request?.url?.absoluteString, APIDemo.baseURL + &quot;/users&quot;)</pre><pre>...</pre><pre>...</pre><pre>}</pre><h4>Mocking the URLSession</h4><p>Add a new Swift file under the Tests\CombineAPIDemoTests folder and name it URLProtocolMock with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8146cfc1c926a6519064731dcffd5910/href">https://medium.com/media/8146cfc1c926a6519064731dcffd5910/href</a></iframe><p>The URLProtocolMock is the key to create a mocked URLSession with our custom responses and data. The class allows to pass our Data, URLResponse, and Error to simulate the behaviour of a network request.</p><p>The mocked URLSession will be created in this way:</p><pre><strong>let</strong> config = URLSessionConfiguration.ephemeral</pre><pre>config.protocolClasses = [URLProtocolMock.<strong>self</strong>]</pre><pre><strong>let</strong> session = URLSession(configuration: config)</pre><p>So, we can create a custom APISessionDataPublisher and assign it to the APIDemo.publisher to mock the network call.</p><pre>let customPublisher = APISessionDataPublisher(session: session)<br>APIDemo.publisher = customPublisher</pre><p>We can setup our response:</p><pre><strong>let</strong> usersURL = URL(string: APIDemo.baseURL + &quot;/users&quot;)</pre><pre>URLProtocolMock.testURLs = [usersURL: Data(Fixtures.createUserResponse.utf8)]<br>URLProtocolMock.response = mocks.validResponse</pre><p>And create our mocked API client publisher.</p><pre><strong>let</strong> customPublisher = APISessionDataPublisher(session: session)</pre><h4><strong>Implement a reusable test function</strong></h4><p>For each test call, we need to test the client for the following conditions:</p><ul><li>A valid response.</li><li>An invalid response due to an invalid URLResponse.</li><li>An invalid response due to an invalid Data.</li><li>An invalid response due to a network failure.</li></ul><p>The following code will show the implementation of the two functions required to test a generic publisher, when it is Valid or Invalid.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ad689496c0af3f4304e8f6788073b4c/href">https://medium.com/media/6ad689496c0af3f4304e8f6788073b4c/href</a></iframe><p>The sink function will perform an asynchronous network call.</p><p>We need to define all the expectations that we will return so we can wait for them inside our test.</p><p>Here is an example of how to configure the test for a valid response:</p><pre><strong>//Setup URLSession Mock</strong><br><strong>let</strong> usersURL = URL(string: APIDemo.baseURL + &quot;/users&quot;)</pre><pre>URLProtocolMock.testURLs = [usersURL:      Data(Fixtures.createUserResponse.utf8)]<br>URLProtocolMock.response = mocks.validResponse</pre><pre><strong>let</strong> config = URLSessionConfiguration.ephemeral<br>config.protocolClasses = [URLProtocolMock.<strong>self</strong>]<br><strong>let</strong> session = URLSession(configuration: config)</pre><pre><strong>let</strong> customPublisher = APISessionDataPublisher(session: session)</pre><pre>APIDemo.publisher = customPublisher</pre><pre><strong>// Create the Publisher<br>let</strong> publisher = APIDemo.create(user: <strong>self</strong>.mocks.user)</pre><pre><strong>// Test the Publisher</strong><br><strong>let</strong> validTest = evalValidResponseTest(publisher: publisher)<br>wait(for: validTest.expectations, timeout:testTimeout)<br>validTest.cancellable?.cancel()</pre><h4>Unit testing a DataTaskPublisher</h4><p>Here is the full example of the test for the create function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1d42cec6b8dc718ea9c1a248828976ee/href">https://medium.com/media/1d42cec6b8dc718ea9c1a248828976ee/href</a></iframe><h3>Wrapping Up</h3><p>Overwrite CombineAPIDemoTests.swift with the following content:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d72f49d5c688b81549e26f8d225b1172/href">https://medium.com/media/d72f49d5c688b81549e26f8d225b1172/href</a></iframe><p>You have now the full test for your API client.</p><p>In Xcode, run the unit tests using the CTRL+U shortcut from the keyboard, or, from the menu, <em>Product-&gt;Test.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V0AzGBHBxXZ4DOyiAjUkLQ.png" /></figure><p>That’s all! Thanks for reading the full article, I hope you liked it.</p><p>Here is the <a href="https://github.com/Andrea-Scuderi/CombineAPIDemo">full project</a>.</p><h3>References</h3><ul><li><a href="https://medium.com/better-programming/upgrade-your-swift-api-client-with-combine-4897d6e408a0">Upgrade Your Swift API Client With Combine</a></li><li><a href="https://github.com/apple/swift-package-manager/blob/master/Documentation/Usage.md">apple/swift-package-manager</a></li><li><a href="https://www.hackingwithswift.com/articles/153/how-to-test-ios-networking-code-the-easy-way">How to test iOS networking code the easy way</a></li><li><a href="https://nshipster.com/nsurlprotocol/">NSURLProtocol</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fbda186758e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/swift-unit-test-a-datataskpublisher-with-urlprotocol-2fbda186758e">Swift: Unit Test a DataTaskPublisher With URLProtocol</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Upgrade Your Swift API Client With Combine]]></title>
            <link>https://medium.com/better-programming/upgrade-your-swift-api-client-with-combine-4897d6e408a0?source=rss-6690818517f1------2</link>
            <guid isPermaLink="false">https://medium.com/p/4897d6e408a0</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[vapor]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Andrea Scuderi]]></dc:creator>
            <pubDate>Thu, 01 Aug 2019 14:14:07 GMT</pubDate>
            <atom:updated>2019-08-05T22:56:30.754Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implement a data publisher with the Combine API and the URLSession, and how to use it as an API client</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0XNDeHBXhjl1ndY9m8dPaw.jpeg" /></figure><blockquote>“The Combine framework provides a declarative Swift API for processing values over time. These values can represent many kinds of asynchronous events. Combine declares publishers to expose values that can change over time, and subscribers to receive those values from the publishers.” <a href="https://developer.apple.com/documentation/combine">Apple Developer documentation.</a></blockquote><p>The new <a href="https://developer.apple.com/documentation/combine">Combine framework</a> released by Apple in the new iOS 13 and <a href="https://developer.apple.com/xcode/">Xcode</a> 11 is quite cryptic… This article shows how to implement a data publisher using the Combine API and the URLSession, and how to use it as an API client.</p><p>This article answers the following questions:</p><ul><li>How to use Combine to get API responses?</li><li>What’s the difference between your old client API and the new one with Combine?</li><li>What are the advantages of using Combine to retrieve data from an API?</li><li>What could be a path to upgrade my old API to be Combine ready?</li><li>How to manage nested API calls with Combine?</li></ul><h3>Let’s Start a Demo API With Vapor and Docker</h3><p>We want an API that can be tested on the Mac with <a href="https://www.apple.com/au/swift/playgrounds/">Swift Playgrounds</a>. The first step is to get a working demo API on it.</p><p>I love Swift, so why don’t we use <a href="https://vapor.codes/">Vapor</a> to run our test API with a server-side Swift app?</p><p>If you don’t know how to install it, follow the instructions <a href="https://docs.vapor.codes/3.0/install/macos/">here</a>. Then, open a terminal on your Mac and type the following:</p><pre>vapor new demo-api --template=auth-template</pre><p>You can try to run the app by using vapor run but at the moment, the macOS 15 beta and Xcode 11 beta are not very reliable to run it.</p><p>To be sure that the Vapor app will run with the right Swift version, we’ll use <a href="https://www.docker.com/">Docker</a> to build and run it. If you don’t have it yet, install Docker on your Mac from <a href="https://www.docker.com/products/docker-desktop">here</a> and then run a Docker container with the Vapor code:</p><pre>cd demo-api</pre><pre>cp web.Dockerfile Dockerfile</pre><pre>docker build . -t demo-api:latest</pre><p>Using the next command, you’ll create your REST API which is listening on the 8080 port:</p><pre>docker run -p 8080:80 --env ENVIRONMENT=DEV demo-api:latest</pre><p>If everything goes well you should see the following message: Server starting on <a href="http://0.0.0.0/">http://0.0.0.0:80</a></p><p>Leave the terminal with Docker open and check the API works. Open a new terminal window and type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cb8f66db5d058a25485abd6d2542162/href">https://medium.com/media/1cb8f66db5d058a25485abd6d2542162/href</a></iframe><p>The output should be:</p><pre>{&quot;id&quot;:1,&quot;email&quot;:&quot;user@example.com&quot;,&quot;name&quot;:&quot;user&quot;}</pre><p>Great, you have done it! You’ve added your first user in the demo API.</p><h3>What Does Our Old API Client Look Like?</h3><p>To start, you need to create a new blank Playground for Mac with Xcode 11 (beta 4 at the moment).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7pA4AzwWa3UJ_8vW6En-gw.png" /></figure><p>Give it a name and copy/paste the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/997e529e48bae216dd243a9f409bd6fc/href">https://medium.com/media/997e529e48bae216dd243a9f409bd6fc/href</a></iframe><p>The old client has been implemented using the dataTask function and must be consumed within a closure.</p><p>Run the playground and check that you have now created user2.</p><h3>How To Use Combine to Get API Responses</h3><p>Now, add the following lines to get the same result using Combine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4480b2d7071f6674610536e1fcd0ae29/href">https://medium.com/media/4480b2d7071f6674610536e1fcd0ae29/href</a></iframe><p>The new client has been implemented using the dataTaskPublisher function. It returns a <em>publisher</em>.</p><p>To consume it, it’s required to <em>subscribe</em> to it. The sink function is a <em>subscriber</em>.</p><h3>The Difference Between the Two API Calls When We Decode the Payload</h3><p>A good app client provides the mapping between the raw data received and the internal classes and structs. The Codable protocol makes it easy to convert raw JSON data to a struct/class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3374e51a7ae85200cc680773846eef98/href">https://medium.com/media/3374e51a7ae85200cc680773846eef98/href</a></iframe><p>Old client (dataTask):</p><ul><li>The completion handler is quite easy to use but becomes unreadable in the case of nested calls.</li></ul><p>New client (dataTaskPublisher):</p><ul><li>It’s a bit harder to write but it’s easy to read as a pipeline. Nested calls can be pipelined.</li></ul><h3>A Path to Upgrade the Old API to Be Combine-Ready</h3><p>Using Future, we can convert our old dataTask to a publisher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9fce750484a9e4cda7bfa2a399419bd2/href">https://medium.com/media/9fce750484a9e4cda7bfa2a399419bd2/href</a></iframe><h3>Full API Client Definition With Combine</h3><p>Here is the complete API, implemented with the dataTaskPublisher. It will be used later.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c43e826b16ac5ef1fef18d58482ba11/href">https://medium.com/media/1c43e826b16ac5ef1fef18d58482ba11/href</a></iframe><h3>Publisher Implementation</h3><p>The DataTaskPublisher is now pipelined to obtain a publisher with a decoded struct.</p><p>A validate function has been defined to validate the response.statusCode.</p><p>Pipeline:</p><pre>DataTaskPublisher—(tryMap with validate)→Data-(decode)→AnyPublisher</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/00f2611e4872a40945c698cefefee55a/href">https://medium.com/media/00f2611e4872a40945c698cefefee55a/href</a></iframe><h3>Using Your Combine API</h3><p>It’s time to use publish with a sink subscriber.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7393529f4e7d76fe63a3f327da8d70a2/href">https://medium.com/media/7393529f4e7d76fe63a3f327da8d70a2/href</a></iframe><h3>Combining Publishers</h3><p>In the previous example, a Token was received after the login.</p><p>To post a Todo, we need to use it as a parameter of the postTodo.</p><p>Here, I show you how the two calls are pipelined.</p><p>Pipeline:</p><pre>[AnyPublisher]-(map)-(flatMap)-&gt;[AnyPublisher]</pre><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64509a5849ed65feda7a7fa50658418b/href">https://medium.com/media/64509a5849ed65feda7a7fa50658418b/href</a></iframe><p>That’s all! Thanks for reading the full article, I hope you liked it.</p><p>Here the full <a href="https://github.com/Andrea-Scuderi/CombineDemoAPIPlayground.git">Playground project</a></p><h3>Cleanup</h3><p>Don’t forget to stop your Docker image when you finish!</p><pre>docker ps -a</pre><pre>CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                       PORTS                  NAMES</pre><pre>16edf993e50f        demo-api:latest     &quot;/bin/sh -c &#39;./Run s…&quot;   3 hours ago         Exited (255) 3 minutes ago   0.0.0.0:8080-&gt;80/tcp   elastic_poitras</pre><p>The above code will give you the list of the Docker containers.</p><p>Get the container name, in my case 16edf993e50f.</p><pre>docker stop 16edf993e50f</pre><p>Remove the image:</p><pre>docker rm 16edf993e50f</pre><h3>References</h3><ul><li><a href="https://developer.apple.com/documentation/combine">Combine | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2019/721">Combine in Practice - WWDC19 - Videos - Apple Developer</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2019/712/">Advances in Networking, Part 1 - WWDC19 - Videos - Apple Developer</a></li><li><a href="https://heckj.github.io/swiftui-notes/">Using Combine</a></li><li><a href="https://theswiftdev.com/2018/11/15/docker-loves-swift-and-vapor/">Docker loves Swift &amp; Vapor - The.Swift.Dev.</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4897d6e408a0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/upgrade-your-swift-api-client-with-combine-4897d6e408a0">Upgrade Your Swift API Client With Combine</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>