benwiggy
benwiggy

Reputation: 2749

Xcode: how to create instances of views and pass info to them?

I'm trying to create a MacOS app that plays audio or video files. I've followed the simple instructions on Apple's website here

But I want to use the File > Open menu items to bring up an NSOpenPanel, and pass that to the View Controller.

So presumably, the Open action should be in the AppDelegate, as the ViewController window might not be open. And then pass the filename to a new instance of the ViewController window.

Is that right? If so, how do I "call" the View from AppDelegate?

Here's the AppDelegate:

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBAction func browseFile(sender: AnyObject) {     
        let dialog = NSOpenPanel();
        if (dialog.runModal() == NSModalResponseOK) {
            let result = dialog.url // Pathname of the file

            if (result != nil) {

            // Pass the filepath to the window view thing.
        } else {
            // User clicked on "Cancel"
            return
        }
        }
    }

and here's the ViewController:

class ViewController: NSViewController {
    @IBOutlet weak var playerView: AVPlayerView!  
        override func viewDidLoad() {
            super.viewDidLoad()

            // Get the URL somehow
            let player = AVPlayer(url: url)
            playerView.player = player
        }

Upvotes: 0

Views: 379

Answers (1)

Ivan I
Ivan I

Reputation: 9990

There are some details not disclosed in your question, but I believe I can provide the proper answer still.

You can call NSOpenPanel from AppDelegate, nothing wrong with that. Just note that user may cancel the dialog and how to handle that situation.

Considering the view the best thing is to create WindowController that is connected to the ViewController (it is like that by default) in the Storyboard, then access it from the code using NSStoryBoard.instantiateController(withIdentifier:), and then use its window property with something like window.makeKeyAndOrderFront(self) . If you have NSWindow or NSWindowController class in your code then you should initialize the class in the code and again make window key and front.

Upvotes: 1

Related Questions