Storyboard Advice

It’s a couple years old, but UIStoryboard Best Practices still has good advice.

I’m trying to use storyboards for the first time. At first I had one big storyboard that was really hard to work with, even on a 27" screen. Now I’m breaking it up into separate storyboards.

Testing Singletons

The iOS Unit Testing blog, in Testing Singletons, suggests making singletons by choice — not enforcing singleton-ness by overriding allocWithZone or init.

Agreed. Good practice.

App Store Improvements

David Smith has good ideas Towards a Better App Store.

I’m worried about a possible future where the only way to make money (outside of the super-rare mega-hit) is with 1) websites with recurring revenue and 2) Mac apps sold outside the Mac App Store.

The iOS app, in this future, would be a checklist item. Something you have to make but that doesn’t directly make money.

The problem with that future is that making a good iOS app is expensive and takes time. If quality can’t be justified with revenue, then quality will suffer.

(There are some people who’d argue that this future is already here.)

A better App Store would mean (by definition) that quality apps do better. And the future I worry about could be avoided.

NSNotificationCenter and Threads

Lap Cat Software: NSNotificationCenter is thread-safe NOT.

(Via Michael Tsai.)

I have a simple rule: posts notifications on the main thread only.

That’s not a guideline — it’s a rule. No exceptions.

Mobile Services and Blob Storage

This is a quick write-up of how I got this working.

Here’s the situation:

  • I want to store images and other binaries in Azure blob storage (which is like Amazon S3) rather than in a SQL database or NoSQL table.

  • I want the client to upload directly to blob storage — I don’t want the image data to pass through the API server.

I struggled with this. For a while I was looking at the REST API and building a SharedKey. It wasn’t until I found Chris Risner’s page on this from last year that I found what I needed. (Thanks tons to Chris for writing this up.)

So this tutorial exists in case you’re in the same boat.

I’ll assume you already have a Mobile Service and know how to set up custom APIs. I’ll talk about the server side mostly, since you already know how to use NSURLSession and friends.

Get a blobService

Set up a storage service if you haven’t already. (New > Data Services > Storage.) A storage service is NoSQL table storage, queues, and blobs.

Add the storage service’s name and primary access key to your Mobile Service’s key storage (see the Configure pane, under app settings). Key names such as BLOB_ACCOUNT and BLOB_ACCESS_KEY are fine. Whatever you want.

In your code:

var azure = require('azure');

The azure module is available without you having to do anything. Just require it to use it.

The azure module gets you a blobService:

var blobService = azure.​createBlobService​(accountName, key, host);

accountName and key should come from your Mobile Service’s key storage — request.​service.​config.​appSettings.​BLOB_ACCOUNT, for instance.

The host is accountName + '.blob.core.windows.net'.

Whenever you’re going to do something with blob storage, get a blobService.

Creating a container

blobService.​createContainerIfNotExists​(containerName, function(err)…

This creates a private container. (You can create public containers too, but that’s outside of the scope here. It’s easy, though.)

Listing files

blobService.​listBlobs​(containerName, function(err, results)…

The results are in JSON. You could return those to the client, or filter them to just filenames or whatever the client needs.

Deleting a file

blobService.​deleteBlob​(containerName, filename, function(err)…

Uploading

Here’s the fun part. You don’t want the image binary to go through the API server. Instead, the API server generates a temporary shared access URL that will allow the client to upload directly.

First use createContainerIfNotExists. (I assume you have some way of deciding what the container names should be. They could be based on a person’s user ID, for instance. Depending on the security needs of your app, it may be a good idea to hash the container names, so they’re not personally identifiable.)

You need a sharedAccessPolicy.

var sharedAccessPolicy = {
  AccessPolicy: {
    Permissions: 'w',
    Expiry: azure.date.​minutesFromNow(5)
  }
}

Then you generate the URL to return to the client:

var sasURL = blobService.​generateSharedAccessSignature​(containerName, filename, sharedAccessPolicy);
var accountName = request.​service.​config.​appSettings.​BLOB_ACCOUNT;
var urlForUploading = 'https://' + accountName + '.blob.core.windows.net' + sasURL.path + '?' + qs.stringify(sasURL.queryString);

(Somewhere above this you need var qs = require('querystring').)

Return this URL to the client.

The client can use an NSURLSession​UploadTask. Use the PUT verb. Add Content-Type and Content-Length headers. (It’s a good idea to add Content-MD5 too, but not required.)

Downloading

It’s almost exactly the same as uploading, except that sharedAccessPolicy​.AccessPolicy.​Permissions is 'r' instead of 'w'.

I have the server respond with a redirect to the URL.

That’s it. Pretty easy.

Glassboard Design Review

Jared Sinclair looks at Glassboard’s design:

When starting a new design project, the hardest part is finding the project’s voice. There are no easy solutions, and more than one right solution. You discover the voice through a repeating cycle of experimentation and refinement, one following the other, over and over. You try lots of things that turn out to be dead ends. With time and effort you accumulate enough familiarity with your project until one of the possible paths seems obvious.

Atom XHTML Content Considered Jerky

Dr. Drang writes about varying support for Atom’s content type="xhtml".

I strongly disliked this part of the Atom spec.

The thing about this feature is that the HTML tags are included as naked tags in the XML. That is, they’re not escaped or placed in a CDATA section.

From the good doctor’s example:

<content type="xhtml" xml:lang="en-US" xml:base="​http://lancemannion.typepad.com/​lance_mannion/">
<div xmlns="​http://www.w3.org/​1999/xhtml"><p><em>Barnes & Noble. Thursday. April 17, 2014. Six forty five p.m.</em></p>…
</content>

Just look at it. This feature is a giant invitation to screwed-up feeds. The HTML — which is probably a blog post, typed by a human — has to be valid XML. People writing scripts to generate these feeds have to make sure they can turn that HTML into valid XML.

Feeds are already screwed-up often enough. This could only make it worse.

The second issue: how can a parser handle this? What an RSS/Atom parser really wants is everything between <content> and </content> as a string.

I remember writing this code for NetNewsWire, which still supports this feature. (I checked. I have no idea if they’ve touched my code or not.)

I’m going from memory, but I’m pretty sure this is what I did.

NetNewsWire used libxml2’s SAX parser, which meant it gets called when the XML parser encounters the beginning and end of a tag and when it encounters a range of characters. There was no easy way — that I know of; correct me if I’m wrong — to tell the parser to treat everything inside a tag (<content> and </content>) as a string when there are XML tags inside that tag.

So I wrote the Atom parser to rebuild the HTML. It maintained a string and pushed stuff on it. If it encountered a tag and (optionally) attributes, it would create a string version and push it. When it encountered characters it would push those. When it encountered the end of a tag it would create a string version and push that. Once the </content> was reached then it had the entire string.

The end result was equivalent HTML, but not necessarily character-for-character the same, since little things like quote characters could change.

It worked. But boy was I coding angry that day.

PS Luckily I didn’t see this feature used very often. Still had to write the code, though.

PPS I still wonder if there’s an easier way. (Using a SAX parser. No way would I give up SAX. Performance and memory use considerations require SAX.)

PPPS For a great list of other ways feeds get screwed up, see Brian’s Stupid Feed Tricks.

Azure SQL Server Command Line

Database stuff is easy using Mobile Services — it’s a piece of cake to do almost everything you need via the browser or via the Azure command line.

Almost everything. It’s great until you hit the things that aren’t supported. Then, well, then there’s this weird browser-based SQL Server portal you could use.

But that’s not true anymore. Now there’s sql-cli, a Node module that provides a command-line interface to SQL Server. It’s so much like using the sqlite3 command-line interface that I’m at home right away. (It’s written by Hasan Khan, who’s been a huge help. Just about daily, lately.)

UIActivityViewController and Things

NSHipster looks at UIActivityViewController, introduces IntentKit (which I hadn’t heard of before), and reminds us to hope for remote view controller APIs.

App Camp For Girls in Seattle

App Camp For Girls is coming to Seattle. Cool news for my town.

CocoaRadio One

I’m on episode one of Justin Williams’s new podcast CocoaRadio. We talk syncing.

[Sponsor] Microsoft Azure Mobile Services

Mobile Services is a great way to provide backend services — syncing and other things — for your iPhone, iPad, and Mac apps.

If you’ve been to the website already, you’ve seen the tutorials where you input code into a browser window. And that’s an easy way to get started.

But don’t be fooled: Mobile Services is deep, too. A mobile service is a Node.js site, and you can write JavaScript in your favorite text editor. Deploy via Git. Write unit tests using Mocha. Administer via the command line. All on your Mac.

You can get started today with a free trial.

Vesper Sync Diary #15 - Server Testing

I don’t write many tests as I go along, because I know I’ll change the design and do a bunch of refactoring. Tests would have to be rewritten and rewritten again.

I like the idea of test-driven development, but in practice it means more wasted time than I’d like. (For me. I’m sure it works great for other developers, but not every developer’s the same.)

I just ran cloc on the API server. It’s 1,545 lines of code. It’s small, which I take as a good thing. By the time I’ve finished writing tests it should be closer to 3,000 lines of code.

(If writing a Mac app is like writing a novel, and writing an iOS app is like writing a short story, then writing an API server is like writing a poem. It has to be compact, and every line has to have a reason to be there and has to do its job perfectly. In an iOS app you can slightly screw up an animation somewhere and just fix it later. On the server nothing can be slightly screwed up.)

My process

First step is to go through every single file and add all the easily-testable functions to a to-test list. That’s most of them.

As I’m going along I find some small refactorings that can be done that will make more things testable, so I jot those down and then do those after going through all the files. And update the list of functions to test.

Next step is to write the tests — using Mocha — from the ground up. Do the low-level simple utility routines first.

(I used Josh Twist’s post on unit testing Mobile Services scripts to help me get started.)

Live tests

Unit tests are indispensable, but there are two issues:

  • They don’t actually hit the server itself.

  • There are some things that are very difficult to test — because they need all the context of the server.

For instance, it’s easy to test the logic for merging notes, but it’s hard to test end-to-end — sending some notes to the server and making sure they really end up merged and stored in the database.

I’ve been thinking about what to do here and I don’t see any existing frameworks that fit the bill. (Tell me if I’m wrong.)

So here’s my thinking. I’ll write code in the client app that calls the server and runs tests with some test data. Ideally these would be XCTestCase tests — with special junk for doing async tests — but if that doesn’t work, if it’s a special configuration of the app instead, I won’t stress about it. (Well. Weeeeell. I might stress about it. And bang on it until it works. Because it really ought to work. It bugs me so much that XCTestCase doesn’t have built-in support for async tests.)

This is made just a little more complex by the fact that I want to run tests against both the production and staging servers. That’s a small complexity, though. The bigger thing is the code to set up the environment on the server so that it can run the tests.

Here’s what I like, though: every line of code is testable. All the logic is testable. This is so different from client apps, where it’s hard-to-impossible to test everything.

Given the complete lack of margin for error, given my need to not constantly worry about the server, this is a wonderful thing.

PS I counted. First step is to write unit tests for 53 functions.

Scaling and Performance

In the recent Accidental Tech Podcast John Siracusa pointed out that I had talked about scaling when I was really talking about performance.

John’s right, and I know better.

In the vernacular sense of scaling the two things are related, but I should use more precise language.

So I’ll be more precise: my main goal is to maximize performance and minimize the amount of resources used. My second goal is to design so that I have scaling options if needed.

(Performance is related to scaling only in the sense that it lessens the need to scale, but it doesn’t solve the problem of scaling itself.)

Here’s what I’m doing for actual scaling:

  • Using a system that allows for multiple web servers to be automatically created as needed.

  • Using a SQL Server database with a maximum of 150 GB.

  • Using blob storage for binaries (images), which can scale forever (presumably).

The weakest link here is, I think, the database. If I have to, I can split up the data into separate databases. There are just four tables — accounts, deletednotes, notes, and tags — and each of those could be moved into a separate database. (There are no joins and no foreign key constraints.)

I don’t expect to ever come anywhere near doing that, so I’m not actually planning the migration steps. But it’s in the back of my head that there’s a non-zero probability.

And if I have to go even further, I can. The biggest of the tables, by far, is the notes table. I can break that table out into separate databases, separated by userID. (Which is an integer. Each database would store notes for a range of userIDs.)

And, if that’s not enough, the remaining tables (accounts, deletednotes, and tags) could also be broken out the same way.

I don’t think I’ll ever have to do any of this — but I can, if I need to, with only small code changes.

The web server may also be a weak link. The way to solve this one — not that I think I’ll need to, because I can run a bunch of instances of the server — is to create separate API servers. Each endpoint could be a separate server with its own set of instances. This would require a small code change on the client, but I’d see this coming and make sure it gets done in plenty of time.

PROCEDURE

Check out the code listings in More Macintosh Toolbox (for instance) for a reminder of the role Pascal used to play in our world.

Pascal’s cool.

Craig on X 10.10

Craig thinks Helvetica Neue will be the next Mac system font, and suggests you start testing your apps with it now.

IAC on iOS

Check out GCDWebServer. (Via iOS Dev Weekly, which you should subscribe to.)

GCDWebServer is an embeddable and lightweight http server for Mac and iOS. On iOS it runs as a background task — it keeps running even when your app isn’t in the foreground.

Picture this: app X wants to send some data to app Y.

App Y is running GCDWebServer, so app X wraps up the data as JSON and talks to app Y via http. Just as if it were talking to some server on the web, only it’s a local app.

Update 4 pm: Or not. I’m not sure it’s possible, or maybe just not allowed, to keep a network server running when the app is in the background.

Quartz Composer + Snapping Scroll

Two tutorials from Dawid Woldu fascinate me. I keep wanting to make time to get into Quartz Composer.

The Science Behind Snapping Scroll – Part I: Dragging

The Science Behind Snapping Scroll – Part II: Animation & Logic

Quartz Composer isn’t included in Xcode these days, but you can still download it from Apple. (Find “Graphics Tools for Xcode.”)

Node + MongoDB + iOS

A two-part tutorial from Michael Katz is a good place to get started writing services. Node makes a great API server. And it’s fun.

How To Write A Simple Node.js/MongoDB Web Service for an iOS App

How to Write An iOS App that Uses a Node.js/MongoDB Web Service

The tutorials use MongoDB. I haven’t had a good reason for a NoSQL database myself lately — but my early career, back in the ’90s, was all about schema-less databases, and I have a major soft spot for them.

(I’m digressing now.)

Frontier’s database was a hierarchy of tables. Each table could contain anything, including other tables — including even your scripts.

To run a script named myScript inside the bar table which was inside the foo table, you’d write foo.bar.myScript(params).

If that script took a string as a parameter, say, you could use a local variable or reference any string anywhere in the database: myApp.data.settings.username, for example. This was all presented with a user interface, navigable and editable.

I haven’t seen a database like that anywhere else since then. So easy and intuitive. Great for productivity. (It was within this laboratory that such things as templated and scripted websites, blogs, RSS, OPML, and XML-RPC were invented and/or fleshed-out.)

Web, Money; App Store, No Money

Subvert: Why we chose to build our core software business on the open web instead of on a closed app store platform:

More so, unless you have huge sales volumes, it’s near impossible for a company selling $2.99 apps (our lowest cost product and a fee which, in the app store world, is considered wildly exorbitant) to make enough money to support their team, pay for office space, keep up to taxes, cover fees and look after all of the financial requirements that it takes to run a real business.

What is making money for them? A web app.

We’ve done next to zero promotion of this software-as-a-service (SaaS) product since we started building, using and supporting it two years ago. Instead, we’ve been slowly adding to the system, improving the platform and signing up paying customers on a regular basis. As a result, the product has been making money — real money — and long ago surpassed the combined revenues of our other commercial software applications in a big way.

I’m not sure that the choice is between web apps and app store apps — I think it’s actually about standalone apps versus apps-plus-services. But, still, read the post.

Archive