tingraldi / SwiftScripting

Utilities and samples to aid in using Swift with the Scripting Bridge. If you want to automate tasks on your Mac, but don't like AppleScript, this is for you.
285 stars 29 forks source link

iTunesArtwork.setData fails with error "object has not been added to a container yet; selector not recognized" #15

Open dstaley opened 6 years ago

dstaley commented 6 years ago

Hello!

First off, thank you for creating SwiftScripting! I've been banging my head against a wall trying to find a reasonable way to script my iTunes library, so I'm incredibly thankful for the work you've put into this.

I'm reasonably new to Scripting Bridge, so I'm not sure if this issue is with SB or with SwiftScripting or with my application code.

Basically, I'm trying to add album art to tracks in iTunes.

My script is (essentially) this:

let app = application(name: "iTunes") as! iTunesApplication

let sources = app.sources!() as! [iTunesSource]
let librarySource = sources.first!
let libraryPlaylists = librarySource.libraryPlaylists!() as! [iTunesLibraryPlaylist]
let library = libraryPlaylists.first!

let file = NSURL.fileURL(withPath: "/Users/dylanstaley/Documents/1799.m4a")
let track = app.add!([file], to: library as! SBObject)

let image = NSImage.init(contentsOfFile: "/Users/dylanstaley/Downloads/merged.png")
let artwork = objectWithApplication(app, scriptingClass: iTunesScripting.artwork) as iTunesArtwork
track.artworks!().add(artwork)
artwork.setData!(image)

When I run this script, I get the following error

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[SBProxyByClass setData:]: object has not been added to a container yet; selector not recognized [self = 0x1015b04e0]'

From what I understand, SB objects need to be immediately added to their container before you can set properties on them. However, as far as I know, I'm doing just that. I mimicked the exact same structure with adding a playlist and it worked correctly, so I'm fairly sure I'm invoking it in the right way.

tingraldi commented 6 years ago

This one has me a bit stumped. I haven't reached a solution yet. Stay tuned...

tingraldi commented 6 years ago

Hmm...

It looks like setting iTunes track artwork is something like the "third rail" of the Scripting Bridge. There's an old thread on CocoaBuilder that basically concludes that you must resort to AppleScript for this task. See http://www.cocoabuilder.com/archive/cocoa/199978-setting-itunes-album-art-with-scriptingbridge.html#200000.

I'm close to officially giving up on this one, but I'll probably poke at it a bit more.