Devarshi
Devarshi

Reputation: 16758

Unable to change desktop image because url is not file url

I am trying to change desktop image using below code:

NSError *anError = nil;
NSString *imageURLString = [[NSBundle mainBundle] pathForResource:@"wallpaper" ofType:@"jpg"];
NSURL *imageURL = [NSURL URLWithString:imageURLString];

[[NSWorkspace sharedWorkspace] setDesktopImageURL:imageURL forScreen:[NSScreen mainScreen] options:nil error:&anError];

but it is always throwing this exception message in console:

Invalid parameter not satisfying: url != nil && [url isFileURL]

When I tried to log - [url isFileURL] it is returning NO, which I am unable to figure out.

When I tried to print description of imageURL, it printed following message:

<CFURL 0x100165c50 [0x7fff7f508ea0]>{type = 15, string = /Users/miraaj/Library/Developer/Xcode/DerivedData/DesktopFun-cevkcaebvcfnstgqbulqyibcfvru/Build/Products/Debug/DesktopFun.app/Contents/Resources/wallpaper.jpg, encoding = 134217984, base = (null)}

Can anyone suggest me the reason for this problem?

Upvotes: 1

Views: 456

Answers (1)

Kurt Revis
Kurt Revis

Reputation: 27994

You're using the wrong method to create an NSURL. You want

NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"wallpaper" ofType:@"jpg"];
NSURL* imageURL = [NSURL fileURLWithPath:imagePath isDirectory:NO];

Or, you could save a step and get an NSURL directly from NSBundle (on 10.6 and later):

NSURL* imageURL = [[NSBundle mainBundle] URLForResource:@"wallpaper" withExtension:@"jpg"];

Upvotes: 2

Related Questions