Archive for October, 2015

Printing Playground Documents #swiftlang

Damian Esteban (@estebanrules) writes: In relation to Swift and PDFs, is it possible to “print” a Playground with markup rendered to a PDF or Postscript file? I could have sworn it used to work fine for me, but lately when I’ve done it, the markup doesn’t show in the PDF.

Xcode’s ability to create and present multi-page rich-text playground documents is one of its stand-out features for Swift development. These playgrounds enable you to document APIs, teach algorithms, and more, all within the scope of a standard Xcode window.

Unfortunately, in Xcode’s current state, you cannot print a playground. A playground that looks like this:

Screen Shot 2015-10-31 at 3.13.34 PM

Prints output that looks like this:

Screen Shot 2015-10-31 at 3.14.13 PM

All the nice formatting and text disappears and you’re left with raw code.

There is a way around this although it’s not particularly nice. Simply put, you can write an Xcode plug-in that renders the fully expressed playground timeline scroll view instead of code. Here’s what that looks like:

Screen Shot 2015-10-31 at 3.15.48 PM

And here’s the code that I used to build the plug-in. The rest of the work is left as an exercise for the reader but it basically goes like this: find an Xcode plugin template on github, add a menu item, add its implementation, add the Xcode UUID, install, run.

- (void) printTimeline
{
  NSWindow *window = [NSApp mainWindow];
  NSArray *subviews = 
    allSubviews(window.contentView); 
    // recursive descent

  for (NSView *view in subviews) {
    if ([NSStringFromClass([view class]) 
     isEqualToString:
       @"IDEPlaygroundSourceTextScrollView"])
    {
      NSScrollView *scrollView = 
        (NSScrollView *) view;
      NSPrintOperation *printOperation = 
        [NSPrintOperation printOperationWithView:
          scrollView.documentView];
      NSPrintInfo *printInfo = 
        [printOperation printInfo];
      printInfo.horizontalPagination = 
        NSFitPagination;
     [printOperation runOperation];
     return;
   }
 }
}

Setting up your new headless Apple TV Development unit

When it comes to tvOS development, you don’t need a separate TV on your desk. Your best development set-up is already there for you on your main computer. Sure, there are a few weird “headless” set-up tasks where you kind of have to rely on faith and blind clicking but you can set up your system pretty easily and reliably without struggling with an extra monitor.

Before you start

Before you start: Make sure you have a USB-C cable to connect to Apple TV unit your computer. These cables are not included in all Apple TV boxes, so prepare in advance. You’ll also need an Apple TV remote of any generation and a recent iOS device.

I recommend using old-style Apple TV remote — you probably have a bunch already on hand. Setup goes smoother with these, and they’re ready to use without charging and pairing.

CSma4CGUYAAVIex

Just plug in your new Siri remote to charge somewhere with a lightning cable and get down to real work with an older remote. Remember: You do need to maintain line-of sight with IR remotes.

Going Headless

Originally, I set up my system to pass through an HDMI converter and then into Elgato’s EyeTV HD. This is a pretty bad solution as there are significant delays in presentation. Every time I click my remote, I’d have to wait for a full second before I could see the result of that interaction.

EyeTV HD does not support 1080p and there’s a bad bug in the early Apple TV 4th gen that doesn’t “remember” 720p settings. It keeps switching back to “Auto”, which means back to 1080p. My radar has been closed as a duplicate. So it isn’t just me.

QuickTime Player offers a better approach. Just keep your Apple TV connected through USB-C. It takes several steps to get this set up properly but feeding your Apple TV through QuickTime Player not only lets you skip extra monitors on your desk, it enables you to take screenshots and record usage videos. It’s super handy.

Most modern monitors (assuming you’re not working on an iMac) provide multiple HDMI-in ports. If available, you can use these during Apple TV set-up to see what’s going on onscreen. Consider using your display’s picture-in-picture features to multi-share your screen.

Using QuickTime requires that Apple TV’s HDMI port is connected somewhere. As @Rizwan noted on Twitter: “Not rendering UI for me as headless after setup on TV, unless HDMI active. No screenshots either.” So make sure that the HDMI port is connected. Mine always was throughout the entire dev preview period and it didn’t occur to me to disconnect to check in my initial  write-up, which I’ve updated in-place several times.

When available, you can always just throw the other end of an HDMI cable onto a spare port on the back of your display. The HDMI doesn’t have to actually be viewed just connected. You can also use a headless dongle that pretends to be a display to ensure your Apple TV is set up for dev use:

Connecting to a spare HDMI port on your monitor allows you to switch over to full-screen TV mode if you’d like. I should note, however, that from a consumer point of view, the 4th gen model is still greatly lacking in usability. I keep a 2nd gen next to my 4th gen and use it to watch movies because the 4th gen just isn’t up to the task.

Once you’ve got the HDMI port bit sorted out, you’re ready to get going.

Restoring

Restore your device in iTunes. It helps to download the new firmware and put your device into recovery mode. (Press menu and play-pause until the white light repeatedly blinks) Option-Restore and select the firmware.

Here’s a quick reference to the old-style buttons from iClarified:

42501

Activating

Once restored, your device needs to be activated. It’s easiest to do this with your Apple TV connected to a TV of some kind, however it is not at all required. I’ve become something of an expert at setting up my Apple TV without seeing it. Here are the steps I take.

First, enable bluetooth on a recent iOS device (I use a 5th gen iPod touch). Unlock it, place it on top of your Apple TV with the screen visible to you and the auto-lock disabled or set to a long timeout. Newer devices can simplify the Apple TV setup process and enable you to “type” on an iOS keyboard instead of the horror of using an Apple TV remote.

Gently press the main “OK” button on your remove (this varies by remote. I used an old silver model, where it’s at the top inside the round controls.) Repeat and wait. If memory serves, the first click selects “English” as the dev language, and the next few clicks select similar agreeable default settings.

At some point (after about 4-6 clicks or so), your iOS device will ask you if you want to set up your Apple TV because you’ve chosen to set up using a device. (Versus setting up manually with an Apple TV remote.)

Go ahead and perform all the steps to set up your iCloud account, App Store account, etc on the iOS device — don’t stray too far away from the Apple TV unit. Continue until your iOS device stops asking your for passwords and first born children.

My new-style Siri remote is a piece of crap and won’t hold a charge. I’ll be replacing it soon. Unfortunately, while I was planning on getting a few extras for better multiplayer testing, I’m now told that’s not going to be a possibility.

Moving to Xcode

In Xcode, you should now be able to open the Devices tab and take screenshots. (Until this point, you could not because the device was not activated).

Screen Shot 2015-10-30 at 5.35.30 PM

There are still several steps before you can start using Apple TV. Take screenshots and respond on your remote to each step, which will include enabling location services (why not?), enabling Siri (do it!), enabling the screensaver (lots of bandwidth), sending diagnostics (yes), sending analytics (your call), agreeing to terms and conditions (you gotta).

Screen Shot 2015-10-30 at 5.08.28 PM

Once you finally see the main menu on a screenshot, launch QuickTime Player.

Screen Shot 2015-10-30 at 5.08.43 PM

Moving to QuickTime Player

In QuickTime Player, select File > New Movie Recording. From there, select your Apple TV  as the camera and microphone.

Screen Shot 2015-10-30 at 5.09.37 PM

Your Apple TV unit should now be live and usable. You’ll probably want to hop into Home Sharing and get that set up. Don’t forget to use the “press-and-hold” shortcut to move between regular and caps letters when entering your password. If you’re using your Siri Remote, you’ll probably need to pair it so don’t freak out when Apple TV doesn’t respond to any of your interactions.

Screen Shot 2015-10-30 at 5.59.23 PM

Move your cursor away from the QuickTime screen to view the content without the QuickTime overlays shown in this screenshot.

You won’t be able to play and record movies because the QuickTime rendering doesn’t do HDCP copy protection stuff, but since this setup is primarily to enable application development and testing, that shouldn’t be a problem.

Congrats and welcome to the world of tvOS dev!

Review: Crayola Color Studio HD+ and Crayola Light Marker

Print Job

Middle child and I were at the dollar store earlier this week. It’s fall break and we were feeling antsy and rich, with dollars in our pockets and hours to kill.  So we picked up one each of Crayola’s Color Studio HD+ and Light Marker products for a cool buck each (originally priced at $29.99 and co-branded with Griffin).

After returning home and putting these technologies to the test, we quickly figured out why they had been discounted down to a buck each.

They kind of suck.

The Light Marker app (free) uses your iPad’s onboard camera to look at a colored flashlight, letting your little artistic prodigy draw pictures from a foot or two away from the canvas. I’m not joking here. The child waves the flashlight in a dim or dark room, and with luck, manages to “draw” images to the screen.

It’s a terrible user experience and a terrible app.

However, it’s not nearly as bad as the unusable Crayola ColorStudio HD+ with stylus. This “stylus”, believe it or not, works by emitting a high pitched irritating pulsing beep, which the iPad tracks and triangulates to figure out where the “stylus” is on-screen. It also has a hideous color-changing light-show on the side of the “stylus”.

You have to push really hard to get the iPad to recognize the interaction. My daughter is way better at this than I am, and she drew the magnificent inspired art work at the top of the post.

Both apps are shortly going to be trashed.

As for the products, the Light Marker stylus is of moderate use in that it is, in fact, a flashlight, so can be used as a flashlight. The HD “stylus” will be in the trash shortly as it gave me a headache during use and its only good feature seems to be that it…no…never mind. It doesn’t have a good feature.

However, hidden within the packaging of the Light Marker is a damned fine iPad stand that we *loved*. Well worth that $1, this collapsable stand has rubberized footers, a solid build, and can not only be used with the intended iPad, but also pretty much every iDevice and Kindle we could throw at it — regardless of width and case. It folds down to almost nothing but is strong enough to throw into a backpack or purse.

Photo 10-30-2015-15.44.29

I’m probably going to go back and buy a few more Light Marker packages because this stand is awesome.

To summarize: both products are crap, not worth $1, let alone $30. Given the ubiquity of $1 tablet styluses at the dollar store, it’s not as if they couldn’t have just packaged a decent toddler-appropriate stylus. This is a perfect example of people trying to be too clever and not at all practical when putting together a product.

However, if you have a Dollar Tree near you, head on over and buy some of these stands. I loved ’em.

Update: Compared to my beloved Two-Hands stands, this is nothing to write home about. Not nearly as stable, won’t move with the device when you pick it up, can’t adjust the angle with exact precision etc. BUT unlike the Two Hands, this cheapy stand can handle Kindle (Two Hands ends are too thin), thick cases (same problem), phones and ipod touches. I’ve been using this all afternoon for plopping testing devices into. If you’re looking for the ultimate iPad stand, stick with the Two Hands. For throwing testing devices onto, this is great.

Converting the Swift Programming Language to PDF

An updated approach.

  1. Go to ~/Library/Containers/com.apple.BKAgentService/Data/Documents/iBooks/Books.
  2. Once there, locate the 881256329 epub folder. You must use a non-beta version of the book. Beta versions are DRM’ed. If your version appears to be DRM’ed (a holdover from the beta period), delete it in iBooks and re-download.
  3. Copy this epub folder to your desktop. Remove the epub extension, zip it, rename to epub. Apple uses a non-standard epub format, and these steps transform the book back to something Calibre can import and convert.
  4. Drag this epub into Calibre.
  5. Click Convert books, choose PDF.
  6. In Page Setup, select default output profile, set margins to 72 on each side
  7. In PDF Output, add printable TOC.
  8. Click OK and let the conversion start

Result:

Screen Shot 2015-10-28 at 4.34.56 PM

What makes good code

Got an email recently asking: “What makes good code?” I was a bit sick at the time, so I rambled the following off the top of my head as quickly as I could before taking some Advil, decongestants, and expectorants and then lying back down. Now, in somewhat better health, I thought I’d share these thoughts because I feel they’re an interesting starting point for an important discussion. At the time, I wrote:

It’s probably easier to ramble by phone because I’m currently under the weather but off the top of my head, here you go:

  • Good software code doesn’t just compile, it communicates. It talks to you as a developer here and now and to future you, who will be maintaining this code. It is comprehensible to your team and to anyone who will look at it externally.
  • It always chooses reliable and testable over clever, and prefers to take an extra step or ten if needed to make its intent and outcome clear.
  • It’s code that thinks about scale, about living in a forest as well as being a single tree, and being run a million times at once as well as once.
  • It’s code that believes in being broken down into sensible units instead of massive single implementations.
  • It’s code that understands that it will be implemented not once or twice but reviewed and refactored to be the best and most robust implementation possible.
  • It’s code that thinks globally and provides hooks for many cultures and multi-abled users, which is a real code-level thing — how you add internationalization and accessibility and not as an afterthought.
  • It’s code that thinks about not just the specifics of the destinations it will run on today but how to adapt for when those destinations change over time. 

That all said, what are your feelings on what makes good code and what would you add to, remove from, or modify in my initial list? I’m looking forward to hearing what you have to say.

Update:

Seivan Heidari suggests: It’s code that exposes externally-consumed APIs without sharing internal implementation details.

Anonymous suggests: It’s code that ships. Good code works, does what I need, is delivered on time, and the rest of these points be damned.

Dave DeLong: Great code leaves you in awe and inspired to go write your own great code.

Paul Cantrell: It’s code that strikes a mindful balance in all the tradeoffs these other bullet points imply. It sees engineering tradeoffs, not dogmatic absolutes. It doesn’t let tools or techniques become in-group status markers.

Rainer Brockerhoff: It’s code that I can easily reuse (often years later) and which can be extended/adapted in a few lines.

Playground Secrets now available on Leanpub #swiftlang

CoverPlayground2bscaled

With the help of 梁杰, I got the most recent version of Playground Secrets uploaded to Leanpub last night. Leanpub offers a promising commerce platform for in-progress and completed books.

  • The book has its own web page to visit. You should be able to now order a copy of the book from China and other regions of the world that do not have access to iBooks.
  • Structured Documentation is also available and includes the 1.1 updates that just went live in iBooks.
  • Playground Secrets is also relisted and available on Amazon.

I’m not going to submit Structured Documentation to Amazon for a while as the content may keep changing and Amazon does not allow updates the way Leanpub and iBooks do. I consider the Playgrounds book to be fairly stable and do not expect major updates for some time.

If you’re still left out and unable to purchase, please let me know so I can keep working on this. Let me know the country and what resources are available to you. Thanks!

Book Updates now available #swiftlang

Screen Shot 2015-10-27 at 9.32.21 AM

I just pushed a major revision to Swift Documentation Markup and a minor revision to Playground Secrets and Power Tips. These should now be available in iBooks.

I extend feature discussion in the Markup book, added some material mentioned in Apple’s online markup documentation (but not well supported in Xcode), and since Dave Verwer promised playground coverage in last Friday’s iOS Dev Weekly, I introduced a section about that as well. I also added a little coverage about promising third party tools.

There’s about 30% new material, so it’s a substantial bump in content. I’m extending Markup’s initial sale discount on iTunes for another week due to the positive feedback.

Once again, let me express my gratitude to everyone who has been tweeting, posting, and otherwise helping to spread the word about both Markup and Playgrounds. If you’re a blogger with an audience that’s interested in these topics, please ping me by email for a promo code if you’d like to write up a review on your site.

Today, I also got a first look at the galley’s for the Swift Developer’s Cookbook. I’m really excited about this — January seems forever away from October.

I’m back to the writing trenches, for now.

It’s Friday in #swift-lang land

Question: Hi! How can I print the name of a closure. for example. I have var super = { (item: int) -> () in print(notSureWhat)} and I want print to print “super”

So Mike Ash gives an appropriate answer: “That’s the name of a variable that happens to store a reference to that closure, not the name of the closure. The closure has no idea what variables hold references to it. In short, you can’t”

Me (because it’s Friday): I bet you could use an associated object to name a closure.

And that leads to this:

Screen Shot 2015-10-23 at 12.30.58 PM

Basically, it works like this. Using @convention(block) creates an object-based block that can be cast to NSObject. Associated objects adds a custom nameTag property that’s accessible from any NSObject instance.

It is bad and I should feel bad. I know.

Update: Improved version