iOS,从代码锁定设备 [英] iOS, locking the device from code

查看:25
本文介绍了iOS,从代码锁定设备的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于测试目的(制作本地通知的屏幕截图),我需要能够通过代码(测试代码或应用程序代码)锁定设备(模拟器).我看过这里的几个答案(GSEventLockDevice),但它们已经很老了,对我不起作用

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

推荐答案

XCUIDevice 中有一个私有方法,所以你可以使用它来锁定设备/模拟器.

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

Swift 3 示例:

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)
}

此外,您可以在测试结束时通过调用返回 SpringBoard(仅限 iOS 10):

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

XCUIDevice.shared().press(.home)

希望有帮助!

这篇关于iOS,从代码锁定设备的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆