Simple callback using MASShortcut using Swift

I installed the latest (2015-02-03) MASShortcut as CocoaPod along with the correct bridge header for a very simple OS X Swift application. I ended up with the following code and I don’t know what am I doing wrong ?:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    @IBOutlet weak var window: NSWindow!

    func callback() {
         NSLog("callback")
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        let keyMask = NSEventModifierFlags.CommandKeyMask | NSEventModifierFlags.AlternateKeyMask
        let shortcut = MASShortcut.shortcutWithKeyCode(kVK_Space, modifierFlags: UInt(keyMask.rawValue))
        MASShortcut.addGlobalHotkeyMonitorWithShortcut(shortcut, handler: callback)
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }


}

Thanks in advance!

+4
source share
2 answers

There are several issues here. Before installing them, make sure that you have installed MASShortcut2.1.2 (this can be seen in Podfile.lock). If you do not, you must run pod updateto get the latest version.

- , OS X. Command + Option + Space Finder . , , Control .

. -, keyMask:

let keyMask: NSEventModifierFlags = .CommandKeyMask | .ControlKeyMask | .AlternateKeyMask

, Swift , NSEventModifierFlags ( , .ControlKeyMask ).

Swift , rawValue . rawValue of NSEventModifierFlags UInt, .

keyCode UInt. , :

let keyCode = UInt(kVK_Space)

Swift , , Swift. , shortcutWithKeyCode:modifierFlags:, Swift . , :

let shortcut = MASShortcut(keyCode: keyCode, modifierFlags: keyMask.rawValue)

rawValue - UInt.

, API MASShortcutMonitor. , :

#import <MASShortcut/MASShortcut.h>

, API. :

#import <MASShortcut/MASShortcutMonitor.h>

:

MASShortcutMonitor.sharedMonitor().registerShortcut(shortcut, withAction: callback)

. !

. applicationWillTerminate: :

MASShortcutMonitor.sharedMonitor().unregisterAllShortcuts()
+5

, . ! , . !

.

#import <MASShortcut/MASShortcutMonitor.h>

, .

#import <Cocoa/Cocoa.h>
#import <MASShortcut/Shortcut.h>

and Shortcut.h already reference MASShortcutMonitor.h.

Again: Thank you very much!

-1
source

All Articles