Lock screen on device programmatically

cocoa-touch, ios, objective-c

Solution

This has already been resolved by somebody else. You can find it on Github: https://github.com/neuroo/LockMeNow

char *gsDylib = "/System/Library/PrivateFrameworks/GraphicsServices.framework/GraphicsServices";
void *handle = dlopen(gsDylib, RTLD_NOW);
if (handle) {
  BOOL locked = FALSE;
  void (*_GSEventLockDevice)() = dlsym(handle, "GSEventLockDevice");
  if (_GSEventLockDevice)  {
    _GSEventLockDevice();
    //...
  }
  dlclose(handle);
  //...
}

Problem

I have read the other questions regarding the same, but everyone is just saying 'Jailbreak', 'that'll never be approved by Apple', 'It's not possible' and 'private API, GraphicsServices.framework'. Let me just clear something up, I am not doing this for a jailbroken phone, I am doing this because the lock-button on my phone is broken, and I simply want to not have to wait 1 minute for the screen to lock. So I figured I could have an app which called `lockScreen` in the beginning of `AppDelegate.h`. This is not going on AppStore, it's just for me. I've seen people saying they can use `GSEventLockDevice();` when importing `GSEvent.h` from `GraphicsServices.framework`, but when I try running it (both on device and simulator) I get this, and it won't build: ``` Undefined symbols for architecture armv7s: "_GSEventLockDevice", referenced from: -[AppDelegate application:didFinishLaunchingWithOptions:] in AppDelegate.o ld: symbol(s) not found for architecture armv7s clang: error: linker command failed with exit code 1 (use -v to see invocation) ``` I'm not completely sure what this means. If I remove the line `GSEventLockDevice();` but still import `GSEvent.h`, everything is running fine. Does my device need to be jailbroken for this to work or something?

Original source