Swift and scriptingbridge object initialization

前端 未结 4 1951
天命终不由人
天命终不由人 2021-02-03 14:45

I\'m trying to write an application for swift control iTunes. But when initializing the application returns an object of type AnyObject, but must iTunesApplication.

4条回答
  •  长情又很酷
    2021-02-03 15:36

    I suspected that the problem was that the iTunes.h file was not being imported. Therefore it's methods where not being picked up.

    So I created a -Bridging-Header.h file.

    My Project is name swiftItunesTest. so the -Bridging-Header.h file is named:

    swiftItunesTest-Bridging-Header.h

    Inside of this I placed the #import "iTunes.h" line

    And in the AppDelegate.swift file

    import Cocoa
     import Appkit
     import ScriptingBridge
    
    
    
    
    
    class AppDelegate: NSObject, NSApplicationDelegate {
    
        @IBOutlet var window: NSWindow
    
    
        func applicationDidFinishLaunching(aNotification: NSNotification?) {
            var iTunes : AnyObject = SBApplication.applicationWithBundleIdentifier("com.apple.iTunes")
    
            iTunes.playpause()
    
    
        }
    
        func applicationWillTerminate(aNotification: NSNotification?) {
            // Insert code here to tear down your application
        }
    
    
    }
    

    The iTunesApplication (iTunes.) now started to pick up the methods/functions


    Here is a slightly updated example.

     func applicationDidFinishLaunching(aNotification: NSNotification) {
            let iTunes : AnyObject = SBApplication(bundleIdentifier: "com.apple.iTunes")!
    
            iTunes.playpause()
    
    
              guard let currentTrack: AnyObject =  iTunes.currentTrack!.name else {
    
                 print("No Tracks Playing")
                 return
           }
              print("\(currentTrack)")
    
        }
    
        func applicationWillTerminate(aNotification: NSNotification) {
    
        }
    

提交回复
热议问题