Parsing HTML in Swift 3 (and RTF, etc.)

A friend of mine and I were discussing how to parse HTML and turn them into NSAttributedStrings the other day. That is to say, to take a tagged string, such as

<h1><i>This</i> is <b>NPR</b></h1>

And produce an NSAttributedString that will look like:

This is NPR

xkcd comic
*This* is HTML
  • My friend, who works at a well-known dating app startup, had a rather limited problem (no font or color variations, for example), and could hard-code much of his solution, using NSScanner to do the rest.
  • I came up with an algorithm using a struct to hold Range and NSAttributeName information, and filling those structs by extracting the information while walking through the original string using a regex pattern (something like <\/?\w[\w\d]?\w{0,9}>) to catch the tags.
  • But before we could have the fun of combining/comparing the two solutions, I had a facepalm moment, discovering the built-in methods for doing so, and wrote the following extension (below).

Apple is Wrong! (In this small way)

How should you section off your delegate (and datasource) methods? I have seen (so far) two ways that Apple does so in their templates:

  1. ‘Brief’ Format:

// MARK: - Table View

2. ‘SeparateComponentsWith ” ” ‘ Format:

// MARK: - Table view data source

What this misses:

  • Firstly, the idea of having a plain-English pragma mark does not make sense – we should not be reading the pragma marks — not when there is an immediately recognizable heiroglyph such as UISomeAPIiKnowBySight.
  • Secondly, this version…

// MARK: - UITableViewDataSource

…can be ⌘-clicked to take you to the docs and/or implementation of the API in question, which makes so much sense – put the instructions next to the tools in case they are needed.

So I change all boilerplate templates to conform their respective APIs. While those two reasons are not earth-shattering, they are compelling enough that I will not forget (or rather, can ‘re-derive’) which convention I adhere to, consistently. Consistency in coding is a very powerful contributor to readability, so sign me up.

So, who is going to let Apple know that they got this one wrong?


Book Review: The Swift Developer’s Cookbook, by Erica Sadun

240 pages, Addison-Wesley Professional, 1st ed (19 Dec 2015)


In sum, if you are a moderately experienced in Objective-C, this petite volume covers basically the same ground as Apple’s Swift Programming Language, but written in a problem-solution style, with the added value of her non-Apple perspective — oh, and did I mention that she does this all in 1/3 of the space (~200 pages to SPL’s 600+). The title “Swift for the Really Impatient” is apparently already taken, but would fit this book quite well. Highly recommended, if you’re her target audience.


Are you an Objective-C developer looking for an advanced primer to dive into Swift? Then look no further. Erica Saudi’s slim volume is densely packed with well-written code that tersely explains (a) how to do Objective-C tasks in Swift syntax, and (b) how to avoid that road, and take advantage of Swift to accomplish those tasks Swift-ly.

Those who have read her other books, such as iOS Autolayout Demystified, or follow her blog, know you are in good hands with a professional who has a deep and intimate knowledge of the inner workings of the Cocoa APIs, and like a good tour guide, can point out common hazards to avoid as she takes you on the safe path. Moreover, she provides ‘historical’ context about what came before. And throughout are little gems of humor.[1]

This book is not for everyone, but it may very well be for you. It is certainly not for fresh beginners, and it is not for someone looking to learn iOS programming or APIs. Myself, I have been programming in Objective-C for about a year now, and just completed my first Swift project when I got my hands on the book, which I saw as a time-saving alternative to scouring the tech-blogosphere and weeding out the Swift 1.x stuff from the Swift 2.x. Rather than read it cover to cover, I read the chapter I needed to bone up on, or searched the index — and in this regard, it works quite well, as a ‘cookbook’ should (though it is not really a cookbook, as I’ve seen the term used, such as in “The iOS Developer’s Cookbook” by the same author — the code provided are mostly of snippet-length).

In sum, if you are a moderately experienced in Objective-C, this petite volume covers basically the same ground as Apple’s Swift Programming Language, but written in a problem-solution style, with the added value of her non-Apple perspective — oh, and did I mention that she does this all in 1/3 of the space (~200 pages to SPL’s 600+). The title “Swift for the Really Impatient” is apparently already taken, but would fit this book quite well. Highly recommended, if you’re her target audience.

Note that this cookbook is focused on Swift, not Cocoa, as in the iOS Developer’s Cookbook by the same publisher. Double-check the table of contents to make sure it covers the topics you require.

[1] My favorite:
“Uppercase function names are immediately distinguishable from methods but are currently out of fashion. This practice was quite common up to and including name-spacing, when it suddenly went extinct. It’s like a million capitalized voices cried out and were suddenly silenced.”
(p.68 / Kindle Locations 2086-2088).

Full Disclosure: I purchased a dead tree copy of the book for my own edification. Subsequently, I was offered a free copy in exchange for an honest review, which got me the electronic version. So, to be honest, I have issues with all programming e-books and how they fail to display code in a helpful manner (read: syntax highlighting!). Dead trees win in that regard, which boggles the mind. But I love having the e-book for searching. I would buy far more books like these if there was an e/tree bundle that was *less* than, say, the price of two full copies!

Link an Existing Project to GitHub

GitHub is amazing; I am eternally grateful to be born in an age where there is free, accessible, distributed version control software (Git), that is moreover  centralized/backed up in The Ether. But there sometimes is a slight hitch: Github creates the online repository, but Xcode creates the new project. How can I create a new project in Xcode that is simultaneously tracked in its own Github repo?

How to Create a new Xcode project + GitHub repo [almost]  Simultaneously

My solution is the same as associating an existing project with an existing repo.  This is my workflow:

  1. Create the project locally.(If you don’t know, try Treehouse or CodeSchool)
  2. Create the repo on GitHub. (again, Treehouse, or CodeSchool)
  3. Copy the repo’s SSH from GitHub. GitHub BlogPost media-1
  4. Initialize the local git repo, and add the remote to the local repo.

    //git remote add origin

    //git pull origin master

    //git push -u

  5. Pull, Push.
Screen shot of my Terminal
A linked repo is born!

App Store: Quickie Privacy Policy


My second app submitted to the app store was rejected because I skipped a step that I had been diligent about with my first: the privacy policy. [UPDATE: Upon closer inspection, it was rejected because I did not explain how my app (a card trick with numbers) was appropriate for kids. They expressed additional concern over my lack of a privacy policy, but would never have noticed had I not already drawn the Eye of Sauron my way. I fixed that by recommending my app for only 13+ years.]

iTunesConnect rejection screenshot
As in life, rejection hurts, however justified.

So here is how I set up a privacy policy in under 30 minutes, which, with practice, can certainly be shortened to 10-15 min.

1. Generate a Privacy Policy

A quick Google search will find you a number of free privacy policy generators, which I prefer over templates. Make sure to add the keyword “app” to your search string, otherwise you may reach a website privacy policy generator instead. I used Generate your policy, and download.

2. Grab a Free Website

A free wordpress site will do just fine. I used Weebly, since my apps are not for marketing, but to build my portfolio.

Screen Shot 2016-01-21 at 8.45.57 PM

3. Add a “Privacy Policy” Page

…and stick your policy there. In this case, I didn’t even load the HTML, but included the file for anyone to download.

Screen Shot 2016-01-21 at 8.49.24 PM

4. Tell Apple

Cut and paste the URL into its berth on iTunes Connect. Relax by reading some tech blog posts.

Screen Shot 2016-01-21 at 8.52.14 PM


AutoLayout Equations and The Trivial Solutions that Magic Away your UIViews

The Lost Socks of Interface Builder

There are times when AutoLayout makes me think of views as socks: sometimes you cannot locate a UIView no matter how simply you laid it out the night before. It doesn’t matter if you did it programmatically or in Interface Builder, it may as well be on the dark side of the moon, or stolen by UIView Gnomes. You suspect Autolayout is the culprit, but you get nothing in the console. Nada. Silent failure. No [UPDATE: Often no] helpful remarks like:

“I’ll assume you know what you’re doing, usually, and were merely distracted by some 18th century disease — say, dysentery — when you gave me illogical and contradictory constraints. By looking or not looking at this window, you are agreeing that it was ok for me to break some of those constraints at my whimsy. Next time, try harder, or don’t try at all, buddy. And stay healthy — cholera is not covered by Apple Care.”

I have begun reading Erica Sadun’s excellent, if only slightly dated*, iOS AutoLayout Demystified. She notes what the Apple Docs say, that autolayout basically solves a system of linear equations. What…??, you ask. This is today’s nugget: you already learned the basics of solving systems of linear equations in high school, if not grade school (for those readers in grade school, read on and learn!).

*”Completely updated for iOS 7 and Xcode 5!”


tl;dr — sometimes the only solution to an equation is the trivial solution (e.g., 1 – x = 1 + x is true when x = 0). This is different than no solution (e.g., x – 1 = x + 1). In autolayout, no solution leads to a warning/crash/constraint-breaking. A trivial solution can often (but not always) lead to silent failure – a view of 0 x 0 dimensions — though in Xcode 7, the compiler has often said “You probably didn’t mean it, I’ll break one of these constraints.”



N Equations for N Unknowns

Let’s solve for x, shall we?

x = 3

Have you got it? I hope so. In this equation, there is one unknown, and we can fully solve for the variable, x. The same is true for this variant:

3x – 2 = 7

Although more convoluted, we essentially have a single Unkown, and one equation suffices to solve for it.

If we had two unknowns, however, we would not be able to do so:

y + x = 4

Indeed, the set of possible solutions is infinite, since you can pick any pair of numbers that ‘cancel out’ (for example: [0, 4], [1, 3], [-100, 104], and so on…). That set, by the by, can be represented visually (say, on graph paper) as a Line. But we can solve this:

Screen Shot 2016-01-20 at 11.42.25 AM

For the visual learners, this would be represented by taking that line (y = -x + 4) and picking the spot where = 3.

Screen Shot 2016-01-20 at 11.44.25 AM


When we presume that the x in the first equation is the very same x in the 2nd equation, we are viewing the two as a system. Put differently, the equations comment on one another. Think of Sudoko.

Su Doku, xkcd-style
Click Me for something slightly worse!

Fancy Mathy Pants

In school we learned to “plug in” the variables from one equation into the other in order to solve these (“substitution method”), and most high school math courses teach linear arithmetic (“elimination method”). But there are many sophisticated techniques for solving these equations quickly and efficiently.

[The place to start might be Khan Academy, but I am a big fan of Gilbert Strang’s course (and textbook!), now online for free from MIT (text not free ☹ )].

Conclusion: Solving for x, Solving for UIViews

What about these equations, do they have a viable solution?

x = 3, x = 4

Correct, they don’t! If those equations represented constraints, they would crash the app, or eliminate your views — or Xcode could/might ignore one of them for you, and let you off with a stern warning. And if the latter happens, heed the warning, and fix the constraints – because if you are not deciding how to place your views, who is??


How to Use Boolean Attributes in Core Data

Some Context

The data model of my current project started breaking after I versioned it to #7, rejecting my usage of Booleans. Part of my confusion was due to this selective, late-in-the-game breakage: booleans had been working fine up until now, and I hadn’t changed anything that I recall; #7 added a new transient attribute to a different entity. Shouldn’t they have been breaking from day 1?

I searched fruitlessly for “How to Use Boolean Attributes in Core Data” and variations on that theme, to no avail (excuse the redundancy).  Only after I had this explained to me in person did I realize that the answers were out there, obliquely (amongst the usual suspects: a Stack Overflow post, or this one, and in a few posts years old).

So you’ll forgive me if I broadcast and blast that phrase repeatedly, in the hopes of raising the SEO rankings for “How to Use Boolean Attributes in Core Data.” If you’re reading this, there’s a good chance you’re happy that I did. And if you’re unhappy, well, there are pills for that.


How to Use Boolean Attributes in Core Data


The Simple Way

  1. Check the “Use scalar properties for primitive data types” checkbox while auto-generating your subclasses.
  2. Grab a beer.

    "Use scalar properties for primitive values" checkbox
    The third screen in the process.

The Objective Way

  1. Instead of  YES and  NO , use  @YES  and   @NO .
  2. For control flow purposes (i.e., logical tests), call the  boolValue .



“The opposite of a fact is falsehood, but the opposite of one profound truth may very well be another profound truth.” –Niels Bohr

Do all AIBOs go to robot heaven? Do androids dream of electric sheep? Can Core Data keep track of profound truths? Yes, yes, and yes.

The limitation of scalars is that they must be, or not be, without question: 0/1, YES/NO. But opposite of ‘existence’ is not ‘death’ or ‘sadness’ or any something — it is non-existence.

In Objective-C, what indicates non-existence?  nil. If you need your attribute to have this capability, you need objects, such as NSNumber (ty CH for pointing this out).

Conversely, if you get errors with your boolean (see below), check to see if they are not actually NSNumbers. Two Things to be aware of then:

Thing #1: Setting the Entity’s value – You have added a boolean attribute to your entity in the data model, and had Xcode generate your model classes from it. You might think to code something like so:

You will probably get a warning along the lines of “makes pointer from integer without a cast.” This is because, as mentioned above, Core Data defaults to avoid booleans and other scalars, and so the attribute is stored as an NSNumber. Check your managed object header file (iOS 9: +coreDataProperties header), and you’ll see:

So instead, set the NSNumber like so:

Thing #2: Accessing the Entity’s value – In control flow statements, or wherever you are testing for the logical value of your boolean, you must always use the boolValue, because while  NO is ‘zip, zilch, 0’,  @NO evaluates to true (it exists)!

Instead, use boolValue:

Good hunting, peoples.


Favorite Xcode Shortcuts (an ever-expanding list)

This post has been a long time coming. And yet, it has not come. A shortcut here or there does not seem to merit a post entire, but the collective impact of each of these shortcuts has been of such deep and lasting workflow importance that overlooking it is surely a crime.

Solution: start the Journey of 1,000 Steps post, and add to it as new awesomeness comes to my attention.

Jumping Right In:

  • Expand/Collapse all folders/search results in the navigator panel: ⌘ + click the triangle (rather than click).
  • Expand/Collapse all curly-braced code in an editor panel: ⌘ + ⌥ + ⇧ + ← or →

My criteria, so far, include shortcuts that are part of your regular workflow, but are not [readily] visible on drop-down menus. As always, suggestions more than welcome!