Swift and scriptingbridge object initialization

前端 未结 4 1939
天命终不由人
天命终不由人 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:28

    In my swift project , I had issues with using the types defined in the generated iTunes.h file (linking errors and such).

    The answer from markhunte explains that you can obtain a reference to the application object. But beyond that, I was getting compilation/linker errors when trying to obtain instances from that application object.

    In my swift project, I ended up creating an objective C wrapper class that exposes the iTunes types as basic objective C types (arrays and dictionary), and adapts methods as well.

    My swift classes use this wrapper instead of the iTunes types.

    So, the objective C wrapper looks like this (redux):

    #import "ITunesBridgex.h"
    #import "iTunes.h"
    
    @interface ITunesBridgex(){
        iTunesApplication *_iTunesApplication;
        iTunesSource* _iTunesLibrary;
    }
    @end
    @implementation ITunesBridgex
    
    -(id)init {
        self = [super init];
        if (self) {
            _iTunesApplication = [SBApplication applicationWithBundleIdentifier:@"com.apple.iTunes"];
            NSArray *sources = [_iTunesApplication sources];
            for (iTunesSource *source in sources) {
                if ([source kind] == iTunesESrcLibrary) {
                    _iTunesLibrary = source;
                    break;
                }
            }
        }
        return self;
    }
    
    - (NSDictionary*) currentTrack {
        iTunesTrack* track = _iTunesApplication.currentTrack;
        if (!track)
            return nil;
        NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys: track.name, @"title", nil];
        return dict;
    }
    
    @end
    

    and the calling swift code:

    import Foundation
    import Cocoa
    
    class ITunesBridgeSimple {
    
        var iTunesBridgex: ITunesBridgex
    
        init(){
            iTunesBridgex = ITunesBridgex()
            self.updateFromCurrentTrack()
        }
        func updateFromCurrentTrack() {
            if let track = self.currentTrack {
                if let title : AnyObject = track.objectForKey("title"){
                    println("Current track: \(title)")
                }
            }
        }
    }
    

提交回复
热议问题