Reputation: 2505
I have an NSImage (and it's corresponding NSData) and I need to set that image as the desktop. It seems that the only method APple provides for setting an image is
[NSWorkspace setDesktopImageURL:forScreen:options:error:]
How can I convert from an NSImage or NSData to an NSURL? I am doing this to save the imageData:
[imageData writeToFile:@"wallpaper" atomically:NO];
But how can I get that URL in order to set it as the desktop? I can't figure out how to get the URL that it is saved to.
Upvotes: 0
Views: 758
Reputation: 366003
To answer exactly the question you asked:
[NSURL fileURLWithPath:@"wallpaper"]
But it makes more sense to actually write the file to the same URL you pass to NSWorkspace, like this:
NSURL *url = [NSURL fileURLWithPath:@"wallpaper"];
[imageData writeToURL:url atomically:NO];
[[NSWorkspace sharedWorkspace] setDesktopImageURL:url …];
It makes even more sense to pick a good place to put the file. As a general rule (even outside of software), if you know where you put something, it's a lot easier to find it later than if you just tell someone "put this somewhere". And your specific "put this somewhere" really means "put this in the current working directory", which may be somewhere you don't have write access, or somewhere the user doesn't want you to clutter up, or it may already have a file (or a directory) called "wallpaper" in it, or…
So, you probably want to call -[NSFileManager URLForDirectory:inDomain:appropriateForURL:create:error:] to get the NSTemporaryDirectory, or use a different temp-file API. Or you might want to put it in your app's cache directory instead of a temporary location. Whatever seems to make sense to you.
Also, you probably want to put an appropriate extension on the file. And, without knowing where you got imageData from, I'm not sure you're going to get a usable image file. But that's all separate issues.
Upvotes: 2