簡體   English   中英

Swift & Xcode IOS 應用:限時應用在后台運行

[英]Swift & Xcode IOS App: limit time app is running in background

我想知道如何限制我的應用程序在后台運行的時間。

目的是再次顯示 LaunchScreen 並在后台運行 5 或 10 分鍾后從初始 state 啟動應用程序。

提前致謝

這里有一些想法和想法來實現你想要的。

首先,當您的應用進入后台時,它會在您的App Delegate中調用applicationDidEnterBackground(_:) 如果您正在使用帶有Scene Delegate的場景,那么您應該在sceneDidEnterBackground(_:)中執行任何最后的邏輯

根據文檔,調用上述函數后,您有5 seconds的時間執行任何任務

applicationDidEnterBackground(_:)

盡快從 applicationDidEnterBackground(_:) 返回。 您對該方法的實施大約有五秒鍾的時間來執行任何任務並返回。

在此之后,您的應用程序進入suspended狀態 state 如果您需要超過 5 秒,您可以通過調用beginBackgroundTask(withName:expirationHandler:)請求更多,但出於您的目的,我認為您不需要這個。

有關上述主題的更多信息,請點擊此處

您幾乎無法控制您的應用何時再次在后台運行,即從暫停狀態移至后台 state。

BGTaskRequest有一個名為earliestBeginDate的屬性,但根據文檔:

最早開始日期

指定 nil 表示沒有啟動延遲。

設置該屬性表示后台任務不應早於該日期開始。 但是,系統不保證在指定日期啟動任務,只是保證不會提前開始。

長話短說,您無法真正判斷您的應用程序何時會再次在后台運行,也無法決定將運行多長時間。

你可以做的是實現applicationDidEnterBackground(_:)sceneDidEnterBackground(_:)如果你使用場景來跟蹤應用程序進入后台的time ,如下所示:

func sceneDidEnterBackground(_ scene: UIScene)
{
    // Get the current date / time
    let currentDate = Date()
    
    let userDefaults = UserDefaults.standard
    
    // Start tracking time as soon as the app goes
    // into the background
    userDefaults.setValue(currentDate,
                          forKey: "PreviousLaunchDate")
    
    // Just for testing, remove from production app
    print("start tracking")
}

然后當您的應用程序進入前台時,檢查已經過了多少時間並做出相應的反應:

func sceneWillEnterForeground(_ scene: UIScene)
{
    let userDefaults = UserDefaults.standard
    
    let currentDate = Date()
    
    // Check if you have saved a date before
    if let previousLaunchDate
        = userDefaults.object(forKey: "PreviousLaunchDate") as? Date
    {
        // Retrieve the minutes elapsed
        // Check if minutes elapsed is greater than 10 minutes or as you wish
        if let minutesElapsed = Calendar.current.dateComponents([.minute],
                                                             from: previousLaunchDate,
                                                             to: currentDate).minute,
           minutesElapsed > 10
        {
            // Reset your window's root view controller to start again
            // showing the splash view or reset your storyboard etc
            // For example
            // let splashVC = SplashViewController()
            // window?.rootViewController = splashVC

            // just for testing, remove from production app
            print("show splash vc")
            
            return
        }
        
        // Do nothing since 10 minutes haven't elapsed so you can
        // show the current state of the app to the user
        
        // just for testing, remove from production app
        print("do nothing")
    }
}

我認為這應該讓你接近你正在尋找的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM