Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement NSWindowRestoration in Swift?

I tried implementing the NSWindowRestoration protocol in Swift, in a non-document-based application. However, the method restoreWindowWithIdentifier is never called at application launch. Can anyone point out my mistake?

Here is a subset of the code (which compiles and runs fine):

class AppDelegate: NSObject, NSApplicationDelegate, NSWindowRestoration {

  var windowController : MyWindowController?

  func applicationDidFinishLaunching(aNotification: NSNotification?) {
    windowController = MyWindowController(windowNibName:"ImageSequenceView")
  }

  class func restoreWindowWithIdentifier(identifier: String!, state: NSCoder!, completionHandler: ((NSWindow!,NSError!) -> Void)!) {
    NSLog("restoreWindowWithIdentifier: \(identifier), state: \(state)")
  }

 }

class MyWindowController: NSWindowController {

  override func windowDidLoad() {
    super.windowDidLoad();
    window.restorationClass = AppDelegate.self
  }
}

Thanks in advance!

like image 799
Frank Dellaert Avatar asked Nov 01 '22 22:11

Frank Dellaert


1 Answers

You need to set a restoration class and also an identifier:

class MyWindowController: NSWindowController {
    override func windowDidLoad() {
        super.windowDidLoad()

        self.window?.restorationClass = type(of: self)
        self.window?.identifier = "MyWindow"
    }
}

extension MyWindowController: NSWindowRestoration {
    static func restoreWindow(withIdentifier identifier: String, state: NSCoder, completionHandler: @escaping (NSWindow?, Error?) -> Void) {
        if identifier == "MyWindow" {
            // Restore the window here
        }
    }
}

Of course you can also let another class restore the window, like you tried. You need to assign AppDelegate.self as the restorationClass in that case.

Also, be aware that the window restoration setting now defaults to "off", for whatever stupid reason.

like image 50
DarkDust Avatar answered Dec 23 '22 21:12

DarkDust