Archive for the ‘Xcode’ Category

Bluetooth Lessons I: Manager and Scanning

Last June, Izzy inspired me to do something with Bluetooth and playgrounds but honestly, I haven’t had the time and I couldn’t afford a Sphereo. I’ve wrapped up Swift Style. Attempting to write meaningfully about drawing while the Denver Public School system has for reasons I cannot begin to comprehend released my child to my recognizance for two entire weeks seems unlikely. (Another child has half days. Fun.)

To prepare, I purchased one of the cheapest BLE devices I could find, a Mi wristband (Amazon cost under $20 shipped), which has a reverse engineered API that lets you control vibration. A friend of mine just purchased the hugely expensive Buzzies for Autism bands. I’m  hoping I can mimic some of that functionality with a playground, a low-rent BLE device, and a full-price child.

Have I mentioned recently how awesome playgrounds are for playing around with and learning about new tech? They really are, especially because you can integrate just one concept at a time, and then test it live before expanding to the next.

I decided to go with Cocoa for my BLE exploration instead of iOS, although the tech is more or less the same on both platforms. When you work in Cocoa, using a macOS playground, the startup speed is phenomenal because you don’t have to work with a simulator.

My first project simply sets up a central manager (CBCentralManager), monitors its state, and lists any devices it finds. I’m pretty happy for this as a first day, not many hours to spend on it, playing around and doing something marginally useful result.

The CoreBluetooth documentation is pretty dire. For example, this is the Swift docs for CBManagerStatePoweredOn.  After SE-0005, the constant is actually .poweredOn, as you see in the following sample code, not CBManagerStatePoweredOn. And there’s no documentation in that documentation.

Nonetheless, I persevered and my first child-full day produced a basic helper class. You really need to work in NSObject land for this because of all the delegation. So I set up an objc-friendly class, set it as a manager delegate, and implemented the one required callback method, which follows the manger state.

Try sticking the Bluetooth icon in your system menu bar.  (System Preferences > Bluetooth > Show Bluetooth in menu bar.) It’s a lot of fun to toggle it on and off and watch your playground keep tabs on that state.

Next, I added a basic peripheral scan. You need to scan only when the manager achieves poweredOn state.

Apple writes, “Before you call CBCentralManager methods, the state of the central manager object must be powered on, as indicated by the CBCentralManagerStatePoweredOn constant. This state indicates that the central device (your iPhone or iPad, for instance) supports Bluetooth low energy and that Bluetooth is on and available to use.”

That’s why I added the scan to the playground’s “update state” callback. You’ll want to stop scans when the BLE powers off.

Finally, I implemented one more callback, which asynchronously lists discovered peripherals. It picked up nicely on my Apple TV and when I enabled and disabled a hotspot on my iPhone. Great fun.

Here’s the code involved. You can see how very short it is. The struggle wasn’t in the lines of code or complexity, it’s mostly about how very badly documented most everything seems to be.

I’ll post more as time allows.

https://gist.github.com/erica/d249ff13aec353e8a8d72a1f5e77d3f8

Dear Erica: Playground Support Folder

“N” asks: “Hey, is the “shared playground folder” long gone, or does it still exist?”

Still there, still useful.

The big difference for long-time playground users is that it moved into the PlaygroundSupport module from the XCPlayground module. The latter was deprecated in Xcode 7. It’s a tiny module that supports playground-specific features. This constant (playgroundSharedDataDirectory) gives you a well-defined sandboxed folder that’s shared between all playgrounds.

This is, by the way, a terrible symbol name (take note!), as it returns a URL. It used to return a string but the name never got updated:

public let playgroundSharedDataDirectory: URL

I often build playground-specific subfolders so my directory doesn’t get all messy.

Another valuable feature is indefinite execution support (needsIndefiniteExecution) for playground pages that have to perform asynchronous work before completion. You can use this support to build little playground-based utilities instead of writing shell scripts.

I have some pages that work with Imgur, Google search, Wolfram queries, etc. A nice thing about building in playgrounds vs shell is that you can integrate audio and visual elements rather than having to save them to files and open them in helper applications.

If you’re writing API utilities, enable manual execution. Constant reloads can almost immediately deplete, for example, your Gist API query count for the day. Oops.

In Xcode, the shared data folder is available for iOS, macOS, and tvOS playgrounds. The shared data folder is not available on iOS’s Swift Playgrounds. This policy discourages custom local storage and access beyond standard media library locations.

There are some further protocols and types under the PlaygroundSupport umbrella in Swift Playgrounds. These aren’t available for Xcode playgrounds because they’re meant for use in Playground Books.

The extra functionality is part of Playground Book support, which underlies the tech in “Learn to Code”, etc. These additional APIs include items like a key-value data store, message passing between the live view and the primary playground page, and more.

If you want to learn more about Playgrounds, I have a book.  It discusses the features you use in Xcode and an overview of how to use iOS Playgrounds. I quite deliberately did not include much about Playground Book authoring as the topics are somewhat orthogonal.

I’ll probably be revising both Playground Secrets and Power Tips and my Swift Documentation Markup after WWDC. There’s also a three-book bundle available with Swift from Two to Three.

A few most favored Xcode text preferences

Line numbers. Seriously, how does anyone work without line numbers? They add context and reference for conversations and screen shots, especially in playgrounds. Text Editing > Editing > Show, Line Numbers

Trailing space trimming. Tidiness is godliness. Text Editing > Editing > While editing, Automatically trim trailing whitespace.  (I’ve never bothered with “Including whitespace-only lines” and vaguely suspect it would mess with indentation levels for braced scoping.)

Keyword highlights. I like the built-in highlighting feature that shows corresponding symbols after a short delay.  It’s a subtle cue that emphasizes “where else do I use this?” without having to enter “edit all in scope mode”. Text Editing > Editing > Highlight instances of selected symbol. I use a delay of 0.25 seconds, but I could imagine lengthening that so the highlights don’t appear until I’ve focused longer on a particular symbol.

Spaces. Need I say more? Text Editing > Indentation > Prefer indent using, Spaces. I’m an unabashed 4denterist. My tabs indent “in leading whitespace”. I’m not saying 2denting is bad or wrong but man can it be hard to read and interpret as visual columns. (“Would you like a pamphlet on how 4denting can save your eyes?”)

What about you? What is special about the way you’ve set up Text Editing preferences?

Xcode Tricks: Adding Keyboard Shortcuts

One of the great things about Xcode is that you can add custom keyboard shortcuts for just about any command. Two favorites enable me to toggle playground markup on and off and to run a playground on demand.

Adding shortcuts lets me run these common tasks without lifting my hands from the keyboard and selecting items from a menu. It’s a big time saver.

You establish shortcuts using Xcode > Preferences > Key Bindings.  Search for the command-name using the field at the top-right, then double click in the key field and type the key (or key-chord) you want to use.

Click away from the field after entering your selection. Don’t press return or Xcode interprets that as your requested key entry.

A red exclamation point indicates binding conflicts:

Click the red icon to jump to the Conflicts tab, which lists all keybinding issues:

Red conflicts indicate unresolvable overlaps. Yellow conflicts mean that keyboard shortcuts established in System Preferences may override the built-in bindings.

Activate the edit field by double clicking. Either replace the key binding or click the small gray circle with a minus at the right to remove the assigned key. Once resolved, conflict items leave the list.

The Customized tab list all user-adjusted key bindings. This tab enables you to review your changes in one place.

This screenshot shows both the custom F8 binding for “Execute Playground” and the customization for “Step Out” on the debug menu, which normally uses F8. I removed that to resolve the overlap, preferring F8 for playgrounds.

To revert changes, select one or more items you’ve customized and click Delete. If you want to try this out, it’s safe. Deleting key binding customizations uses Xcode’s undo stack. You can undo your reversion to recover any customization you may have accidentally removed.

Running Python in Xcode: Step by Step

As I’m preparing for a project that will involve Python programming, I need to get up to speed with at least a basic level of Python mastery. However, I’m not a big fan of using the interactive Python REPL, or whatever it is actually called:

screen-shot-2016-12-04-at-11-37-21-am

I decided to use Xcode instead, and I’m finding it a much better solution for my needs:

screen-shot-2016-12-03-at-8-31-15-pm

Here’s the steps I took to set up this project:

Step 1: Install Python 3.5

If you run python -V at the command line, macOS reports “Python 2.7.10”, or at least it does on my system. Bzzt. I want 3.5.2, which is the most recent non-beta release, and dates to June of this year.

I grabbed my installer from the Python.org downloads page: https://www.python.org/downloads/release/python-352/

Step 2: Locate python3

I use tcsh, so where python3 reports /usr/local/bin/python3. The location is surely the same for you, but I don’t know what the equivalent for where is in bash.

Step 3: Create an Xcode project

File > New > Project > Cross-platform > External Build System > Next.

screen-shot-2016-12-04-at-11-44-06-am

Enter a name (e.g. Python), and enter the path from Step 2 into the “Build Tool” line. Click Next.

screen-shot-2016-12-04-at-11-44-43-am

Navigate to whatever location you like, and click Create.

Step 4. Create a Python file

Choose File > New,  select macOS > Other > Empty. Click  Next.

screen-shot-2016-12-04-at-11-48-04-am

You should already be in your project’s top level folder. If not, go there. Name your file Whatever.py, choosing whatever name you like. I went with Work.py. Make sure the “add to target Python” box is checked. Click Create.

screen-shot-2016-12-04-at-11-49-43-am

Step 5. Edit your Run Scheme

The Xcode default should have the Run scheme selected:

cap

Click and hold on the Python target in the jump bar. Select Edit Scheme…

screen-shot-2016-12-04-at-11-50-56-am-2

The Run scheme displays, with the Info tab selected.

Step 6. Choose the Executable

I warn you now that this step is going to be delicate, fragile, and stupid. That’s because Xcode, for whatever reason, will not let you use the symbolic link at /usr/local/bin/python3. I don’t know why.

In the Info tab. Select “Other” from the Executable pop-up list. A file selection dialog appears.

cap

 

Return to the terminal. Type: open /usr/local/bin. Select python3 and control-click/right-click. Select Show Original. This will probably be named python3.5. It’s not a symbolic link but unfortunately Xcode continues to be fussy about allowing you to select it as your executable because of the period in its name. Sigh.

Drag python3.5 onto the file dialog and click Choose, if you’re allowed to. If so, great. If not, you need to work around Xcode: create a hard link and then drag the link onto the dialog.

% ln python3.5 python35

I know, I know. Ew. But it’s better than copying, or worse, renaming the file. And no, symbolic links don’t seem to work here. Better solution? Let me know.

Finally, uncheck “Debug executable”. You don’t want to debug the Python language itself.

screen-shot-2016-12-04-at-12-05-26-pm

Step 7. Add Launch Arguments

Now, click the Arguments tab. Click + under “Arguments Passed On Launch” and type $(SRCROOT)/ followed by the name of the Python file you created in Step 4.

screen-shot-2016-12-04-at-12-07-02-pm

Step 8. Test it out.

Click Close to dismiss the scheme editor. Enter a program (don’t forget all those colons and tabs) and run it:

screen-shot-2016-12-04-at-12-38-05-pm

It’s a very odd thing to be jumping into Python with a Swift background. Clearly Swift has inherited a lot of Python genes. It also feels sinful to use such lax typing without compiler oversight. That said, my first experiences in Python can wait for another day and another post. More to follow.

PaintCode releases new update and leaves App Store

screen-shot-2016-11-02-at-8-54-38-am

I’ve been a fan of PaintCode for a long time. PaintCode is a drawing and programming app that lets you move between code and rendered pictures. With it, you can create paths and fills, and then paint that information right into your app code using a variety of development languages.

Mike A at PixelCut dropped me a note last night letting me know that PaintCode 3 is now ready for release. The new version adds Android code generation, JavaScript, Telekinesis and more, in addition to Objective C and (now) Swift 3 support.

You can now use parameterized methods to draw into target rectangles. The app supports destination behaviors like aspect fit, stretch, center, etc. Although I’ve long since developed similar code for my own use, this is a great feature to add without relying on the end-coder’s expertise.

PixelCut has also made the choice to leave the Mac App Store. I’ve reached out to them to find out more about their decision.

PaintCode isn’t cheap but it’s a good tool for anyone who uses a lot of vector art, drawing, and paths in their code and they’ve been dedicated to keeping the tool current and updated. Existing customers get a 20% discount off the $99 app price.

Xcode 8 Document Coding Enhancements

Now that I’ve gotten Swift 2 to 3 ready and out, I’ve turned my attention to Swift Documentation Markup. I’m updating the book with both Swift 3 examples and markup enhancements. Xcode has added some great new features although as you’ll see there’s still work left to be done.

Xcode’s automatic doc-comment skeleton command is super handy. Move the cursor to any symbol and select Editor > Structure > Add Documentation (Command-Option-/). Xcode scans the symbol you’ve chosen and adds a doc-comment outline including named parameters and return types if they exist.

screen-shot-2016-09-16-at-10-46-30-am

You may want to add further comment features like notes, warnings, authorship, dates, and complexity details, but the basics provided by Xcode form a great place to get started.

One Xcode feature that’s just launching is support for treating closure parameters as first-class documentation elements. Xcode’s default documentation doesn’t include closure parameters, as you see in the screenshot that follows.

screen-shot-2016-09-16-at-11-06-41-am

Swift’s new “no  labels for function types” means that many developers will not include the internal declaration arguments that I use in this example for the action parameter.

By adding internal arguments like (_ line: String), you can extend your documentation. Xcode picks up and formats that information into a special closure parameter box, subordinate to the closure that uses that parameter. Here’s an example that extends the code documentation you just saw:

screen-shot-2016-09-16-at-11-09-13-am

Swift’s native comment schema suggests that Xcode could potentially add further support. The schema includes nesting parameters, return values, and throws document comments, as promised in this commit:

screen-shot-2016-09-16-at-11-15-05-am

As far as I can tell, the only feature that is currently supported by Xcode is the named closure parameters, demonstrated above. Here’s what the schema looks like from Swift’s point of view:

<!-- In general, template parameters with whitespace 
   discussion should not be emitted, unless direction 
   is explicitly specified. Schema might be more strict here. -->
  <choice>
    <element name="ClosureParameter">
      <optional>
        <ref name="Abstract" />
      </optional>
      <optional>
        <ref name="Parameters" />
      </optional>
      <optional>
        <ref name="ResultDiscussion" />
      </optional>
      <optional>
        <ref name="ThrowsDiscussion" />
      </optional>
      <optional>
        <ref name="Discussion" />
      </optional>
    </element>
    <element name="Discussion">
      <ref name="BlockContent" />
    </element>
  </choice>

Unadopted Swift enhancements don’t end there. There’s further work to be done to support changes provided by Swift but not picked up on by Xcode. Here are examples from the Swift language change log and from Swift proposal SE-0111:

  • Three new doc comment fields, namely - keyword:- recommended: and - recommendedover:, allow Swift users to cooperate with code completion engine to deliver more effective code completion results. The - keyword: field specifies concepts that are not fully manifested in declaration names. - recommended: indicates other declarations are preferred to the one decorated; to the contrary, - recommendedover: indicates the decorated declaration is preferred to those declarations whose names are specified.
  • This proposal introduces two new document comment fields, MutatingCounterpart and NonmutatingCounterpart. These replace the roles of the former mutable_variant and message arguments. Under this scheme, @discardableResultwill not use arguments. Documentation comment fields will, instead, supply usage recommendations in both directions.

iOS Playgrounds: Where is my print output?

Nate writes: “I can’t figure out how to show console output/print in the Swift Playgrounds app for iOS.”

All print output appears in the “sidebar” to the right of the code as little pop-ups:

Screen Shot 2016-06-22 at 1.11.56 PM

Embed the viewer by tapping “Add viewer” so you don’t have to keep popping up the quick view.

The hint box shown (for example “123”, or “?”, or “abc”, etc) depends on the type of item produced. The tiny cube represents an class instance.

Screen Shot 2016-06-27 at 11.40.51 AM

Like desktop playgrounds, you can view a single value at a time or tap the embedded display to select other views like List view:

Screen Shot 2016-06-24 at 12.15.27 PM

Compilation errors appear in-line for main playground code:

http://ericasadun.com/wp-content/uploads/2016/06/Screen-Shot-2016-06-21-at-11.51.25-AM.png

Sources-based errors (which  you cannot yet fix in the app) are shown as popups. When these issues occur, debug back on  your Mac before trying again on iOS.

http://ericasadun.com/wp-content/uploads/2016/06/Screen-Shot-2016-06-21-at-11.29.05-AM-535x401.png

It’s important to remember that the iOS Playgrounds app almost never is running the same version of Swift as you are on the desktop and won’t be until both Swift 3 and iOS 10 go gold.

Want to learn more about iOS Playgrounds? Read Playground Secrets and Power Tips.

Messing with Extensions: Describing color literals for the color blind

As the latest nightly build of Swift refuses to link on my system, I put together a new source editor extension. Developing these is still about as fun as having wisdom teeth pulled (actually the dental surgery would be more fun) but I’ve learned to keep a terminal window open so I can repeatedly delete derived data between builds:

Screen Shot 2016-08-03 at 11.41.33 AM

The new extension looks for a color literal on the cursor line and uses the XKCD color library to describe it.