Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active April 18, 2021 17:36
Show Gist options
  • Save steipete/dbb6b26c9c6bc5d67d5c1baa44e00b5f to your computer and use it in GitHub Desktop.
Save steipete/dbb6b26c9c6bc5d67d5c1baa44e00b5f to your computer and use it in GitHub Desktop.
If saving is too slow for you in the new SwiftUI DocumentBrowser wrapper, here's a terrible trick to make it instant. (This is new API in iOS 14; Apple might change the underpinnings to not use UIDocument, so this might fail in future updates. InterposeKit fails gracefully and worst case you end up with the save delay). FB8748779
private func speedupDocumentSaving() throws {
// SwiftUI triggers updateChangeCount: when the binding changes,
// which triggers an autosave operation to eventually store the document.
// There's no direct way to access UIDocument (used inside SwiftUI.PlatformDocument)
// to speed up this process. It is noticable as it delays changing the thumbnail.
// While saving is triggered instantly when the application backgrounds,
// we still want to update the document immediately.
//
// We could apply this to SwiftUI.PlatformDocument for a more narrow tweak.
// We could also swizzle the NSTimer initializer, check for the target being PlatformDocument
// and modify the value there (which would not be private API, still hacky tho)
_ = try Interpose(UIDocument.self) {
try $0.hook(
// This is private API, so we hide the selector.
NSSelectorFromString("otua_".reversed() + "savingDelay"),
methodSignature: (@convention(c) (AnyObject, Selector) -> CGFloat).self,
hookSignature: (@convention(block) (AnyObject) -> CGFloat).self) {
store in {
let originalAutoSaveDelay = store.original($0, store.selector)
print("Changing autosave delay from \(originalAutoSaveDelay) to 0")
return 0
}
}
}
}
@steipete
Copy link
Author

Swizzling powered by https://interposekit.com/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment