简体   繁体   English

如何取消 iOS 应用程序的睡眠模式?

[英]How to cancel sleep mode of an iOS application?

I am working on an iOS application where the app is supposed to make a server request before going to background mode.我正在开发一个 iOS 应用程序,该应用程序应该在进入后台模式之前发出服务器请求。 I app should not wait for the response as that's not needed.我的应用程序不应该等待响应,因为这是不需要的。 The sole purpose of this request is that I need to keep the status of the app in my DB to know if the user is online/offline.此请求的唯一目的是我需要将应用程序的状态保留在我的数据库中,以了解用户是否在线/离线。

As the app goes to background, i make the server request and put the app into sleep mode by sleep(3) so that it can successfully finish the server call.当应用程序进入后台时,我发出服务器请求并通过 sleep(3) 将应用程序置于睡眠模式,以便它可以成功完成服务器调用。

func applicationDidEnterBackground(_ application: UIApplication) {

    //make a server call

    sleep(3) //so that app can submit request to server before closing
} 

This works fine but if I open the app again (comes to foreground) before that sleep time has been finished, the app does not respond to any kind of user inputs/taps.这工作正常,但如果我在睡眠时间结束之前再次打开应用程序(进入前台),应用程序不会响应任何类型的用户输入/点击。 Even the applicationDidBecomeActive method does not get called.甚至 applicationDidBecomeActive 方法也不会被调用。 It waits for that sleep time to finish that I had set before.它等待我之前设置的睡眠时间完成。

How can I cancel the sleep mode when the app becomes active?当应用程序处于活动状态时,如何取消睡眠模式?

Don't use sleep .不要使用sleep Instead, make your server request using a URLSession that is suitable for background processing:相反,使用适合后台处理的 URLSession 发出服务器请求:

let session = URLSession(configuration: .background(withIdentifier: "foo"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 iOS 中以编程方式禁用/启用睡眠模式? - How to disable/enable the sleep mode programmatically in iOS? 配置iOS VoIP应用程序以在睡眠/后台模式下运行 - Configuring iOS VoIP application to run in sleep/background mode 在IOS Xamarin中处于睡眠模式时如何继续播放混合音频? - How to continue hybrid audio playing when in sleep mode in IOS Xamarin? iOS:在睡眠模式下保持任务运行 - iOS: keep task running when in sleep mode iOS App可防止设备进入睡眠模式 - iOS App prevents device from sleep mode iOS上的XE4 Firemonkey可防止睡眠模式 - XE4 Firemonkey on iOS prevent sleep mode iOS:如何在X小时内每小时在睡眠模式下使用iPad自动发送电子邮件? - iOS: How can I send an email automatically with an iPad in sleep mode every hours during X hours? 后台模式下的iOS应用 - IOS application in background mode 如何在后台模式和锁定屏幕中隐藏或取消来自APN的iOS中的推送通知(Uiusernotification或RemoteNotification)? - How to Hide or cancel Push notification in iOS ( Uiusernotification or RemoteNotification) which comes from apns in background mode and lock screen? 如何在 watchkit 中在睡眠模式下使用定时器 - how to use Timer in sleep mode in watchkit
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM