title: How to loop through all Mac desktop spaces
body: <p>I'm trying to set a desktop background for all screens AND spaces (preexisting and new). However, I can't seem to find a way to set the background for all the existing spaces (and any new spaces created use the old background).</p>
  
  <p>Here is what I have so far:</p>
  
  <pre><code>let sqlData = NSMutableArray()
  let paths = NSSearchPathForDirectoriesInDomains(.ApplicationSupportDirectory, .UserDomainMask, true)
  let appSupportDirectory = paths.first! as NSString
  let dbPath = appSupportDirectory.stringByAppendingPathComponent("Dock/desktoppicture.db") as NSString
  
  var db: COpaquePointer = nil
  if sqlite3_open(dbPath.UTF8String, &amp;db) == SQLITE_OK {
      var statement: COpaquePointer = nil
  
      if sqlite3_exec(db, "DELETE FROM data", nil, nil, nil) != SQLITE_OK {
          let errmsg = String.fromCString(sqlite3_errmsg(db))
          print("error deleting table row: \(errmsg)")
      }
  
      if sqlite3_exec(db, "INSERT INTO DATA (VALUE) VALUES ('\(getBackgroundImagePath())');", nil, nil, nil) != SQLITE_OK {
          let errmsg = String.fromCString(sqlite3_errmsg(db))
          print("error inserting table row: \(errmsg)")
      }
  
      let workspace = NSWorkspace.sharedWorkspace()
  
      for screen in NSScreen.screens()! {
          do {
              let options = workspace.desktopImageOptionsForScreen(screen)
              try workspace.setDesktopImageURL(NSURL(fileURLWithPath: getBackgroundImagePath()), forScreen: screen, options: options!)
          } catch let error as NSError {
              NSLog("\(error.localizedDescription)")
          }
      }
  
      system("/usr/bin/killall Dock")
  }
  
  sqlite3_close(db)
  </code></pre>
  
  <p>Note: I update the .db file found in <code>~/Library/Application Support/Dock/desktoppicture.db</code>. Since this doesn't actually update the background, I then proceed to loop through each screen and set them manually.</p>
  
  <p>Although this changes all of the screen's backgrounds, any non-active spaces are not changed, and any new spaces created use the old background.</p>
  
  <p>I'm using this code within a small app I made on GitHub, and this is an issue a user reported. <a href="https://github.com/josueespinosa/BingBackground-Mac/issues/1">You can find the issue here (with a terminal solution)</a>.</p>
  
  <p>Apple has a seemingly relevant project <a href="https://developer.apple.com/library/mac/samplecode/DesktopImage/Introduction/Intro.html">here</a>, but even they don't update multiple spaces.</p>
  
  <p>Also, if you update the background through the default mac settings app, it also doesn't change pre-existing spaces. Is it impossible?</p>