<?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 🐻TheDev on Medium]]></title>
        <description><![CDATA[Stories by 🐻TheDev on Medium]]></description>
        <link>https://medium.com/@MedvedevTheDev?source=rss-6eb72663fe46------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ye5nT3FaKuId14WD4yqWsQ.jpeg</url>
            <title>Stories by 🐻TheDev on Medium</title>
            <link>https://medium.com/@MedvedevTheDev?source=rss-6eb72663fe46------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 09:34:38 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MedvedevTheDev/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[XMLParser: Working With RSS Feeds In Swift]]></title>
            <link>https://medium.com/@MedvedevTheDev/xmlparser-working-with-rss-feeds-in-swift-86224fc507dc?source=rss-6eb72663fe46------2</link>
            <guid isPermaLink="false">https://medium.com/p/86224fc507dc</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xml]]></category>
            <category><![CDATA[rss]]></category>
            <dc:creator><![CDATA[TheDev]]></dc:creator>
            <pubDate>Sun, 05 Mar 2017 15:53:50 GMT</pubDate>
            <atom:updated>2017-03-05T15:53:50.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*TmBQCQ3-7nQxINKfzm4z2Q.png" /></figure><p>You’ve definitely seen this icon on just about every blog, traditional media site, and plenty of other places. That’s because it represents a rather popular standard of open information proliferation. Originally dubbed RDF Site Summary, but oftentimes called Really Simple Syndication, RSS is a format for delivering regularly changing web content.</p><p>An RSS file consists of both static information about the feed as well as dynamic items. These items are usually news articles or blog entries, but they can be about <strong>any web-accessible content</strong>. Each item sits inside an &lt;item&gt; (or &lt;entry&gt;) tag and contains among others a <strong>title</strong>, a <strong>url</strong>, and a <strong>publication date</strong>.</p><p>You may know that RSS is just a form of XML, which itself is a simple markup language. XML elements are values set off by tags which are one of three types:</p><ol><li>Start tags, to mark the start of a value (such as &lt;item&gt;).</li><li>End tags, to mark the end of a value (&lt;/item&gt;).</li><li>“Empty element” tags, which might contain values as attributes (&lt;feedburner:info uri=&quot;linuxjournalcom&quot; /&gt;).</li></ol><blockquote>RSS feeds have a well defined format. After some header information to describe the news website or “channel”, the RSS feed displays separate news items inside &lt;item&gt;...&lt;/item&gt; elements. Each news item contains a title, link, publication date, full description and other fields.</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FlKXd9sYM5dI9W%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Fpaul-rudd-anchorman-brian-fantana-lKXd9sYM5dI9W&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FlKXd9sYM5dI9W%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="204" frameborder="0" scrolling="no"><a href="https://medium.com/media/54765aef933aaf5cdb359056c7b4abe8/href">https://medium.com/media/54765aef933aaf5cdb359056c7b4abe8/href</a></iframe><p>Now that we’ve covered the basics, I have to tell you something important. The different RSS standards out there (e.g. RSS 2.0, Atom, etc.) are, in reality, mere <em>guidelines</em>. From my experience parsing XML, it appears that, even if an organization or blogger claims to conform to a particular RSS spec, the actual content structure varies tremendously across different feed sources.</p><p>Essentially, each RSS feed is like no other. There are certain overlaps, but I’ve seen publishers take many liberties with their feeds, the use of inline HTML being the most troublesome one. If this doesn’t seem to bother you, then let’s dive in!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FSRGpALDA3i5va%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Fcomedy-will-ferrell-anchorman-SRGpALDA3i5va&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FSRGpALDA3i5va%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/51c989d4159c6d1d5eb922e9dbcfce25/href">https://medium.com/media/51c989d4159c6d1d5eb922e9dbcfce25/href</a></iframe><p>There are many ways to parse XML in iOS. In this tutorial, we will be using XMLParser which is a SAX parser included by default with the iPhone SDK and written in Objective-C.</p><p>Once you have found an RSS feed that you want to work with, take a close look at the actual feed structure. You have to understand the XML structure of the feed in order to make sure the data you are presenting in your app matches up exactly with the news items as they appear in the feed. For that, check the RSS feed’s page source. Now that we know the exact structure of our XML file, we can begin the parsing.</p><p>First, we should create a separate parser class. Let’s call that RSSParser. We need to subclass it from NSObject and make it conform to the XMLParserDelegate protocol. Next, we define some key properties of this class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*BPpJ_SvCF0wxfJRdDZOV7w.png" /></figure><p>xmlParser represents the actual <strong>parser object</strong> that will be performing all of the work. currentElement holds the value for the current XML tag, whereas foundCharacters represents the value of said tag, i.e. characters encapsulated by the tag. Since each item / entry element contains several properties, we reconstruct each feed item in the currentData variable. And since a feed has many articles, once we’re done with all of the components of a single element and begin parsing the contents of the next one, we append our complete entry to parsedData which represents the entirety of a single RSS feed. Finally, isHeader is a flag that lets us know whether we’re parsing an actual feed item or its header (which also has a title, description, and so on).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*14aJuXdx0b-sOy97s8vQ8Q.png" /></figure><p>This process starts with the parser’s startParsingWithContentsOfURL(_:_:) method. It instantiates the actual parser object, sets the class instance as the parser delegate, and begins parsing the contents of a given URL. As we parse through our RSS feed, we append each distinct entry to parsedData. However, because this happens in parser(_:didStartElement:_:_:_:), we always drop the last entry of a feed. In order to get around it, we append currentData to parsedData in startParsingWithContentsOfURL(_:_:) because we know that this currentData represents the last feed element. Finally, we use a completion handler in order to ensure that we’re not trying to pass the parsedData prematurely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t7SKbmSZLt0hoMMr0fOd9Q.png" /></figure><p>Once we’ve invoked startParsingWithContentsOfURL(_:_:), our parser calls on a sequence of methods, the first one being parser(_:didStartElement:_:_:_:). Here we set currentElement to the value of elementName which represents a tag name from our RSS feed. In our case, we’re interested in all of the item and entry tags. The isHeader flag allows us to skip over irrelevant entries and aids us with media url capture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aER09hfn8WefpfTJwbw9pw.png" /></figure><p>parser(_:foundCharacters:) handles the string of characters that we’re interested in — that is, it appends the string values of our desired entries to our RSSParser <em>instance</em> <em>property</em> foundCharacters. deleteHTML(tags:) removes inline HTML tags from our found characters using regex.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nr30-zR4h1iiZOBuORjJew.png" /></figure><p>Finally, parser(_:didEndElement:_:_:) looks at the closing tag of an element. Here, we remove all whitespace and newline characters, then add a new key-value pair to currentData. Voila!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FEklVJOCXj3avu%2Ftwitter%2Fiframe&amp;src_secure=1&amp;url=http%3A%2F%2Fgiphy.com%2Fgifs%2Fanchormanmovie-movie-happy-excited-EklVJOCXj3avu&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FEklVJOCXj3avu%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b6ebb9fb2e913d2f360a9c1523a0768/href">https://medium.com/media/2b6ebb9fb2e913d2f360a9c1523a0768/href</a></iframe><p>Given our setup, once the parser goes through the entire XML file, we will have all of our relevant and nicely formatted entries in parsedData. At that point, the sky’s the limit!</p><p><strong>Useful links:</strong></p><ul><li><a href="http://www.whatisrss.com/">What Is RSS? RSS Explained - www.WhatIsRSS.com</a></li><li><a href="https://developer.apple.com/reference/foundation/xmlparser">XMLParser - Foundation | Apple Developer Documentation</a></li><li><a href="https://www.raywenderlich.com/553/xml-tutorial-for-ios-how-to-choose-the-best-xml-parser-for-your-iphone-project">XML Tutorial for iOS: How To Choose The Best XML Parser for Your iPhone Project</a></li><li><a href="https://github.com/theMedvedev/rss-reader">theMedvedev/rss-reader</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86224fc507dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Xamarin.iOS Intro: Simple Twitter App]]></title>
            <link>https://medium.com/@MedvedevTheDev/xamarin-ios-intro-simple-twitter-app-80bfbc2a7efd?source=rss-6eb72663fe46------2</link>
            <guid isPermaLink="false">https://medium.com/p/80bfbc2a7efd</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[xamarin]]></category>
            <dc:creator><![CDATA[TheDev]]></dc:creator>
            <pubDate>Mon, 16 Jan 2017 03:30:11 GMT</pubDate>
            <atom:updated>2017-01-16T03:30:11.947Z</atom:updated>
            <content:encoded><![CDATA[<p>So I decided to learn Xamarin and C#. Because learning new things is cool. Specialization is cool too, but, as a wise man once said, “The more you know, the more you know you don’t know.” I very quickly realized that documentation is sparse, scattered across the web, and, in some places, outdated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*GyttLiDrfK_g30O8cUa1yw.gif" /></figure><p>Coming into C# and Xamarin from Swift and XCode is not for the faint of heart. I wouldn’t “recommend it to a friend.” There are many arguments to be made against Xamarin development, but, personally, I find the “third learning curve” to be the most off-putting. If you’re not sure about whether Xamarin is right for you, be sure to check out Lee Whitney’s blog:</p><p><a href="http://www.whitneyland.com/2015/07/xamarin-review-2015.html">Review: Xamarin in 2015 - Data Corruption and Swift are Not Helping</a></p><h3>Xamarin.Forms vs Xamarin Native</h3><p>Having a background in Swift, I chose to go with native because it just felt right. I also didn’t feel like diving into XAML because I wanted to get straight to coding instead of picking up a foreign markup language (in addition to all of the things I did not know about Xamarin development, i.e. <em>everything</em>).</p><p>Again, google and see what’s best for you. Also, check out Don Fitzsimmons’ thoughts on the matter:</p><p><a href="https://thedon.me/2016/10/07/xamarin-forms-vs-xamarin-native-ui/">Xamarin Forms vs. Xamarin Native UI</a></p><h3>Goal: Leverage Swift Skills to Build A Twitter Client</h3><p>First things first, lets identify the moving parts in this puzzle:</p><ol><li>Twitter API</li><li>HTTP Requests</li><li>JSON Parsing</li><li>Table Views</li></ol><p>Seems simple and straightforward, <em>right</em>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/1*pv2DQUUZYOYo34V1GNYkew.gif" /><figcaption>How hard can it be? There’s only one way to find out…</figcaption></figure><p>Yeah, no. As I mentioned earlier, documentation is hard to come by and is obscure at best. Some things in Xamarin look rather archaic, as if The Grand Renaming never happened. Out of the 20 hours I’ve spent building this simple Twitter client, I will say that about half went into documentation research.</p><p>As it turns out you can add packages to Xamarin. These are, essentially, the same as pods. There are, however, several different directories in a project. In mine, for example, I have projectName and projectName.ios. The former houses all of the cross-platform code which is available in the global namespace, whereas the latter contains code that exists in a namespace that is a subspace of the global one.</p><h3><strong>TwitterAPIClient.cs</strong></h3><pre> using System;<br> using System.Net.Http;<br> using System.Collections.Generic;<br> <br> namespace freshTwitter<br> {<br>     public class TwitterAPIClient<br>     {<br>         // initial OAuth request<br>         public static string GetAuthToken()<br>         {<br>             var httpClient = new HttpClient();<br>             httpClient.DefaultRequestHeaders.Accept.Add(<br>                 new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)<br>             );<br>             httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, &quot;Basic &quot; + Secrets.Key);<br>             var baseUri = new Uri(&quot;https://api.twitter.com/oauth2/token&quot;);<br>             var parameters = new Dictionary&lt;string, string&gt;();<br>             parameters[&quot;Content-Type&quot;] = &quot;application/x-www-form-urlencoded;charset=UTF-8&quot;;<br>             parameters[&quot;grant_type&quot;] = &quot;client_credentials&quot;;<br> <br>             var response = httpClient.PostAsync(baseUri, new FormUrlEncodedContent(parameters)).Result;<br>             var contents = response.Content.ReadAsStringAsync().Result;<br> <br>             return contents;<br>         }<br> <br>         // GET user timeline Twitter API call<br>         public static string GetUserTimeline(string userScreenName)<br>         {<br>             var httpClient = new HttpClient();<br>             httpClient.DefaultRequestHeaders.Accept.Add(<br>                 new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(&quot;application/json&quot;)<br>             );<br>             httpClient.DefaultRequestHeaders.Add(&quot;Authorization&quot;, &quot;Bearer &quot; + Secrets.Token);<br>             var baseUri = new Uri(&quot;https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=&quot; + userScreenName);<br>             var response = httpClient.GetAsync(baseUri).Result;<br>             var contents = response.Content.ReadAsStringAsync().Result;<br> <br>             return contents;<br>         }<br>     }<br> }</pre><p>First, I create a simple HTTP request GetAuthToken() using my favorite method — try stuff until it works. The key here lies in using Paw to test Twitter’s API endpoints. Then, I add a request that gets a user’s timeline based on their username GetUserTimeline(string userScreenName).</p><h3><strong>ViewController.cs</strong></h3><pre>using System;<br>using Newtonsoft.Json;<br>using System.Collections.Generic;<br>using UIKit;<br> <br> namespace freshTwitter.iOS<br> {<br>     public partial class ViewController : UIViewController<br>     {<br>         // temporary tweets store<br>         List&lt;string&gt; tweets = new List&lt;string&gt;();<br> <br>         // table view<br>         UITableView _table = new UITableView();<br> <br>         // text field<br>         UITextField textField = new UITextField();<br> <br>         public ViewController(IntPtr handle) : base(handle)<br>         {<br>         }<br> <br>         public override void ViewDidLoad()<br>         {<br>             base.ViewDidLoad();<br> <br>             // get token from Twitter, parse token, &amp; set token in Secrets<br>             var oAuthJson = TwitterAPIClient.GetAuthToken();<br>             TwitterJSON token = JsonConvert.DeserializeObject&lt;TwitterJSON&gt;(oAuthJson);<br>             Secrets.Token = token.Name;<br>             Console.WriteLine(token.Name);<br> <br>             // add search text field<br>             textField = new UITextField(new CoreGraphics.CGRect(0, 20, View.Bounds.Width, 20));<br>             textField.Placeholder = &quot;Search for user&quot;;<br>             textField.KeyboardType = UIKeyboardType.Default;<br>             textField.ReturnKeyType = UIReturnKeyType.Search;<br>             textField.MinimumFontSize = 14f;<br>             textField.AdjustsFontSizeToFitWidth = true;<br>             textField.TextAlignment = UITextAlignment.Center;<br>             View.AddSubview(textField);<br> <br>             // add search button<br>             UIButton searchButton = new UIButton();<br>             searchButton.Frame = new CoreGraphics.CGRect(View.Bounds.Width - 70, 20, 60, 20);<br>             searchButton.SetTitle(&quot;Seach&quot;, UIControlState.Normal);<br>             searchButton.BackgroundColor = UIColor.Green;<br>             View.AddSubview(searchButton);<br> <br>             // search functionality<br>             searchButton.TouchUpInside += (object sender, EventArgs e) =&gt;<br>             {<br>                 // handle reuse<br>                 if (tweets.Count != 0)<br>                 {<br>                     tweets = new List&lt;string&gt;();<br>                 }<br> <br>                 var rawTimeline = TwitterAPIClient.GetUserTimeline(textField.Text);<br>                 // TODO: add error handling, e.g. user does not exist<br> <br>                 List&lt;TwitterJSON&gt; timeline = JsonConvert.DeserializeObject&lt;List&lt;TwitterJSON&gt;&gt;(rawTimeline);<br> <br>                 // extract tweets from timeline<br>                 foreach (TwitterJSON tweet in timeline)<br>                 {<br>                     tweets.Add(tweet.TweetText);<br>                 }<br>                 textField.ResignFirstResponder();<br> <br>                 // add table view<br>                 _table = new UITableView<br>                 {<br>                     Frame = new CoreGraphics.CGRect(0, 40, View.Bounds.Width, View.Bounds.Height - 40),<br>                     Source = new TableSource(tweets.ToArray())<br>                 };<br>                 View.AddSubview(_table);<br>             };<br>         }<br>     }<br> }</pre><p>Here, I get a token from Twitter, parse it, and store it. Next, I implement simple search functionality by adding a text field and a search button. That’s pretty much it!</p><h3>TwitterJSON.cs</h3><pre> using System;<br> using Newtonsoft.Json;<br> using Newtonsoft.Json.Serialization;<br> <br> namespace freshTwitter<br> {<br>     // define class used to parse response to get token, tweets<br>     public class TwitterJSON<br>     {<br>         [JsonProperty(&quot;access_token&quot;)]<br>         public string Name // change to something more descriptive<br>         {<br>             get;<br>             set;<br>         }</pre><pre>         [JsonProperty(&quot;text&quot;)]<br>         public string TweetText<br>         {<br>             get;<br>             set;<br>         }<br> <br>         [JsonProperty(&quot;created_at&quot;)]<br>         public string TweetDate<br>         {<br>             get;<br>             set;<br>         }<br>     }<br> }</pre><p>I set up a simple class that helps parse JSON obtained from Twitter in ViewController.cs.</p><h3>TableSource.cs</h3><pre> using System;<br> <br> using UIKit;<br> <br> namespace freshTwitter.iOS<br> {<br>     public partial class TableSource : UITableViewSource<br>     {<br> <br>         string[] tweets;<br>         string cellIdentifier = &quot;TweetCell&quot;;<br> <br>         public TableSource(string[] items) : base()<br>         {<br>             tweets = items;<br>         }<br> <br>         public override nint RowsInSection(UITableView tableview, nint section)<br>         {<br>             return tweets.Length;<br>         }<br> <br>         public override UITableViewCell GetCell(UITableView tableView, Foundation.NSIndexPath indexPath)<br>         {<br>             UITableViewCell cell = tableView.DequeueReusableCell(cellIdentifier);<br>             if (cell == null)<br>                 cell = new UITableViewCell(UITableViewCellStyle.Default, cellIdentifier);<br>             cell.TextLabel.LineBreakMode = UILineBreakMode.WordWrap;<br>             cell.TextLabel.Lines = 0;<br>             cell.TextLabel.SizeToFit();<br>             cell.TextLabel.Text = tweets[indexPath.Row];<br>             return cell;<br>         }<br>     }<br> }</pre><p>And everything is presented in a simple table view.</p><p>In the end, I’ve created a simple app that allows me to look up tweets for a specific user. It would take me about an hour or two to setup an Android version of the app, given that I defined TwitterAPIClient.cs and TwitterJSON.cs in the global namespace. All in all, it was a lot of fun picking up Xamarin. Although I believe in learning both Android and iOS <strong>“the hard way,”</strong> I think Xamarin is an amazing tool which provides a great opportunity for expanding a mobile developer’s platform knowledge.</p><h3>Resources:</h3><ul><li><a href="https://github.com/theMedvedev/fresh-twitter-xamarin">theMedvedev/fresh-twitter-xamarin</a></li><li><a href="https://www.thecodingguys.net/downloads/csharp">C# Downloads | the coding guys</a></li><li><a href="https://mobileup.io/platform/xamarin-forms/json-with-httpclient-and-json-net">Loading and Parsing JSON with HttpClient and Json.NET - Brax</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=80bfbc2a7efd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why Encoding Matters: A Primer on Bits and Bytes]]></title>
            <link>https://medium.com/@MedvedevTheDev/why-encoding-matters-a-primer-on-bits-bytes-and-history-4ec9dc441355?source=rss-6eb72663fe46------2</link>
            <guid isPermaLink="false">https://medium.com/p/4ec9dc441355</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[unicode]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[TheDev]]></dc:creator>
            <pubDate>Thu, 27 Oct 2016 19:04:03 GMT</pubDate>
            <atom:updated>2017-03-04T21:48:22.936Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*jS1X9oqBV2mNdndw5zGBHw.png" /><figcaption>UTF-8 accounted for 87.7% of all Web pages in October 2016.</figcaption></figure><p>Looking at this chart leads to an obvious conclusion: encoding doesn’t matter; everyone uses UTF-8, and so should <strong>you</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*V2Py0yzoez6b6nohxJ2n9Q.gif" /><figcaption><strong>NOT TRUE!!!</strong> Encoding <strong>does</strong> matter.</figcaption></figure><p>However, that’s simply not the case. In order to grasp the full significance of encoding, we have to go back to the old days, the <em>Pre-UTF-8 Era.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dKWjqbBj9gueiErUeaMzkQ.png" /><figcaption>Remember when you tried to talk to somebody over email or IM and you couldn’t figure out why the person received your messages just fine but replied with garbled text?</figcaption></figure><p>Those were the dark ages of encoding. Communication could easily break down, and it would be hard for the average user to figure out what exactly had gone wrong. This problem resulted from using different encodings to read byte sequences. To understand the crux of this issue, let’s look at two key terms:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*EkE0z-NCk1yQNGZCs0MLzw.gif" /></figure><ul><li><strong>Bit</strong>: a basic unit of information, commonly represented as either 0 or 1</li><li><strong>Byte</strong>: a fixed-length sequence of bits, most commonly consisting of 8 bits</li></ul><p>Thus, a byte came to be represented as 2⁸ = 256 numbers, ranging from 0 to 255 (or 00000000 to 11111111 in bits). The bits in a byte were given indices. The right-most bit (also referred to as the <em>least significant</em>) received an index of 0, and the left-hand most bit (also referred to as the <em>most significant</em>) was given an index of 7. <em>This is still the case today, btw!</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/608/1*-j-LAy8d8hHPpaImuXPw6A.jpeg" /><figcaption>Check out this simple chart that shows you decimals in hexadecimal and binary form.</figcaption></figure><p>Using binary (or hexadecimal) notation was cumbersome and inefficient, to say the least. There was a need for some encoding standard. This is where things got weird, because, as you’ve probably guessed, the <em>meaning</em> of raw bit sequences changed depending on the encoding used.</p><h3>Enter ASCII</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*72VwYzkdpf5cV0qWtT9pGw.png" /><figcaption>Most modern character-encoding schemes are based on ASCII (although they support many additional characters).</figcaption></figure><p>ASCII is a character encoding standard which uses 7 bits to represent 128 specified characters based on the English alphabet. Numbers between 0 and 32 were reserved for control characters that dictated how the data should be interpreted and represented. They were designed for printing control, data structuring, and transmission control. All unaccented English characters use numbers between 32 and 127.</p><p>The key here is that ASCII was designed for <em>unaccented English characters</em>. Despite the fact that this encoding only uses 7 bits (leaving an entire bit unused), ASCII cannot be easily used for many other languages.</p><p>For example, Asian alphabets have thousands of letters, which were never going to fit into 8 bits. Many other alphabets use accents such as <strong>ˆ</strong>, <strong>´</strong>, <strong>¨</strong>, and so on. Therefore, just as the United States developed ASCII, other countries created their own encodings. This led to an incongruent mix of various code standards that were based on the needs and nuances of different languages and warranted transcoding.</p><p>Essentially, different countries had varying encoding standards. When computers came along, it was impossible to effectively exchange information between software tailored for different standards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*8H5ZnJtsebbYcSoI402o5Q.gif" /><figcaption>The same bits, under different encoding standards, became different characters.</figcaption></figure><p>Then came ISO/IEC 8859 — an encoding which was backward-compatible with <strong>8-bit</strong> ASCII and consisted of 191 characters from the Latin script. It included various <em>accents</em> that allowed for complete coverage of Afrikaans, Corsican, Faroese, Norwegian, and many others.</p><p>Nevertheless, ISO/IEC 8859 only encoded the first 256 <strong>Unicode</strong> characters using single-byte fixed length encoding, which meant that some languages still remained incompatible.</p><p>For example, consider ISO/IEC 8859–5 which was designed for Cyrillic alphabets:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8kInSPFYoInSVaeGwJ9ZOQ.png" /><figcaption>ISO/IEC 8859–5 designed to cover languages that use a Cyrillic alphabet.</figcaption></figure><p>And GB 18030 — the official character set of the People’s Republic of China:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KKJ4R3fnHFLM1ZNRzpakVA.jpeg" /><figcaption><strong><em>Information technology — Chinese coded character set</em></strong> defines the required language and character support necessary for software in China.</figcaption></figure><p>Although Cyrillic alphabets were integrated in ISO/IEC 8859, it did not support the Chinese writing system.</p><h3>Enter Unicode</h3><blockquote>Unicode is a computing industry standard for the consistent encoding, representation, and handling of text expressed in most of the world’s writing systems.</blockquote><p>The latest version of Unicode (9.0) contains a repertoire of more than <strong>128,000 characters</strong> covering <strong>135 modern and historic scripts</strong>, as well as multiple symbol sets. Unicode has the following key properties:</p><ul><li><strong>Unicode code point</strong>: a single value in the Unicode code space with a possible value from 0 to 0x10FFFF (17 × 65,536 = 1,114,112 code points)</li><li>Private Use Area (<strong>PUA</strong>): a range of code points that is intentionally left undefined so that third parties may define their own characters without conflicting with Unicode Consortium assignments</li></ul><p>Unicode<strong> </strong>can be implemented by different character encodings, however, most commonly used ones are:</p><ul><li>UTF-8: a <strong>8-bit</strong> variable-width encoding which maximizes compatibility with ASCII</li><li>UTF-16: a <strong>16-bit</strong>, variable-width encoding (uses a minimum of 2 bytes and is therefore incompatible with ASCII)</li></ul><p>The first 256 Unicode code points match the characters found in Latin-1 (ISO/IEC 8859–1). Moreover, UTF-8 is backward-compatible with 7-bit ASCII as it can use 1 byte for any ASCII character, all of which have the same code values in both UTF-8 and ASCII encoding.</p><h3>So why does encoding matter..?</h3><p>String is a fundamental type in many programming languages. Encoding is the way characters are stored into memory. Adding two and two together —</p><blockquote>Encoding matters because it affects the way strings, which are collections of characters, are stored in memory.</blockquote><p>Let’s talk about Unicode equivalence. It’s the notion that some sequences of code points represent essentially the same character. This feature allows for compatibility with preexisting standard character sets. There are two distinct notions of Unicode equivalence, but we’ll be focusing on one — <strong>Canonical Equivalence</strong> which states that <em>two code point sequences are assumed to have the same appearance and meaning when printed or displayed</em>.</p><blockquote><strong>U+006E</strong> followed by <strong>U+0303</strong> is canonically equivalent to <strong>U+00F1</strong>, that is, the character <strong>n </strong>followed by <strong>˜</strong> is equivalent to <strong>ñ</strong></blockquote><p>Another example would be emoji where <em>multi-person groupings are composed from several individual member emoji</em> joined with the zero-width joiner.</p><pre>&quot;👩🏾&quot;.characters.count <em>// 2</em><br>&quot;👨‍👨‍👧‍👧&quot;.characters.count <em>// 4</em><br>&quot;👩\u{200D}👩\u{200D}👦\u{200D}👦&quot; == &quot;👩‍👩‍👦‍👦&quot; <em>// true</em></pre><p>As you can see above, in Swift 3.0, the character count of the two emoji is different (if you’re wondering why 👩🏾 has a count of 2, it’s because one character represents the face/person while another character is used for skin tone).</p><p>This introduces the idea that working with canonically equivalent sequences of code points can lead to unexpected outcomes, or bugs. While this example is undeniably niche, it highlights the importance of encoding in programming today.</p><p>Now, for an even more nuanced example, consider a different scenario. Imagine you have a relatively low cap on an object’s size in bytes. A QR code, for example. This type of 2D barcode can store a maximum of 2953 8-bit characters. Would it matter which encoding we use?</p><p>Yes. Remember, ASCII is a fixed-width encoding, while in Unicode has numerous ways of storing characters in byte sequences. Thus, the same word in two different encodings will have two different sizes, depending on the encoding used.</p><p>To sum it all up, bits, bytes, and canonical equivalence are three concepts that every programmer should know.</p><h3>Additional Resources</h3><ul><li><a href="http://reedbeta.com/blog/programmers-intro-to-unicode/">A Programmer&#39;s Introduction to Unicode - Nathan Reed&#39;s coding blog</a></li><li><a href="https://en.wikipedia.org/wiki/Comparison_of_Unicode_encodings">Comparison of Unicode encodings - Wikipedia</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FMijmeoH9LT4%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DMijmeoH9LT4&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FMijmeoH9LT4%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd22f9218d0f0d58317e5b71bc75d8b/href">https://medium.com/media/7dd22f9218d0f0d58317e5b71bc75d8b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FB1BdQcJ2ZYY%3Fstart%3D85%26feature%3Doembed%26start%3D85&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DB1BdQcJ2ZYY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FB1BdQcJ2ZYY%2Fhqdefault.jpg&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/aaa486834295e370231e95c2762f4985/href">https://medium.com/media/aaa486834295e370231e95c2762f4985/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4ec9dc441355" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generating Basic QR Codes in Swift 3.0]]></title>
            <link>https://medium.com/@MedvedevTheDev/generating-basic-qr-codes-in-swift-63d7222aa011?source=rss-6eb72663fe46------2</link>
            <guid isPermaLink="false">https://medium.com/p/63d7222aa011</guid>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[qr-code]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[TheDev]]></dc:creator>
            <pubDate>Tue, 11 Oct 2016 19:13:33 GMT</pubDate>
            <atom:updated>2016-10-20T19:09:26.100Z</atom:updated>
            <content:encoded><![CDATA[<p>QR codes are a type of 2D barcode that was originally developed for use in the Japanese car industry. Encoding URLs, promoting virtual stores, accessing cryptocurrency wallets, adding new contacts to messaging platforms — QR codes (or some variants of them) provide a streamlined approach to working with various types of data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/631/1*jEgWDnml_m_AwLZGK1WPbQ.png" /><figcaption>Facebook’s take on a QR code v. The Snapcode</figcaption></figure><p>Lets look at using static data to create our code — for example, a String.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2NYU1uPMEYQbX1CNVViQmw.png" /><figcaption>Thanks to the Core Image framework, generating a simple QR code takes only a few lines of code</figcaption></figure><p>In the code above we’ve created a function called generateQRCode(from:) which returns an optional <strong>UIImage</strong>.</p><p>In this function, we first want to convert our string to a <strong>Data</strong> object (which is simply a <strong>MutableCollection</strong> of bytes). This object will contain our string’s representation using some given encoding. In this case, we use <em>ISO Latin 1</em>; however, <em>ASCII</em> or <em>UTF-8</em> works too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*anAcAxZ_kY5FStNYl-RnHQ.png" /><figcaption><strong><em>This is the heart of QR code generation</em></strong></figcaption></figure><p>Now, create an instance of <em>CoreImage</em> filter using the parameter name <strong>“CIQRCodeGenerator.”</strong></p><p>Essentially, we’ve initialized a CIFilter object, one for the specific filter called <strong>“CIQRCodeGenerator.” </strong>This parameter name lets us reference Swift’s built-in filter for QR code generation through the Core Image framework.<strong> </strong>After creating a filter with the CIFilter method in Swift, you must call setDefaults() or setValue(_:forKey:) to set parameters individually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g44JC_uLEo4oPJ8n9YEb1A.png" /><figcaption>Core Image Filter Reference: CIQRCodeGenerator</figcaption></figure><p>After creating a filter with the CIFilter method in Swift, you must call setDefaults() or setValue(_:forKey:) to set parameters individually.</p><p>This might seem esoteric, to some degree, and it probably should, given the underlying levels of complexity. Take a closer look at the next line:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*-1fMXhY5g_0Wun2cWhCdqw.png" /><figcaption>Data, in this case, is our function’s string argument</figcaption></figure><p>Here, we pass our data constant — which is simply an encoded version of our string — to set the value for the key <strong>“inputMessage.” </strong>This step is crucial and it works in this manner because the parameters of a CIFilter object are set and retrieved through the use of <em>key-value pairs</em>.</p><p>Done! Well, not quite.</p><p>To recap, we’ve passed our generateQRCode(from:) function a string which we’ve then encoded into a data object. Then, we’ve created a CIFilter object of the specific kind <strong>“CIQRCodeGenerator.”</strong> Finally, we’ve used our data object to set the value for the key <strong>“inputMessage”</strong> which represents the data input used in our QR code generation. Essentially, we’ve retrieved a specific template, gathered all of the necessary components, but still haven’t <em>returned</em> anything.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*9BCvFh1TwYwGGdCP8gSowA.png" /><figcaption>We create our final <strong>CIImage</strong> by applying a <em>transform</em> and return it as a <strong>UIImage</strong></figcaption></figure><p>Don’t worry about the transform nonsense; we’ll get to that in just a moment (we’re using it to get rid of the blur in our resulting QR code).</p><p>Focus on unwrapping the output. Why are we doing this? It’s because filter — which is our CIFilter — returns an optional <strong>CIImage </strong>(again, feel free to disregard the .applying(transform) at the end there, for now).</p><p>In this particular case, CIFilter ultimately produces a <strong>CIImage</strong> object using a string as an input. In order to have the image properly displayed in the imageView outlet, we cast it as a <strong>UIImage</strong>. Finally, we get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*Sdgrs3tdARBqKegEI9KdIA.png" /><figcaption>Core Image + a few lines of code + some logic = 🔳</figcaption></figure><p>Oh no! Why is our QR code so freaking blurry? Since our <strong>CIImage</strong> is made up of points, the resulting <strong>UIImage</strong> is scaled to fit our UIImageView, which results in a lack of clarity. This is where the transform part comes in!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*9idT0XZh_WfPvVwkLaej9Q.png" /><figcaption>Note that the current scale is set to x: 1, y: 1 — this is exactly what we’ll be working with to fix this blur</figcaption></figure><p>We create an <em>affine transformation matrix</em> which we will use to scale our QR code. This is simply a struct used in drawing 2D graphics. In short, this matrix links two coordinate systems by specifying how points in one coordinate system map to points in another. Then, we apply it when we unwrap the resulting optional <strong>CIImage</strong>.</p><p>The key here are the two scale values — x and y. We’ve set them both to 1, and this is precisely the reason why we’ve created a QR code of such exceptionally poor quality. What if we try changing both values (scaleX and scaleY) to <strong>100</strong>?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/484/1*SND6uNhxXWpI7y4SBvtIqw.png" /><figcaption>Now that’s what I’m talking about!</figcaption></figure><p>We’ve successfully scaled up our <strong>UIImage</strong>. To be honest, we’ve simply used an arbitrarily large number. If we want to be more elaborate with the scaling, we can figure out our desired <em>scaling factor </em>programmatically. So what is this scaling factor?</p><p>Well, actually, it’s always equal to the ratio of an image view’s width and the original QR code’s width. In our example, this translates to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*HU8AWur1SbksAT4-UzWFZg.png" /><figcaption>In order to get the width and height of our QR code, we create a CIImage and assign it to the qrCodeImage variable</figcaption></figure><p>We’ve added three new lines of code. First, we’ve created a <strong>CIImage</strong> object by calling outputImage on our CIFilter object. Since this method returns an optional value, we’ve unwrapped it using a <strong>guard</strong> statement. Next, we’ve set up two constants for our two axes (x and y). As mentioned above, scaleX and scaleY are simply equal to the ratios of our image view’s width and height and our QR code’s width and height, respectively. Finally, we’ve passed these two ratios as parameters to CGAffineTransform to get an adequately scaled affine transformation matrix (i.e. transform). We then call applying(transform) on our outputImage to get the following result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_o4eOrRGBc1BitnKrtSnA.png" /><figcaption>Finally, we have a usable QR code image!</figcaption></figure><p>Another thing we could’ve done during our QR code generation is set the value for error correction. This is done via the key <strong>“inputCorrectionLevel.”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*vqROGOTJc2wr0Seeg9UTHQ.png" /><figcaption>Similarly to how we’ve used setValue for <strong>“inputMessage,”</strong> we call setValue to pass a value to <strong>“inputCorrectionLevel”</strong></figcaption></figure><p>This parameter controls the amount of additional data encoded in the output image to provide error correction. It is equal to <strong>“M”</strong> by default, and <strong><em>changing this parameter affects the resulting QR code shape</em></strong>. Higher levels result in larger output images but allow larger areas of the code to be damaged.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lNXLavpLlzqGCmDtToXepg.png" /><figcaption>Here you can see the effects of using different input correction levels. <strong><em>Note</em></strong>: we have not changed the data input (string)</figcaption></figure><p>That’s it for the basics! You have now mastered QR code generation in Swift.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*F6ICIQS_gA7esYaSP5CXKg.gif" /></figure><p>There’s a lot more to QR codes in Swift, but this is it for our tutorial. Thank you for reading this simple overview of QR generation in Swift!</p><p>Here are some useful references:</p><ul><li><a href="https://developer.apple.com/reference/coreimage/cifilter">CIFilter - Core Image | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/library/content/documentation/GraphicsImaging/Reference/CoreImageFilterReference/index.html#//apple_ref/doc/uid/TP40004346">Core Image Filter Reference</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63d7222aa011" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>