iOS, locking the device from code

允我心安 提交于 2019-12-08 16:01:29

问题


for testing purposes (making a screenshot of a local notification) i need to be able to lock the device (simulator) from code (either tests code or app code). I've looked at a couple of answers from here (GSEventLockDevice), but they are quite old and didn't work for me


回答1:


There is a private method in XCUIDevice, so you can lock device/simulator using it.

Example for Swift 3:

import XCTest

class LockTests: XCTestCase {
  func testExample() {
    XCUIDevice.shared().perform(NSSelectorFromString("pressLockButton"))

    let localNotification = UILocalNotification()
    localNotification.fireDate = Date(timeIntervalSinceNow: 2)
    localNotification.alertBody = "This is local notification"
    localNotification.timeZone = NSTimeZone.local
    localNotification.category = "Message"
    UIApplication.shared.scheduleLocalNotification(localNotification)
  }
}

And will receive something like this:

I have no experience with snapshot tool you are using, but you need to know that moving to locking state takes time, so it might be useful to wait a bit of time before creating snapshot (you can use code like this):

let date = Date(timeIntervalSinceNow: 3)
while date.timeIntervalSinceNow > 0 {
  CFRunLoopRunInMode(CFRunLoopMode.defaultMode, 0.1, true)
}

Also, you can return to SpringBoard in the end of the test by calling (iOS 10 only):

XCUIDevice.shared().press(.home)

Hope it helps!



来源:https://stackoverflow.com/questions/38895668/ios-locking-the-device-from-code

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!