-8

I need to set a timer to lock an iPhone from my app. While using the application, after 3 to 5 minutes the phone should become locked.

Mike Doe
  • 16,349
  • 11
  • 65
  • 88

3 Answers3

1

You cannot lock the screen programmatically without any private API. Even if you use a private API, your app may probably be rejected by App Store.

However you can indeed achieve by sending keyboard events from paired bluetooth hardware devices. But that means your code depends on a Bluetooth connection and I cannot think of any practice use of that. To do this with Bluetooth, click here.

Fangming
  • 24,551
  • 6
  • 100
  • 90
1

Short answer: You can't.

Long Answer: For the security of iOS users, Apple does not allow any application to work with important hardware matters, such as locking the iPhone or controlling the usage of other apps. If your app even attempts to do such a thing (using any method, like external APIs), your app will immediately be rejected by Apple. It is not even worth trying.

Mr. Xcoder
  • 4,719
  • 5
  • 26
  • 44
0

Now there is a workaround if you really need it.

With iOS 16.4 you can now use the "Lock Screen" action in shortcuts.

So to lock a device programmatically you can ask your app to launch a shortcut that will do the job.

You can import the needed "Lockscreen" shortcut with one single line of code:

openURL(URL(string: "https://www.icloud.com/shortcuts/da76168e73974887ae96480d435da049")!)

When user did import the needed shortcut, you can call it directly:

func runLockscreenShortcut2() {
    if let url = URL(string: "shortcuts://run-shortcut?name=Lockscreen"), UIApplication.shared.canOpenURL(url) {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
}

Only drawback is that the Shortcuts app will appear briefly before the device locks, and will be in foreground when unlocking the briefly.

You can add a "Go To Home Screen" action to your shortcut before the "Lock Screen" action, so that Shortcut app won't be in foreground when device will unlock but it will slow down locking process.

Far from perfect but your unique option for the moment...

Clement M
  • 709
  • 6
  • 14