簡體   English   中英

替代 iOS 已棄用的 UIApplicationExitsOnSuspend

[英]Alternative to iOS's deprecated UIApplicationExitsOnSuspend

我有一個不想在后台運行的應用程序。 我的應用在后台模式下無能為力,只會增加煩人的 UI 復雜性。 我希望應用程序在從前台刪除時終止。

UIApplicationExitsOnSuspend是 Apple 之前允許這樣做的方法,它非常適合我的用例。 但是,它現在已被棄用,他們正在拒絕具有該 Info.plist 值的應用程序。

我能找到的唯一替代方法是應用程序委托方法中的exit(0) ,但 Apple 強烈反對這樣做,並且它看起來像一個崩潰。

還有其他可行的選擇嗎? 我只是不希望我的應用程序在后台運行,它所做的只是不必要地耗盡用戶的電池。

作為UIApplicationExitsOnSuspend的替代方法,我在后台檢查經過的時間,並在需要時重置我的導航:

  • 我保留了應用程序最后一次進入后台的時間( NSUserDefaults in applicationDidEnterBackground
  • 當應用程序再次變為活動狀態時,我根據給定的時間閾值檢查保存的時間(在applicationDidBecomeActive中)。
  • 如果超出閾值,我會重置導航(這允許我重新同步我的應用程序或在一段時間后重新請求登錄,但允許快速撥打電話)

由於它是一個舊應用程序,這里是 objective-c:

appdelegate.m:

- (void)applicationDidEnterBackground:(UIApplication *)application {
    NSLog(@"APPLIFE : going to sleep ... ");
    [[NSUserDefaults standardUserDefaults] setObject: [NSDate date] forKey:@"last-background-time"];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    NSLog(@"APPLIFE : ... back to front");
    NSDate * bgTime = [[NSUserDefaults standardUserDefaults] objectForKey:@"last-background-time"];

    NSTimeInterval secondsSinceLastRun = fabs([bgTime timeIntervalSinceNow]);
    double threshold = 60 * 60 * 24; //in seconds.   

    if (secondsSinceLastRun > threshold) {
        NSLog(@"APPLIFE : Too old, reboot app");
        //[navigationController popToRoot] or whatever you want
    }
}

對於 SwiftUI,將其添加到 App 結構中:

@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate

然后添加這兩個類:

class AppDelegate: UIResponder, UIApplicationDelegate {

func application(
    _ application: UIApplication,
    configurationForConnecting connectingSceneSession: UISceneSession,
    options: UIScene.ConnectionOptions
  ) -> UISceneConfiguration {
    let sceneConfig = UISceneConfiguration(name: nil, sessionRole: connectingSceneSession.role)
    sceneConfig.delegateClass = SceneDelegate.self // 👈🏻
    return sceneConfig
  }

}

class SceneDelegate:NSObject,UIWindowSceneDelegate {

func sceneWillResignActive(_ scene: UIScene) { // 這將強制應用程序在兩秒后每次重新啟動(因此關閉的 animation 看起來很干凈) do { sleep(2) } exit(0) } }

暫無
暫無

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

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