When I try the code you suggested.
try "Hello Cruel World!".write(to: wrapperURL, atomically: false, encoding: .utf8)
I get the permission error. However, I was inaccurate in my comment about wrapperURL. The wrapperURL variable removes the .epub extension from the location URL from the file exporter or save panel.
// location is the URL from the file exporter or NSSavePanel.
var wrapperURL = location
wrapperURL.deleteLastPathComponent()
wrapperURL.appendPathComponent(location.lastPathComponent
.replacingOccurrences(of: ".epub", with: ""))
When I replace wrapperURL with location in your example, the file permissions error goes away.
try "Hello Cruel World!".write(to: location, atomically: false, encoding: .utf8)
If I write the wrapper using the location,
try mainDirectory.write(to: location, options: [], originalContentsURL: nil)
The file permissions error goes away, but the file wrapper is empty.