首页 > 解决方案 > UIApplication.shared.backgroundTimeRemaining 总是少于两秒

问题描述

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    application.setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
    return true
}



 func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        let configuration = URLSessionConfiguration.background(withIdentifier: "smat.Tracker")
        switch UIApplication.shared.applicationState {
        case .active:
            print("App is active.")
        case .background:
            print("App is in background.")
            print("Background time remaining = \(UIApplication.shared.backgroundTimeRemaining) seconds")
        case .inactive:
            break
        }
        print(UIApplication.shared.applicationState.rawValue)
        print(configuration.allowsCellularAccess)
        print(configuration.timeoutIntervalForResource)

        let headers: HTTPHeaders = [

            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
            "accept-encoding": "gzip, deflate, br",
            "accept-language": "en-US,en;q=0.9",
            "referer": "https://frys.com/",
            "host":"frys.com",
            "upgrade-insecure-requests": "1",
            "user-agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36"
        ]
        configuration.httpAdditionalHeaders = headers
        let base_url: String = "https://frys.com/search?search_type=regular&sqxts=1&cat=&query_string=" + "vivomove" + "&nearbyStoreName=false"
        let sessionManager = Alamofire.SessionManager(configuration: configuration)
        print("came here")
        if(Trackers.urls.count > 0 ){
            print(Trackers.urls.count)
        }

        Alamofire.request(base_url , headers: headers).responseString { response in
            //print(response.result.value)
            do {
                print("response12 ")
                guard let doc = try! response.result.value else{
                    completionHandler(.noData)
                    throw NSError(domain: "ERROR", code: 42, userInfo: ["BKGROUND":"err"])
                }
                completionHandler(.newData)
                //self.endBackgroundTask()
            }
            catch {
                print("error")
            }
        }


    }

我在 AppDelegate.swift 中有上面的代码。我在几个文档/教程中读到完成后台任务所需的最短时间为 30 秒或更多。为什么我总是让上述时间少于 2 秒?

来自控制台的以下示例输出:

应用程序在后台。后台剩余时间 = 1.79769313486232e+308 秒 0.0 1.79769313486232e+308 UIApplicationState

标签: iosswift

解决方案


推荐阅读