私は最近タスク管理アプリケーションを開発していたときに同じ問題が発生しました。 CFNotificationCallbackメソッドでDarwin Notificationを使用してこの問題を解決しようとしています。
ステップ1:
右AppDelegateクラス宣言の下に
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let displayStatusChanged: CFNotificationCallback = { center, observer, name, object, info in
let str = name!.rawValue as CFString
if (str == "com.apple.springboard.lockcomplete" as CFString) {
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(true, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
}
}
//other functions
}
ステップ2次のコードを追加します。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions:
[UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(false, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
// Darwin Notification
let cfstr = "com.apple.springboard.lockcomplete" as CFString
let notificationCenter = CFNotificationCenterGetDarwinNotifyCenter()
let function = displayStatusChanged
CFNotificationCenterAddObserver(notificationCenter,
nil,
function,
cfstr,
nil,
.deliverImmediately)
return true
}
ステップ3:
次のコードを追加し、didFinishLaunchingWithOptions
内部
をapplicationDidEnterBackground
の中に次のコードを追加します。
func applicationDidEnterBackground(_ application: UIApplication) {
let isDisplayStatusLocked = UserDefaults.standard
if let lock = isDisplayStatusLocked.value(forKey: "isDisplayStatusLocked"){
// user locked screen
if(lock as! Bool){
// do anything you want here
print("Lock button pressed.")
}
// user pressed home button
else{
// do anything you want here
print("Home button pressed.")
}
}
}
ステップ4:あなたはデモプロジェクトで、ここで詳細なアプローチを見てみることができます
func applicationWillEnterForeground(_ application: UIApplication) {
print("Back to foreground.")
//restore lock screen setting
let isDisplayStatusLocked = UserDefaults.standard
isDisplayStatusLocked.set(false, forKey: "isDisplayStatusLocked")
isDisplayStatusLocked.synchronize()
}
:swift-home-vs-lock-button
applicationWillEnterForeground
の内部では、次のコードを追加します