Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

quitting xcode cocoa swift app

Tags:

macos

swift

cocoa

I have written my first swift OS/X application in XCode 6. It all works except I cannot figure out how to exit the app. I have a button to exit and the ExitNow function defined as follows:

@IBAction func ExitNow(sender: AnyObject) {     // ??? } 

I cannot figure out what the code would be. By searching online I've found various options, but they were either in Objective C or too general for me to comprehend. I would appreciate an example which would behave the same way as cmd-Q.

like image 974
Lanny Rosicky Avatar asked Aug 12 '14 21:08

Lanny Rosicky


2 Answers

You should be able to just call terminate on the global NSApp object.


Swift 4 & 5:

@IBAction func ExitNow(sender: AnyObject) {     NSApplication.shared.terminate(self) } 

Swift 3:

@IBAction func ExitNow(sender: AnyObject) {     NSApplication.shared().terminate(self) } 

Swift 2:

@IBAction func ExitNow(sender: AnyObject) {     NSApplication.sharedApplication().terminate(self) } 
like image 168
Mike S Avatar answered Sep 28 '22 02:09

Mike S


Or we could simply exit from the app like this:

@IBAction func ExitNow(sender: AnyObject) {         exit(0) } 

As a side note you can exit because of an error:

fatalError("reason for exiting") 

Unconditionally prints a message and stops execution. iOS 8.1 and later.

like image 41
oyalhi Avatar answered Sep 28 '22 01:09

oyalhi