<?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 Anderson Santos Gusmão on Medium]]></title>
        <description><![CDATA[Stories by Anderson Santos Gusmão on Medium]]></description>
        <link>https://medium.com/@andersongusmao?source=rss-579b41f847e9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RPruE_rV8cvp9b9t.</url>
            <title>Stories by Anderson Santos Gusmão on Medium</title>
            <link>https://medium.com/@andersongusmao?source=rss-579b41f847e9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 01:13:52 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andersongusmao/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[Learning the machine learning.]]></title>
            <link>https://andersongusmao.medium.com/learning-the-machine-learning-e8b13e40df12?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/e8b13e40df12</guid>
            <category><![CDATA[knn-classification]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <category><![CDATA[knn]]></category>
            <category><![CDATA[knn-algorithm]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Sat, 12 Jun 2021 05:03:55 GMT</pubDate>
            <atom:updated>2021-06-12T05:03:55.844Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*ECHLzyLQqpHhMG8HQO4maA.gif" /></figure><h4>A simple machine learning project for starters.</h4><p>Recently I got started learning artificial intelligence projects and I decided to share here a simple machine learning project which can be a good foundation for those who want to understand how we can teach machines to learn. In this way, at the final, I will present a practical machine learning project for handwriting recognition.</p><h3>Main idea.</h3><p>Did you remember when you learn to read and write? When we learn to read and write at school, generally the teaching method is taught by recognizing patterns in what we called alphanumeric characters. Probably your teacher taught you starting with A B C and so on. In this way and with small steps you came here, now you are reading this article without thinking about how you can understand these letters grouped in words that make sentences.</p><p>This is what we are going to do here, let’s see how we can teach a computer how to recognize patterns in handwriting, but we are going to be simple here in recognizing only one character by time, the idea is to understand the principles of machine learning, by saying that, we need to think simple to reduce the complexity of a solution in order we can ease the comprehension.</p><h3>Before coding we must know the k-nearest neighbor algorithm.</h3><p>In the field of machine learning, some theoretical knowledge is necessary, otherwise, the comprehension of the topic will be extremely hard or maybe impossible. <br>The k-nearest neighbor’s algorithm is a simple, easy-to-implement supervised machine learning algorithm that can be used to solve classification problems.</p><h4>What is supervised machine learning?</h4><p>Supervised machine learning, is a subcategory of machine learning and is defined by its use of labeled datasets to train algorithms to classify data. To make this simple in our project example, we are going to provide handwriting samples of numbers and we are going to say what is each sample to the computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QNAkFdziN4IAOQgzBrgFfA.jpeg" /><figcaption>Supervised machine learning.</figcaption></figure><p>As literate human beings, we are going to recognize these samples and inform the computer algorithm what is each letter, classifying it. With some samples, the algorithm will be able to classify as similar to new numbers that we can ask for classification.</p><p>Bear in mind, based on handwriting image samples we are going to have some numbers references, the new images that we will send to the application hardly will be equal to our dataset reference, but by similarity, the algorithm will infer what should be the new image.</p><h4>Explaining the k-nearest neighbor algorithm.</h4><p>The principle behind of KNN (for short), is that similar things exist in close proximity or by saing that similar things are near to each other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*SjBEgwWJTXjp4VjhdtQJTw.png" /><figcaption>Image taken from <a href="https://www.researchgate.net/">https://www.researchgate.net/</a></figcaption></figure><p>Let’s pick any point in the cartesian plane above. Intuitively is reasonable to think that any point which is close to that point that we picked first, has more things in common if compared with other distant points.</p><p>Now I propose a mental experiment, let’s imagine a new point being introduced into any group above you want <strong>i.e.</strong> blue, green, or red. Based on the classification we did, we can infer the class of this new point without knowing it before, this is how KNN works.</p><h4>How to calculate the distance between two points.</h4><p>As I said before, a little bit of math is necessary to solve machine learning problems but trust me, you can do that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*YLQ2qJlEGnMtfVwVvOHBjA.png" /><figcaption>Euclidean distance calculation.</figcaption></figure><p>The principle to calculate the distance between two points is based on the Euclidean distance calculation formula presented above. In the example here, we have two points where each point has its coordinate axises values, i.e. X and Y. <strong>It is important to know we are not limited by two dimensions in this formula, for the sake of simplicity we have only two dimensions here. Save this information, it will be helpful.</strong></p><h4>Join the pieces.</h4><p>Let’s imagine a situation where we have a new point in the cartesian plane and we want to classify it. It is possible to have many different classes around this new point, right? How can we decide to infer which class this new point belongs to? Here the letter K can be explained, using the Euclidean formula we can calculate the distance between closer points as many as we want, but we need to limit the number of points to count how many similar elements we have in common and elect one class for this new point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/405/1*0Pqqx6wGDfFm_7GLebg2Hw.png" /><figcaption>Classifying with KNN.</figcaption></figure><p>In the example above, we can see that depending on how many elements we choose <strong>i.e.</strong> the letter K, we can have different classification results, by choosing (K=3) elements we have CLASS B, and by choosing (K=7) elements we have CLASS A. This is a kind of tuning configuration we have to set up based on our dataset.</p><h3>How to convert an image into a numerical representation to compare it with other images.</h3><p>When I was studying this stuff, the first question that came to my mind was: How can I convert an image like shown below into a number?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/1*hSATuPFeuu7-jFUSVST-SQ.jpeg" /><figcaption>The image of a seven.</figcaption></figure><h4>Raw image representation.</h4><p>Any computer file image is a set of bytes that represent pixels on the screen, and each pixel may be decomposed into four channels RGBA (RED, GREEN, BLUE, and ALPHA) depending on the image format. Of course, many other formats can have other representations, but let’s pick this one for sake of simplicity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*wq1QsI7wSX0v8BiFm6krzQ.jpeg" /><figcaption>Pixels and numbers together.</figcaption></figure><p>In the image above, we can see an image of a pixel matrix side by side with a hexadecimal representation of a computer image file. Then we conclude that any digital image file is by nature a set of numbers. But this format is not the best one for comparison purposes, we need to transform it.</p><h4>Transformations for performance improvement.</h4><p>As said before, an image computer file can have lots of information based on color vibrance and many other properties. All these image properties are good for enriching the picture, but we could recognize it even if it was a black and white image. So, let’s make our first transformation by discarding any color property to make it a small set of bytes. If you have any doubt about it, compare a B&amp;W image with a colorful image and you will see the difference.</p><p>The second transformation we can do is about the size of an image, if we have a large image, say 1000x1000 pixels, we can resize it to a small size and still recognize it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/32/1*nx8IMXQ3figGJCIz3nXI1A.jpeg" /><figcaption>The resized image.</figcaption></figure><p>If we put a magnifying glass on the number seven, we could see something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*syLI2uRJyJ5x0TCxwDDZiA.png" /><figcaption>The zoomed image.</figcaption></figure><p>It is still a number seven, right? As you can see it is a mono-color picture, how could we represent it in a simpler way to facilitate the format transportation over an API? A possible answer would be a linear matrix.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b08ae0086e596b072bcf74215ca21f9/href">https://medium.com/media/0b08ae0086e596b072bcf74215ca21f9/href</a></iframe><h4>Join the pieces again.</h4><p>So, with this representation format i.e. a linear integer matrix composed of zeroes and ones [0, 0, 0, 0, 0, 0, 1, 1, 1…], it is simpler to work in memory making comparisons and it is easy to transport it over REST API requests. We can compare it with other images representation in the same format to see if a new image is similar in any aspect with others because it is a numerical representation.</p><h3>A code is worth a thousand words</h3><p>Here I am going to share two projects that can help you understand better all concepts presented in this article. From my point of view, the best way to comprehend all this stuff is to inspect and debugging a functional project and see how it works.</p><p><a href="https://gitlab.com/mascate/grave">Mascate / Grave</a></p><h4>The grave project</h4><p>This is a web based rest api project developed in python for handwriting recognition, in the <strong>README.md</strong> has all information to build and run it.</p><p><strong><em>It has only handwriting numbers in its dataset, but you can teach it with letters as well, then you can use alphabet handwriting recognition.</em></strong></p><p><a href="https://gitlab.com/anderson.gusmao/lerobot">Anderson Santos Gusmão / Le Robot</a></p><h4>The Le Robot project</h4><p>This is an iOS application that allows users to draw characters on the canvas and it integrate with the Grave project.</p><h3>Final words</h3><p>Have fun with it. If you like it, you can thank me by sharing this with your colleagues and friends allowing this knowledge to reach more people. And sorry for my poor English.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e8b13e40df12" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Build and run a boot-loader]]></title>
            <link>https://andersongusmao.medium.com/build-and-run-a-boot-loader-561822fd4299?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/561822fd4299</guid>
            <category><![CDATA[boots]]></category>
            <category><![CDATA[bootloader]]></category>
            <category><![CDATA[operating-systems]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Sat, 12 Sep 2020 06:55:45 GMT</pubDate>
            <atom:updated>2020-09-17T01:15:36.297Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/504/1*gj5o90sXYNjjzwtyhGLmjQ@2x.png" /></figure><h4>Principles of computing and operating systems.</h4><h4>What to expect here.</h4><p>If you’re a curious guy like me, you’ve probably wondered how an operating system works. Here, I’ll share some research and practical experiments I’ve done to understand computing and operating systems better. After reading, you will create your bootable program that works in any virtual machine application like Virtual Box.</p><h4>Important note</h4><p>This article is not intended to explain everything about the boot loader with its complexities. This example is just a starting point based on the x86 architecture. It must be difficult reading for most people, which requires basic knowledge of microprocessors and computer programming.</p><h4>What is a bootloader?</h4><p>In simple words, a boot-loader is a piece of software loaded into a computer’s working memory after booting.</p><p>In more detail, after pressing the start button on a computer, many things must be done. Then, a firmware called BIOS (Basic Input Output System) kicks in and does its job. After that, the BIOS gives control to the boot loader installed on any available media, that is, USB, hard drive, CD drive, etc. The BIOS goes through the data media found in sequence, checking for a unique signature — the so-called boot signature (or ‘boot record’). When the boot record is found and loaded into the computer’s memory, the processor starts to function from that point. To be more precise, at address 0x7C00, save this memory address; this is important in building the boot loader.</p><h4>Work inside of the first sector with only 512 bytes.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G3Tdhi8VBfVE8z3pz3GJRA.png" /><figcaption>Figure 01 — MBR (Master boot record) — The first sector is where boot-loader must be</figcaption></figure><p>During the BIOS initialization process, the BIOS looks in the bootable devices’ first sector for a single signature, as mentioned before. This unique value is 0xAA55 and must be in the last two bytes of the first sector. Despite 512 bytes available in the master boot record, we cannot use all of them; we need to subtract the partition table schema and signature, and only 440 bytes remain. It doesn’t seem like good memory space, but you can write code to load more data from other sectors into memory and solve the problem</p><h4>The initialization steps in a simplified way</h4><ul><li>The BIOS boots computers and their peripherals;</li><li>The BIOS searches for bootable devices;</li><li>When the BIOS finds the signature 0xAA55 in the MBR (master boot record), it loads that sector into memory at position 0x7C00 and gives control to this entry point, that is, it starts executing instructions from this point 0x7C00 in memory ;</li></ul><h4>Let’s start coding</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6aad8bdacb4935e66de39a9c7f80a176/href">https://medium.com/media/6aad8bdacb4935e66de39a9c7f80a176/href</a></iframe><p>As you can imagine, this is assembly language and needs to be compiled into machine code with an assembly compiler to generate machine code, as you can see in the next block of code. Note that 512 in hexadecimal notation is 0x200 and the last two bytes are 0x55 and 0xAA; it is inverted compared to the assembly code above; this is related to the storage ordering system known as endianness. For example, in a big-endian system, the two bytes required for the hexadecimal number 0x55AA would be stored as 0x55AA in storage (if 55 is kept at storage address 0x1FE, AA will be at address 0x1FF). On a little endian system, it would be stored as 0xAA55 (AA at address 0x1FE, 55 at 0x1FF).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3006e417f7fff26d9ec3acb40b08b89/href">https://medium.com/media/a3006e417f7fff26d9ec3acb40b08b89/href</a></iframe><h4>How this code works</h4><p>I will explain this code line by line in case you are not familiar with assembly language.</p><p>1-) Specifying target processor mode, this BITS directive specifies whether NASM should generate code designed to run on a processor operating in 16-bit mode, 32-bit mode, or 64-bit mode. The syntax is BITS XX, where XX is 16, 32, or 64.</p><p>2-) Specifying the binary file program origin, this ORG directive is to specify the origin address, which NASM will assume the program begins at when it is loaded into memory. When this code is translated to machine code, the compiler and linker will determine and organize all data structures needed by the program; this reference address will be used for this purpose.</p><p>3-) This is just a label; when defined in code, it refers to a memory position you can point to; it is used together with jump instructions to control the application’s flow; This idea will make more sense in the next line.<br>After explaining the fourth line, we need to describe the concept of registers:</p><blockquote><em>A processor </em><strong><em>register</em></strong><em> is a quickly accessible location available to a computer’s processor. </em><strong><em>Registers</em></strong><em> usually consist of a small amount of fast storage, although some registers have specific hardware functions and may be read-only or write-only. In computer architecture, registers are typically addressed by mechanisms other than main memory but may, in some cases, be assigned a memory address. This definition was extracted from Wikipedia.</em></blockquote><p>4-) Assigning data with <strong>MOV</strong> instruction, this instruction is used to move data; in this case, we are moving the value of the memory address of the label <strong>message</strong> to the <strong>SI</strong> register; Which will point to the text <em>“Hey! This code is my boot loader operating.”</em>. If you look in the image below, you will see that this text is stored at poison <strong>0x7C10</strong> when translated to machine code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7P1ZuUNptWTFf-UPm8l_Bw.png" /><figcaption>Figure 02 - Binary file disasembled by IDA software.</figcaption></figure><p>5-) We will use the BIOS video services to display the text on the screen, so we are settings how we want this work. It moves the byte 0x0E to the register AH.</p><p>6-) Another label reference that allows controlling the execution flow, later we will use it to create a loop.</p><p>7-) This instruction loads a byte from the source operand into the AL register. Remember the fourth line, in which the SI was set with a text address position; now, this instruction is getting the character stored at memory space 0x7C10. It is vital to notice this is behaving like an array, and we are point to the first position, which contains the character ‘H’; as we can see in figure 03 below. This text presentation will occur in a vertically iterative manner, and each character will be set each time. Besides, the second character was not presented extracted snapshot from the IDA program; 0x65 in ASCII represents the character ‘e’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*Gm9r9_6iqU_bbTLWptJnBg.png" /><figcaption>Figure 03 — Array of characters between 0x7C10 until 0x7C3B.</figcaption></figure><p>8-) Performing <strong>OR</strong> boolean operation between (<strong>AL</strong> | <strong>AL</strong>), at first glance, it does not seem to make any sense, but it does. We need to check if the result of this operation is zero, based on logic boolean, the result will be the same after this operation, for example, [1 | 1 = 1] or [0 | 0 = 0]. In the next line, you are going to understand why this is necessary.</p><p>9-) Jump to <strong>halt label</strong> <strong>(Line 12)</strong> if the result of the last <strong>OR</strong> operation is zero, in the first moment, the value of <strong>AL is [0x48 = ‘H’]</strong> based in the last <strong>LODSB</strong> instruction, do you remember that on Line 7? So, it will not jump to <strong>halt label</strong> in the first moment. Why that? (0x48 OR 0x48) = 0x48, then it will go to the next instruction in the next line. It is important to say that <strong>JZ</strong> instruction is not related only to <strong>OR</strong> instruction. There is another register called <strong>FLAGS</strong>, which is observed during jump operations, i.e., the result of <strong>OR</strong> operation is stored in this FLAG register and observed by <strong>JZ</strong> instruction.</p><p>10 -) Invoking <strong>BIOS</strong> interruption, the instruction <strong>INT 0x10</strong> displays the value of <strong>AL</strong> on the screen; remember line 5, we set the value of <strong>AH</strong> with <strong>0x0E</strong>; this is a combination to present the value of <strong>AL </strong>on the screen.</p><p>11-) Jump to <strong>.loop labe</strong>l, that’s it without any condition, it is like <strong>GOTO</strong> instruction compared to a high-level language.</p><p>12-) We are in line 7 more one time, <strong>LODSB</strong> will retake action. After the byte is transferred from the memory location into the <strong>AL</strong> register, the <strong>SI</strong> register is incremented. The second time, it is pointing to the address <strong>0x7C11 = [0x65 ‘e’]</strong>, then the character ‘e’ is presented on the screen. This loop will run until it reaches the address <strong>0x7C3B = [0x00 0]</strong>, and when the <strong>JZ</strong> is executed again on line 9, the flow will be driven to the <strong>halt label</strong>.</p><p>13-) Here, we finish our journey. The CLI and HLT instructions halt the execution.</p><p>14-) At the seventeenth line you see an instruction that pads the remaining 510 bytes with zeroes after that adds the boot record signature 0xAA55.</p><h4>Let’s build and run</h4><p>In the first step, you must make sure you have installed the NASM compiler and QEMU on your computer, using your favorite dependency manager or downloading it from the internet; QEMU is a virtual machine emulator.</p><p>If you have Linux, you can type on terminal:</p><pre>sudo apt-get install nasm qemu</pre><p>On a mac you can use homebrew:</p><pre>brew install nasm qemu</pre><p>After accomplishing the first step, you must create a file with the assembly code presented in <strong>Code 01 block</strong>. Let’s name this file as <strong>boot.asm</strong> and then run NASM command:</p><pre>nasm -f bin boot.asm -o boot.bin</pre><p>It will produce the binary file you need to run your virtual machine, let’s run it on QEMU:</p><pre>qemu-system-x86_64 -fda boot.bin</pre><p>You should see the following screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/753/1*sgk1YY8G25N6RwDEYOwhJg.png" /><figcaption>Figure 04 — Running the boot-loader with QEMU.</figcaption></figure><h4>Running it from Virtual box</h4><p>Firstly you need to create a virtual an empty floppy disk</p><pre>dd if=/dev/zero bs=1024 count=0 &gt; floppy.img</pre><p>And then append the binary content inside of it:</p><pre>cat boot.bin &gt;&gt; floppy.img</pre><p>Now you can create a Virtual Box machine and boot it using your image file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0qBpBc8w0ddfKW0UvxIBgg.png" /><figcaption>Figure 05 — Running the boot-loader with Virtual Box.</figcaption></figure><p>I was not able to explain many things here for the sake of brevity; if this is your first time with this type of content, probably many questions have arisen in your head, ok, this is not an easy subject, and I hope it can serve as a starting point for many studies. A book that I recommend is Operating Systems Design and Implementation by Andrew S. Tanenbaum, a useful reference to better understand many principles of computing and operating systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=561822fd4299" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Shifting traffic with AWS Lambda function.]]></title>
            <link>https://andersongusmao.medium.com/shifting-traffic-with-aws-lambda-function-7067b3f36641?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/7067b3f36641</guid>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 23:49:42 GMT</pubDate>
            <atom:updated>2020-09-09T23:49:42.258Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to distribute processing over different versions of your AWS Lambda functions.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FfUVzdD0-cgKNsG4UJuE1w.jpeg" /></figure><h3>Initial assumption</h3><p>The content presented by this article assumes that you have basic knowledge of what is AWS Lambda functions and how to use it. So, we are going to start with this assumption in mind. If it is not the case, please take a look at <a href="https://aws.amazon.com/lambda/">AWS documentation</a> before reading this article.</p><h3>Versioning and shifting traffic feature.</h3><p>Recently, I figured out an interesting feature of AWS Lambda functions, it is possible to create different versions of your function and then allow it to shift traffic between two versions, based on weights (%) that you assign to it.</p><p>I could imagine a lot of scenarios that I can use it in the real life, but for studying purposes, I created a lambda function to sort an array and I picked some sort algorithms to see how those different algorithms would perform on AWS Lambda applying the same input values and shifting traffic between them in 50/50.</p><p>In the image below you can see the result that I got in the <strong>AWS Cloud Watch</strong> dashboard comparing (1) bubble sort versus (3) merge sort.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*YtsKBHmA-mUamHDBqtMHXw.png" /><figcaption>(1) Bubble Sort VS (3) Merge Sort</figcaption></figure><p>There would be a lot of other usages for it and we could extract some metrics to evaluate which version is better than other based on those metrics, such as duration time, memory allocation, error count, success rate and so on.</p><h3>How to do it.</h3><p>It is very simple to configure it, I will describe it here step by step:</p><ul><li>Step 1 — Create your lamdba function;</li><li>Step 2 — Add your code into it;</li><li>Step 3 — Publish a new version of it clicking on <strong>ACTION MENU</strong>;</li><li>Step 4 — Change something in your code based in the <strong>$LATEST</strong> version and then publish a new version of it;</li><li>Step 5 — Now you have two version you can create an ALIAS in the <strong>ACTION MENU</strong>,</li></ul><p>In the image bellow you can see how to distribute weights over your versions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wkh5dIl1jT7bs_CBOxr12g.png" /><figcaption>Creating an ALIAS</figcaption></figure><p>After this step, you will have a new ARN, something like that:</p><blockquote>arn:aws:lambda:us-east-1:XXXXXXXXX:function:sort:split</blockquote><p>Now, you need just to associate it with your trigger and start to use it.</p><h3>Conclusion</h3><p>There are many situations where we are not sure about the results we are going to have by using different approaches, with this feature we can make experiments and see over metrics how our code is going on. Furthermore, we can minimize risks by shifting traffic proportionally and check if your code is working properly.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7067b3f36641" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple chat app using WebSocket.]]></title>
            <link>https://andersongusmao.medium.com/a-simple-chat-app-using-websocket-80bb6b9fdd1?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bb6b9fdd1</guid>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 23:49:13 GMT</pubDate>
            <atom:updated>2020-09-09T23:49:13.825Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to consume WebSocket API&#39;s in Swift.</h4><figure><img alt="WebSocket ilustration from medium article." src="https://cdn-images-1.medium.com/max/1024/1*WFaceQwtwiNewZOVMGgTwQ.png" /></figure><h3>Before read all the stuff.</h3><p>Here we are going to present three things:</p><ul><li>The basic concept behind WebSockets;</li><li>The new WebSocket API in iOS 13;</li><li>A simple chat sample using AWS resources and WebSocket on iOS;</li></ul><p>I hope you can have fun reading and learn something new. Let’s get started.</p><h3>What is WebSockets?</h3><p>If you are wondering what is web socket protocol, we can simply define it as a way to provide bi-directional communication between devices, <em>i.e.</em> a full-duplex channel. To make clearer why it is different, let’s compare it when we have peers connected under conventional HTTP protocol, the communication works like that:</p><ul><li>The client connects to the server to make a request;</li><li>The server processes the client’s request and responds;</li><li>The client and server get disconnected;</li></ul><p>If the client needs any update from the server, it should establish a new connection into the server again, as you can imagine, in the HTTP connection model we are disconnected most of the time from the server, at least from the client perspective. In a situation that we need real-time communication, we look for alternatives such as <strong>“Pooling”</strong>, a technique largely used to create the sensation of real-time communication, <em>i.e.</em> the client from time to time asks for updates to the server. It is inefficient because:</p><ul><li>Even the server has nothing to say, the client keeps asking for it unnecessarily;</li><li>It generates an extra overhead to the server, each new device connected will increase a lot the number of requests per minutes/hour;</li><li>User’s bandwidth wasted;</li><li>We do not have a real-time communication, and it is necessary to determine the minimum time for pooling, the longer is this time, the real-time sensation is compromised and the shorter is this time, more inefficient it becomes;</li></ul><p>The WebSocket concept came to solve the above-mentioned issues with lower overhead than half-duplex alternatives such as HTTP polling. This is made possible by providing a way for the server to send content to the client without being first requested by the client, and allowing messages to be passed back and forth while keeping the connection open. In this model, a two-way ongoing conversation can take place between the devices.</p><h3>WebSocket as a first-class citizen.</h3><p>In 2019, Apple announced at WWDC a new WebSockets API in the presentation “<a href="https://developer.apple.com/videos/play/wwdc2019/712/">Advances in Networking, Part 1</a>”, take a look, I recommend it. The great news is: Websockets in iOS 13, macOS 10.15, tvOS 13, watchOS 6, and Mac Catalyst have gained first-class citizen status in the networking stack, it is part of Foundation API and it works with existing URLSession. Up to now there are small quirks and rough edges, for instance, the <strong>receive</strong> method reads a WebSocket message once, it means that when we receive a message, we need to call it over and over again. Besides this issue, you don’t need to mess with constructing a Websocket frame anymore, which is a big advantage. Previously, if you wanted to use WebSockets you had to rely on CFNetwork, which implicates with pointers and memory allocation common in C language or you had to rely on Third-Party libraries to make the dirty job to you.</p><h3>About the simple chat app.</h3><p>Nothing is better than have a more practical vision and understand how it works with a real application. I created a simple iOS app application that you can take a look at the link below. The source code tell us how it works by itself, in the next session, I will provide some tips how to run it by yourself and the main points of WebSocket usage:</p><p><a href="https://github.com/anderson-gusmao/hanashi">anderson-gusmao/hanashi</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*9jZ9S4HubCs79SKuUoPJoA.gif" /></figure><h3>How it works.</h3><h4>We need a server application to centralize connections.</h4><p>It means we need to connect to a server that is responsible to manage all connections with devices. To simplify this part, I rely on the following Github project:</p><p><a href="https://github.com/aws-samples/simple-websockets-chat-app">aws-samples/simple-websockets-chat-app</a></p><p>In using <a href="https://github.com/aws-samples/simple-websockets-chat-app"><strong>simple-websockets-chat-app</strong></a> project from AWS Samples repository, we have all the server infrastructure we need, in this way, we can be focused on the app perspective and abstract all server implementation details. If you are not familiar with AWS cloud computing it can be a small challenge, but I encourage you to go beyond and start learning it. For this, you will need the following things:</p><ul><li>An AWS account;</li><li>To have AWS client tool installed in your machine, i.e. <a href="https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/serverless-sam-cli-install.html">AWS SAM CLI</a>;</li><li>Clone the <a href="https://github.com/aws-samples/simple-websockets-chat-app"><strong>simple-websockets-chat-app</strong></a><strong> </strong>project locally in your machine and run the deployment commands, the instructions are there at the link above:</li></ul><p><strong>Important disclaimer:</strong></p><blockquote><em>All resources used by this sample are eligible in AWS Free Tier which provides customers the ability to explore and try out AWS services free of charge up to specified limits for each service, so you do not need to be concerned in being charged if you do not exceed these limits.</em></blockquote><h4>After deploying all server infrastructure on AWS.</h4><p>We need the URL to consume the API, you will find it on the API Gateway service section on the AWS Web console. The scripts of <a href="https://github.com/aws-samples/simple-websockets-chat-app"><strong>simple-websockets-chat-app</strong></a><strong> </strong>project<strong> </strong>will create an API Gateway called <strong>SimpleChatWebSocket</strong>, open this API instance and go to <strong>Stage</strong> configurations section, there you see the URL, something like that:</p><blockquote>wss://xxxxxxxxxx.execute-api.us-east-1.amazonaws.com/Prod</blockquote><p>After testing it, it is recommended to destroy all provisioned resources if you do not plan to use anymore, run the following command to do that:</p><blockquote>aws cloudformation delete-stack — stack-name simple-websocket-chat-app</blockquote><h4>Here we are good to go to iOS app implementation details.</h4><p>This is the presentation layout of the app:</p><figure><img alt="A simple chat app using WebSocket" src="https://cdn-images-1.medium.com/max/375/1*GNybYdmC3iqKMLdKfbG43A.png" /><figcaption>App interface.</figcaption></figure><p>To consume our WebSocket API, we need to create an instance of <strong>URLSessionWebSocketTask</strong> which is responsible for everything. The first step is to connect into API and it is done like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2aba353e2a27670895dcaa7c52396c4/href">https://medium.com/media/b2aba353e2a27670895dcaa7c52396c4/href</a></iframe><p>After that, if nothing goes wrong, we are good to send and receive messages from the <strong>URLSessionWebSocketTask </strong>instance, to send messages we need to call the send method like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/052256466af2812871026e31ebc03139/href">https://medium.com/media/052256466af2812871026e31ebc03139/href</a></iframe><p>You can provide your message in String or Data format, the content of the message is based in your definition, for this chat application we are sending a JSON payload with two properties and it is embedded inside <strong>Message.string</strong> enum.</p><p>To receive messages we need to invoke the <strong>receive</strong> method passing a closure as a parameter into it, take a look:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74598a76e33c9a423cec428685a8c066/href">https://medium.com/media/74598a76e33c9a423cec428685a8c066/href</a></iframe><p>The weird thing here is that it works once as described in <a href="https://developer.apple.com/documentation/foundation/urlsessionwebsockettask">Apple documentation</a>, so, to keep it receiving messages continuously, we need recall it recursively, but it does not mean we are reconnecting or something like that, it is just the way this new class was designed, besides of its weirdness, it works fine.</p><h4>Other functions.</h4><p>To keep the connection open for a long term, it is always a good thing from time to time to say to the other part you are alive and expecting for new income messages, for this purpose we have a method called the <strong>sendPing </strong>method<strong>. </strong>If you want to be disconnected, just call the <strong>cancel</strong> method in <strong>URLSessionWebSocketTask </strong>instance.</p><h3>Conclusion.</h3><p>Like everything in life, nothing comes to solve all issues in our life, there are lots of real scenarios that WebSockets fits well and we can have it in our favor. Real-time communications can take place of these advantages, mainly the above optimization perspective.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bb6b9fdd1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Optional extensions]]></title>
            <link>https://andersongusmao.medium.com/optional-extensions-93e1f65dc85b?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/93e1f65dc85b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[optional-extensions]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Fri, 17 Aug 2018 22:54:06 GMT</pubDate>
            <atom:updated>2018-08-17T22:54:06.485Z</atom:updated>
            <content:encoded><![CDATA[<p>Is it empty or nil?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4PZYeWbSVXavHR2tm0Ii3A.jpeg" /></figure><p>You know that extensions are a marvelous thing on swift, but it is much better when we can use it with a meaning. So today I would like to share something I learned, and I like so much, sometimes we need to check if a string is empty or nil at the same time, and we have some approaches to do this, such as:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9e95537ae36719baecbdecbb8870978/href">https://medium.com/media/a9e95537ae36719baecbdecbb8870978/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/579fbfea990d94ccc48c93f3b1ffd0f1/href">https://medium.com/media/579fbfea990d94ccc48c93f3b1ffd0f1/href</a></iframe><h3>How about this?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e40f1a432ffeadb75e63b81917729207/href">https://medium.com/media/e40f1a432ffeadb75e63b81917729207/href</a></iframe><p>Did you like it? Unfortunately, it is not a native property of String type, but it easy to add it, look this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/460745d7c39ba194384bd1ff36bf3b2c/href">https://medium.com/media/460745d7c39ba194384bd1ff36bf3b2c/href</a></iframe><p>It is checking optionals related to Collection type and verifies if it is nil and returns true, otherwise it checks its native property “isEmpty”, it is simple, right? I hope it helps you to provide a clean and more readable code. Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=93e1f65dc85b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generic table view controller]]></title>
            <link>https://andersongusmao.medium.com/generic-table-view-controller-b7b065c45ee?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7b065c45ee</guid>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[tableviews]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Sat, 28 Apr 2018 21:37:09 GMT</pubDate>
            <atom:updated>2018-05-25T01:43:39.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>A reusing approach for table view controller.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*LVasoJc8Vh-xWUNI3TwoYQ.png" /><figcaption>Navigation flow</figcaption></figure><h3>Getting started</h3><p>Hey folks! Today we are going to talk about generic things, take a look at the image above. What do you see? A simple iOS application navigation flow that presents some screens. What do they have in common? At first glance, we can observe four screens built on TableViewController, right? Do you agree? Probably the most intuitive way would be building five view controllers to accomplish this app, but I would like to share an approach that we are going to use just two. One for a generic table view controller used in all list screens and another to display a not found screen, this second view controller was built only to prove a concept that you can integrate another kind of view controllers with the concept that we are going to show here. Get the complete code on GitHub at the final of the article.</p><h4>What does change?</h4><p>If you take a look, indeed you are going to notice that the cells are the things that change in these table view screens. So, we can reuse the table view as a generic component and customize any cell we want.</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*eXqWXWQ5vqxgRs5LLBc-CQ.png" /><figcaption>Components</figcaption></figure><h3>Generic table view controller</h3><p>To achieve this goal using storyboard I think is very hard, I would not say impossible, but I spent much time, and I could not figure out an elegant solution, mostly because of the generic type we must inform into generic view controller and the way the storyboard instantiates does not favor that. So it is a complicated subject, and of course, there are pros and cons, if you want to read more about it I wrote a post talking about this subject on the link below:</p><p><a href="https://medium.com/@andersongusmao/what-layout-programmatically-are-you-crazy-why-should-i-do-this-c03ee095bfd6">What? Layout programmatically? Are you crazy? Why should I do this?</a></p><p>So, to achieve this goal I used a programmatically view controller, take a look below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47f32dc4aeaba8af62a194f8a1579d0b/href">https://medium.com/media/47f32dc4aeaba8af62a194f8a1579d0b/href</a></iframe><p>The code above has all we need to perform a table view controller presentation, and it has (cellForAt) method, numberOfRowsInSection and didSelectRowAt methods implemented. Notice the generic type inferred by the constructor, this generic type has a constraint, and it must conform the protocol DescriptiveProtocol to provide a way to bind UITableViewCell for each item on (cellForAt) method. So, in this way, each element from data source must inform which cell type must be returned by reusable dequeue method from the table view. Here is the trick, the generic table view <strong>does not know anything</strong> about the cells, then it can be used for all of them.</p><h3>The descriptor</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e0f91bdf2b3be532b67c159eeb944b5/href">https://medium.com/media/0e0f91bdf2b3be532b67c159eeb944b5/href</a></iframe><p>The descriptor object is responsible for holding the cell type, reuse identifier and the closure that must be called to configure cell.</p><h3>The model</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14feee3d1fe3043f6b147e1d0d38495f/href">https://medium.com/media/14feee3d1fe3043f6b147e1d0d38495f/href</a></iframe><p>As you can see, this struct conforms DescriptiveProtocol, and it has a property called descriptor, as mentioned above it has the responsibility to bind it into UIViewTableCell specialization, at this moment the cell type is informed when table view cellForAt method is called.</p><h3>Conclusion and the souce code</h3><p>The remaining code is self-explanatory, I think it is not a silver bullet, but can help someone in some specific context, feel free to comment if you have something to say about it. Bye and see you next time.</p><p><a href="https://github.com/heuristisk/hkImperatorMensa">heuristisk/hkImperatorMensa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7b065c45ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What? Make layout programmatically? Are you crazy? Why should I do this?]]></title>
            <link>https://andersongusmao.medium.com/what-layout-programmatically-are-you-crazy-why-should-i-do-this-c03ee095bfd6?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/c03ee095bfd6</guid>
            <category><![CDATA[layout-programmatically]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Fri, 13 Apr 2018 03:18:27 GMT</pubDate>
            <atom:updated>2018-05-25T01:59:07.755Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eiTkY0C8ZUeqfYjQKyDn-A.jpeg" /></figure><p>When I heard it for the first time, I confess it sounded weird to me. A smart coworker suggested it to me, and I thought, “this is certainly a waste of time, because Xcode provides me many facilities”, “Why would I want to increase the complexity of my project?” Other questions came up to my mind. Later, I studied more the subject, and I got interested in software architecture, so I realized that these Xcode facilities come with a price. During this time when I was thinking about the subject, I was invited by Facebook to participate in a hiring process, and I was not hired, of course, but I found out that Instagram team do not use storyboards, at least the interviewer told me that. I wondered why do they do this in that way? They are facebook company, and surely they have a good reason. The advantages you have to use storyboard is clear, and we do not need to say. On the other hand, the price you pay is not so bright than storyboard facilities. Here I am going to propose some advantages of this approach, I mean, layout programmatically and I am going to share a simple, pure swift project for you have some idea how it is developed. My bits of advice are, look the number of lines of each class, look how responsibility distribution, look at the perspective of dependency injection and so on.</p><h3>What I think about disadvantages</h3><ul><li>Spending more time to develop;</li><li>Sometimes this could be more complex to organize teams to work together;</li></ul><h3>What I think about advantages</h3><ul><li>More flexibility to inject the dependency, you must create your class initializers, you define how it will be the input parameters of your view controller for example;</li><li>More accessible to track changes on the code, I mean, the code is more descriptive than storyboard XML file;</li><li>Great to decouple and make it testable, and talking about decoupling, you can create your main view, taking out presentation logic from view controllers, what is hard to do with storyboards. To sum up the separation of concerns;</li><li>Easier to make reusable components, I mean, you need to think in this way;</li><li>Great style and shortcode;</li><li>Have the opportunity to know better how things work behind the scenes, UIKit, Constraint and so on;</li></ul><h3>Conclusions</h3><p>It took some time, for me realizing about advantages and disadvantages. What do you think? Please contribute here and leave your comment. Do not forget to take a look at the sample below, bye and I&#39;ll see you next time.</p><p><a href="https://github.com/heuristisk/screex">heuristisk/screex</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c03ee095bfd6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Encapsulating the Auto Scroll Positioning Logic Inside UIScrollView]]></title>
            <link>https://andersongusmao.medium.com/encapsulating-the-auto-scroll-positioning-logic-inside-uiscrollview-83cde3a84f03?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/83cde3a84f03</guid>
            <category><![CDATA[uiscrollview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Sun, 25 Mar 2018 21:17:11 GMT</pubDate>
            <atom:updated>2018-03-25T21:17:11.411Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*IQQ5IfOl26s-sUUE0vPpIw.gif" /></figure><p>In some projects that I helped to develop, sometimes I needed to control the UITextField positioning on the screen, mainly when using a large and scrollable screen.</p><p>I never liked the results, because I was putting a lot of logic inside my view controllers, and I always thought that the logical part should not be there. So, I thought of a way to achieve this, and now I think that I have a better solution.</p><p>I built a new class that extends from UIScrollView. Inside this class, we have all the logic instructions, ready to detect when the keyboard calls for activity, and then it controls the content in a previously set distance from the bottom.</p><p>For applying this solution in our own project, the only task you need to do is to copy and paste the class into the project. On Xcode Identity inspector you must use the custom class called “KeyboardScrollView”.</p><p>It is easy and functional. I exploit a property called “Extra Bottom Space” as an IBInspectable, in order to allow programmers to set some bottom adjustment space on IDE.</p><p>An improvement that might be done in the future is to detect automatically the keyboard accessory space. In this version I have not considered that enhancement. So, the logic will fail if applying keyboard accessories of different sizes, but with the same keyboard size, my software will work as intended.</p><h4>Implementation</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac2c5aa3c672e7e71669f721ebdfdc9d/href">https://medium.com/media/ac2c5aa3c672e7e71669f721ebdfdc9d/href</a></iframe><h4>A demo project</h4><p><a href="https://github.com/heuristisk/MagicKeyboard">heuristisk/MagicKeyboard</a></p><p>I hope it helps you, any comments or suggestions are welcome.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83cde3a84f03" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Certificate pinning technique on iOS]]></title>
            <link>https://andersongusmao.medium.com/certificate-pinning-technique-on-ios-af0f0813e88?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/af0f0813e88</guid>
            <category><![CDATA[pinning]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ssl-certificate]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 01:34:01 GMT</pubDate>
            <atom:updated>2017-10-10T12:42:51.103Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using swift</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jyo0QkiqaZ6jl0EuoSQktA.png" /></figure><p>Hi, folks! Today we are going to talk about security. To completely comprehend these concepts presented here I need to provide some background knowledge about how SSL/TLS works and other stuff. Of course, it is not a deep dive, it is just a simple explanation before starting the main subject, if you already know it, it is ok, just step out this part and go to next section. At the final we are going to see a practical example of how to do certificate pinning on a iOS project, let’s go!</p><h3>Part 1 — SSL/TLS at a glance</h3><h4>What is it?</h4><p>SSL/TLS ensures transparently encryption on client-server communication over HTTPS, i.e (HTTP over SSL/TLS). The encryption is based on Public Key Infrastructure (PKI for short). It is transparent because the application layer knows nothing about this encryption process, the network infrastructure takes care of everything, as programmers we just compose our application requests putting our headers and bodies with plain-text inside requisitions and the network infrastructure does all the job for us.</p><h4>Handshake</h4><p>Before sending any application data, the server and client negotiate about how to encrypt/decrypt data, this process is called handshake, in the image below you can see a simplified view about this process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*X_1z5WGqjcyWjBS4BQaEGQ.gif" /><figcaption>SSL Handshake process (Simplified view from Google images)</figcaption></figure><h4>After handshaking</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*G5Ex2Xki9h5VMD7tgOEM_w.jpeg" /><figcaption>Encrypted data (Image from Google images)</figcaption></figure><p>At this moment, if anyone tries to inspect the messages exchanged between client and server on data transportation, nothing will be human-readable, all traffic is encrypted on transit, i.e, it is just deciphered on the client and server perspective.</p><h4>Certificate validation process</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uOAIAxJnG8G7EzVsZNxY0g.png" /><figcaption>Certificate warning (Image from Google images)</figcaption></figure><p>During the handshake process, the server presents a digital certificate and the client needs to trust in the certificate issuer, based on a predefined trust certification authorities list, a. k. a. trusted root CA store. On a secure connection, if the presented certificate was issued by an unknown issuer, generally browsers shows a warning ⚠️ for the user to decide if he or she must proceed with the connection or not. This behavior on apps is different by default, where the connection is interrupted. It is possible you set as trusted a self-signed certificate on your device, in this case, the client will trust in this certificate in the subsequent connections.</p><h4>Man in the middle attack</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/587/1*ekx1FKEYvwzreZQOcV1BMg.jpeg" /><figcaption>Man in the middle attack (Image from Imperva, Inc)</figcaption></figure><p>What would happen if instead of connecting to the original server, your connection passes through another server faking as an original server? See a brief description of what is a man in the middle attack from <a href="https://www.incapsula.com/web-application-security/man-in-the-middle-mitm.html">Imperva Incapsula web site</a>.</p><blockquote>A man in the middle (MITM) attack is a general term for when a perpetrator positions himself in a conversation between a user and an application — either to eavesdrop or to impersonate one of the parties, making it appear as if a normal exchange of information is underway.</blockquote><p>In this situation someone can see all traffic and all information can be captured by an attacker.</p><h3>Part 2 — Certificate pinning</h3><h4>What is it?</h4><p>With the above background presented we can better understand what certificate pinning is. As we know, during the handshake 🤝 process, the server will present a certificate that must be trusted or not by the client. The certificate pinning technique consists in to save the target’s server certificate within the app bundle and trust just and only in it.</p><h4>Our example</h4><p>Let’s see a practical source code, for this purpose I created a stub authenticate rest service published on <a href="https://www.heroku.com/">Heroku</a> and a client iOS project.</p><p><strong><em>At the moment of this publication, the generated certificate is not expired and the service is up. Of course, I cannot guarantee this over time, but if you understand the concept correctly, you can change the certificate and hostname to reach your own service successfully.</em></strong></p><p>In our example we are going to reach the following URL <a href="https://floating-stream-25740.herokuapp.com/authentication/login">https://floating-stream-25740.herokuapp.com/authentication/login</a> using a post method to submit the request shown below:</p><blockquote>POST /authentication/login HTTP/1.1<br>Host: floating-stream-25740.herokuapp.com<br>Content-Type: application/x-www-form-urlencoded<br>Cache-Control: no-cache</blockquote><blockquote>id=user&amp;password=pass</blockquote><p>The id or password informed does not matter, it was created only for test. The output always will be:</p><blockquote>{<br> “Id”: “user”,<br> “name”: “Sergio Mallandro”,<br> “preferences”: [“XPTO”,“XPTA”,“XPTZ” ]<br>}</blockquote><h4>Necessary tools</h4><p>For testing purposes, we are going to need some web debugger to act as a proxy to simulate the man in the middle attack. For Mac users like us, I suggest two options, <a href="https://www.charlesproxy.com/">Charles Web Debugging proxy application</a> or <a href="https://portswigger.net/burp">Burp</a>. Both are commercial solutions, but you can get a trial or free edition. In case you are running Windows on another machine you can get <a href="http://www.telerik.com/fiddler">Fiddler</a> which is an excellent free option.</p><h4>Client Sample project</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/1*Ao2sK80G-MLq6eE8CrGCEQ.png" /><figcaption>Sample project</figcaption></figure><p>Our client application is published on GitHub at:</p><p><a href="https://github.com/heuristisk/hkPraesidium">heuristisk/hkPraesidium</a></p><h4>Where the things happen</h4><p>The project is very simple, it is just one view controller class calling another API class to make a request in order to put its result on a TextView control. To simplify I put here the part of the code where is the pinning logic, basically, we have a URLSession making our request and the API class implement URLSessionDelegate to treat urlSession method. Inside urlSession method we have the logic to compare the remote certificate with the local certificate, if the code gets some divergence, the request operation will be canceled.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb47afd2241c2e3de0bb8fb03a01389d/href">https://medium.com/media/eb47afd2241c2e3de0bb8fb03a01389d/href</a></iframe><h4>How to test it (Using Charles Web Debugging Proxy)</h4><p>The first thing to do is run the Charles Proxy, when you open it for the first time, it will ask you some administrative rights in order to set up your networking configuration when it is running. So when you open it, automatically your proxy settings will be changed to drive your network traffic via Charles, you can check it on your setting as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RBkPiuu2GrKZiIdPbRiYvQ.png" /><figcaption>Proxy settings</figcaption></figure><p>Now if you open your iOS simulator and try to connect on any site via safari or if you run the sample project presented here, you will see the request and response as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8_P-LX9UeMpI_nBFal2Jcw.png" /></figure><p>If it is a secure connection, nothing can be read because SSL/TLS protection.</p><p>Now try to enable the SSL Proxying:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C-OlDZo_pNcx4sIRXjc20w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mkJjunGgjgAOkOa7gL1_mg.png" /></figure><p>Oops! The connection has failed! Why? The Charles presented a self-signed certificate instead of the original certificate, in this case when Charles application receives a connection request, it tries to act as the original server from the client perspective and make a new request to the original server. When the original server replies the response, it is replied to the client as if it was the original request, but this certificate presented by Charles is not trustable, we need to make the client trust in it to simulate our man in the middle attack. <br>It can be done as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XVlLZnYYQq2FNpRqNuSPrQ.png" /></figure><p>After that, you need to enable full trust for this certificate, if you need to test it on a real device, you can export it and install manually. After that, you need to reset the simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*FX0xUrtm1R9wuwBb9zG_MA.png" /><figcaption>Enabling Charles Certificate</figcaption></figure><p>Now, if you try to connect you will see everything on Charles as if it was a simple HTTP connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-gWxt2MFbFVW30Qki9JXig.png" /></figure><p>But, if you enable certification pinning, our logic will compare the embedded certificate with the presented Charles certificate, so the connection will be canceled as shown in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*vErBS_dodsP-l5LSX76yZg.png" /></figure><h3>Conclusion</h3><p>The advantage of this approach restricts the number of signing authorities trusted by your client application, CAs have had several prominent security breaches where signing keys were compromised or where overly permissive certificates were issued. These breaches allow anyone in possession of the signing key to impersonate any SSL/TLS server, meaning they can successfully and transparently read or modify requests to the server and their responses. Another advantage is that your app will not expose your API contract through proxies applications such as Charles. As a disadvantage, your app will stop to work when the server certificate changes, in this case, you need to update your app.</p><p>I hope it helps you understand certificate pinning technique, if something is not clear, please comment here, perhaps I can help you and improve this article. I see you again in the future, bye! 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=af0f0813e88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xcode “Targets” with multiple build configurations]]></title>
            <link>https://andersongusmao.medium.com/xcode-targets-with-multiples-build-configuration-90a575ddc687?source=rss-579b41f847e9------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a575ddc687</guid>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[multiple-environment]]></category>
            <category><![CDATA[target]]></category>
            <category><![CDATA[build-configuration]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Anderson Santos Gusmão]]></dc:creator>
            <pubDate>Sat, 16 Sep 2017 19:28:06 GMT</pubDate>
            <atom:updated>2017-09-18T02:10:15.687Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to create multiple applications that differentiate and share parts of the source code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EwEFWpEEo4dRkxf7uT4JUg.png" /></figure><h3>Why do I need this?</h3><p>A typical scenario for this situation is when you need to build one version of your app for iPhone and another specific version for iPad, probably you will need to share some part of your code and customize others things such as screen layout or some presentation behaviors. Another situation could be a big company that has some independent business units and desires to build just one app for these companies, we could suppose that some business rules can be different for each business unit.</p><h3>How can I achieve this goal?</h3><p>In the Xcode development universe we have a thing called Target, a brief description from Apple says:</p><blockquote>A target specifies a product to build and contains the instructions for building the product from a set of files in a project or workspace.</blockquote><p>To simplify the subject, by default when you create a new project, a Target is created into your project. If you want, you can rename or duplicate it. You may ask why do I need to duplicate one instead of creating a new one. The explanation is that associated with a Target, there are many default configurations, in this case when you duplicate a Target, you are making a clone of it. After that, you can change bundle identifier, deployment info, display name, app icons source, and so on. When you demand to run the project, you need to specify in which Target it must be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSNj0gmWH1pr7yotzwSMpA.png" /><figcaption>Duplicating a Target</figcaption></figure><p>So, another powerful thing that a Target provides is the possibility to create a resource with the same name for each Target you have. Notice in the picture above, the project has two files declaring a class called Product, in a normal situation it will produce a compilation error, but using Target, you can assign each file to a specific Target. Look at the image below, you select the file and define the Target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQ-aCQd3we1TCTkMLH0iIw.png" /><figcaption>Defining a target membership</figcaption></figure><p>Another way to assign the Target is when you are creating a new resource, observe in the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uA3NnrJpF7Q0pIhWfCBCmQ.png" /><figcaption>Defining target membership on resource creation</figcaption></figure><h3>Look out! A common mistake</h3><p>When you are working with Target it is very common to create a resource and forget to assign more than one Target, later when you try to compile, you get an error saying that that resource does not exist, so you look in the source code tree and file is there, but it is not been included in the selected target, believe me, I already spent some minutes trying to understand what was wrong.</p><h3>A source code sample is worth a thousand words</h3><p>To make it easier, I developed a simple sample application that uses a class name Product to get a property called <strong>“whoIAm”</strong>. There are two version of class Product, one for each Target and the property output is different in each case, i.e, if you run the &quot;<strong>ProductOne&quot;</strong> the output will be <em>“Product One”</em> and if you run <strong>“ProductTwo”</strong> the output will be <em>“Product Two”</em>. To get the source code follow the GitHub link below:</p><p><a href="https://github.com/heuristisk/hkScopum">heuristisk/hkScopum</a></p><h3>Building your app for a specific environment, i.e, development, testing or production</h3><p>Generally, in most enterprise projects we have multiple environments, and from time to time we need to compile our project to a specific environment. A typical setting that we need to change to distribute a version is the URL of backend services, we could make it manually, but it is not the better way to do this. On Xcode we can create multiple build configurations and specify any setting we need to that environment, after that when we need to change the environment, we just select in which environment we are working on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/892/1*Q_RXWb13kyVUyRJE2cHWbQ.png" /><figcaption>Creating build configurations</figcaption></figure><p>As you can suppose, in the image above you see the screen where you can create your new build configuration, the principle is the same as mentioned on creating Targets, it will be cloned from debugging or release configuration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*emEIIHSu6mlAdSK-6cXJMw.png" /><figcaption>Creating new settings</figcaption></figure><p>As you can observe in the image above, after you create a new build configuration you can add new settings and assign in which build configuration it must be applied, in our case, we are adding a different URL for each build configuration.</p><h3>Changing build configuration</h3><p>To change the build configuration, you need to edit the current scheme that you are using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*Q6grc8Kxfd5UvPhKEpkpzw.png" /></figure><p>After that, you can select in which build configuration the build process must be done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d_BpK9XLRk3_mLOFeo0vKA.png" /></figure><h3>Getting the user-defined settings on your code</h3><p>You must be asking yourself, how do I get this setting in code? We need to create a mechanism to recovery this data, and it is through Info.plist file. But wait, we are going to put there just a variable reference as you can see on the image below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwQHvrQVSkWSMknU96dA7Q.png" /></figure><p>As you can see we are using the same reference “<strong><em>$(ENDPOINT_URL)</em></strong>” as typed on the user-defined section at build settings. Now, we need to load the dictionary and recovery the URL as you can see in the code below, during the build process the Xcode will replace the reference variable with URL specified on that build configuration, very elegant, don’t you think?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b20ac66510689416a324ed41d103e0eb/href">https://medium.com/media/b20ac66510689416a324ed41d103e0eb/href</a></iframe><p>The complete sample using these techniques is on GitHub link below as already mentioned before. I hope it helps you understand better these concepts and if you have any question, improvement or suggestion, please feel free to contact me! See you next time.</p><p><a href="https://github.com/heuristisk/hkScopum">heuristisk/hkScopum</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a575ddc687" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>