我想阻止用户的Macbook在应用程序运行时自动休眠。我该怎么办?我见过这个
https://developer.apple.com/library/content/qa/qa1340/_index.html
和此:
Disable sleep mode in OS X with swift
和此:
Using Swift to disable sleep/screen saver for OSX
但是我没有简单的代码行或代理方法可以像iOS中那样简单吗?我只想让整个应用程序正常工作并阻止计算机自动进入睡眠状态。如果有人投入手动睡觉,那么显然这很好。我不想阻止用户让计算机进入睡眠状态。但只要我的应用程序运行,我就不希望电脑睡觉。就像你正在看电影一样,该应用程序不会进入睡眠状态。我该怎么做?
我觉得这是我需要的代码,但我只是在viewdidload中运行此函数,它会工作吗?这很简单吗?
var assertionID: IOPMAssertionID = 0
var success: IOReturn?
func disableScreenSleep(reason: String = "Unknown reason") -> Bool? {
guard success != nil else { return nil }
success = IOPMAssertionCreateWithName( kIOPMAssertionTypeNoDisplaySleep as CFString,
IOPMAssertionLevel(kIOPMAssertionLevelOn),
reason as CFString,
&assertionID )
return success == kIOReturnSuccess
}
答案 0 :(得分:1)
正如我在评论中已经提到的那样,您需要移除防护,否则它将只返回nil并且永远不会禁用屏幕睡眠。您还可以简化方法,返回void并将您的成功属性更改为Bool属性(如禁用)以监视屏幕睡眠状态:
var assertionID: IOPMAssertionID = 0
var sleepDisabled = false
func disableScreenSleep(reason: String = "Disabling Screen Sleep") {
sleepDisabled = IOPMAssertionCreateWithName(kIOPMAssertionTypeNoDisplaySleep as CFString, IOPMAssertionLevel(kIOPMAssertionLevelOn), reason as CFString, &assertionID) == kIOReturnSuccess
}
func enableScreenSleep() {
IOPMAssertionRelease(assertionID)
sleepDisabled = false
}
要禁用屏幕,只需调用第一个视图控制器的viewDidLoad中的方法:
override func viewDidLoad() {
super.viewDidLoad()
disableScreenSleep()
print("sleep Disabled:", sleepDisabled)
}