title: How to write CGImageRef to png file. CGImageDestinationCreateWithURL returns nil
body: <pre><code>- (void)takeScreenShot {
      CGImageRef screenShot = CGWindowListCreateImage(CGRectInfinite, kCGWindowListOptionOnScreenOnly, kCGNullWindowID, kCGWindowImageDefault);
      CGImageWriteToFile(screenShot, [@"~/code/screenshot.png" stringByExpandingTildeInPath]);
  }
  
  BOOL CGImageWriteToFile(CGImageRef image, NSString *path) {
      CFURLRef url = (__bridge CFURLRef)[NSURL fileURLWithPath:path];
      CGImageDestinationRef destination = CGImageDestinationCreateWithURL(url, kUTTypePNG, 1, NULL);
      if (!destination) {
          NSLog(@"Failed to create CGImageDestination for %@", path);
          return NO;
      }
  
      CGImageDestinationAddImage(destination, image, nil);
  
      if (!CGImageDestinationFinalize(destination)) {
          NSLog(@"Failed to write image to %@", path);
          CFRelease(destination);
          return NO;
      }
  
      CFRelease(destination);
      return YES;
  }
  </code></pre>
  
  <blockquote>
    <p>Failed to create CGImageDestination for
    /Users/"username"/Library/Containers/"bundleidentifier"/Data/code/screenshot.png</p>
  </blockquote>
  
  <p>So no destination is returned.
  Preferably I would like to write to ~/code/screenshot.png but if it is something with sandboxing it is also ok to write to "sandbox"</p>
  
  <p>How do I write a screenshot to a file that I can access later?</p>
  
  <p>I have adapted code from <a href="https://stackoverflow.com/questions/1320988/saving-cgimageref-to-a-png-file">Saving CGImageRef to a png file?</a></p>