title: IOSurface - IOS Private API - Capture screenshot in background
body: <p>I want to capture a screenshot from a background service. Private API is just fine as I don't need to submit to app store. I have already tried UIGetScreenImage and it does not work from background app.</p>
  
  <p>I am using following code which I got from SO. IOSurfaceCreate returns null to me. Any help appreciated.</p>
  
  <pre><code>CFMutableDictionaryRef dict;
          IOSurfaceRef screenSurface = NULL;
  
          char pixelFormat[4] = {'A','R','G','B'};
          dict = CFDictionaryCreateMutable(kCFAllocatorDefault, 0, &amp;kCFTypeDictionaryKeyCallBacks, &amp;kCFTypeDictionaryValueCallBacks);
  
          uint32_t width ;
          uint32_t height;
          void *pitch;
          void *bPE;
          void *size;
          CFDictionarySetValue(dict, kIOSurfaceIsGlobal, kCFBooleanTrue);
          CFDictionarySetValue(dict, kIOSurfaceBytesPerRow, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &amp;pitch));
          CFDictionarySetValue(dict, kIOSurfaceBytesPerElement, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &amp;bPE));
          CFDictionarySetValue(dict, kIOSurfaceWidth, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &amp;width));
          CFDictionarySetValue(dict, kIOSurfaceHeight, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &amp;height));
          CFDictionarySetValue(dict, kIOSurfacePixelFormat, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, pixelFormat));
          CFDictionarySetValue(dict, kIOSurfaceAllocSize, CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &amp;size));
  
          IOSurfaceRef destSurf = IOSurfaceCreate(dict);
          IOSurfaceAcceleratorRef outAcc;
          IOSurfaceAcceleratorCreate(NULL, 0, &amp;outAcc);
  
          CFDictionaryRef ed = (__bridge CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys: nil];
          IOSurfaceAcceleratorTransferSurface(outAcc, screenSurface, destSurf, ed, NULL);
          uint32_t aseed;
          IOSurfaceUnlock(screenSurface, kIOSurfaceLockReadOnly, &amp;aseed);
  
          CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, IOSurfaceGetBaseAddress(destSurf), (width*height*4), NULL);
          CGImageRef cgImage=CGImageCreate(width, height, 8, 8*4, IOSurfaceGetBytesPerRow(destSurf), CGColorSpaceCreateDeviceRGB(), kCGImageAlphaNoneSkipFirst | kCGBitmapByteOrder32Little, provider, NULL, YES, kCGRenderingIntentDefault);
          UIImage *image = [UIImage imageWithCGImage: cgImage];
          UIImageWriteToSavedPhotosAlbum(image, self_object, nil, nil);
          CGImageRelease(cgImage);
          CFRelease(destSurf);
  </code></pre>