UIDocument and iOS 9

After updating Trail Wallet to Swift 3, I started getting crash reports from devices still running iOS 8 and iOS 9. Unfortunately, they were super unhelpful crash reports like this:

Crashed: UIDocument File Access
EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x000000005e30c493

Clearly, it was something to do with the backup system I’m using to save the daily backups of user’s data. Unfortunately, the stack trace didn’t give many hints on the exact operation on UIDocument that was causing the problem but I eventually tracked it down to the save operation on the UIDocument subclass.

contents(forType typeName: String) throws -> Any

It turns out that, in my enthusiasm to update everything to Swift 3, I had started returning the new Swift 3 Data struct from this method in my subclass. iOS 10 deals with this just fine, but 9.3 and earlier are expecting an NSData object and die violently when they don’t get it.

Updating the return statement to NSData(data: dataForSaving) made it (and me) happy again.