当用户终止应用程序时,我可以进行 api 调用吗?

Suj*_*jal 7 ios appdelegate swift applicationwillterminate

当用户终止应用程序(强制关闭)时,我需要进行 API 调用。我所做的直接实现如下。

在应用程序委托中,我添加了以下代码。

func applicationWillTerminate(_ application: UIApplication) {
    print("________TERMINATED___________")
    testAPICall()
}

func testAPICall(){
    let url = getURL()
    let contentHeader = ["Content-Type": "application/json"]
    Alamofire.request(url,
                  method: .put,
                  parameters: ["username": "abc@xyz.com"],
                  encoding: JSONEncoding.default,
                  headers: contentHeader).responseJSON { (response) -> Void in
                    print("-----")
                  }
}
Run Code Online (Sandbox Code Playgroud)

但是,没有拨打电话。在查看文档时,我发现在此方法中完成任务只需要 5 秒钟,最重要的是,进行 api 调用不是在这里完成的任务。所以我想知道,有什么方法可以做到这一点。

San*_*ari 8

这是一个双重问题

阶段 1:确保每次用户终止应用程序时 API 调用开始/在它变为活动状态之前

你总是可以在你的 appdelegate 中使用expiration handler后台模式iOS application

宣布 var bgTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0);

并在您的 appdelegate

 func applicationDidEnterBackground(_ application: UIApplication) {

    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    bgTask = application.beginBackgroundTask(withName:"MyBackgroundTask", expirationHandler: {() -> Void in
        // Do something to stop our background task or the app will be killed
        application.endBackgroundTask(self.bgTask)
        self.bgTask = UIBackgroundTaskIdentifier.invalid
    })

    DispatchQueue.global(qos: .background).async {
        //make your API call here
    }
    // Perform your background task here
    print("The task has started")
}
Run Code Online (Sandbox Code Playgroud)

后台过期处理程序将确保您有足够的时间在每次将应用程序置于非活动状态或被终止时启动 API 调用

阶段 2:确保 API 调用启动成功完成

尽管到期处理程序可能会确保您有足够的时间来启动 API 调用,但它无法确保 API 调用的成功完成。如果 API 调用需要更长的时间并且请求正在传输并且时间用完怎么办?

确保 API 调用一旦启动就成功的唯一方法是确保使用正确的配置 URLSession

根据文档

后台会话可让您在应用未运行时在后台执行内容的上传和下载。

链接:https : //developer.apple.com/documentation/foundation/nsurlsession?language=objc

所以利用后台会话并使用上传任务。与其使用简单的 get/post API,您将使用一些参数,而是让您的后端开发人员接受一个文件并将您的所有参数数据放在该文件中(如果有的话),并使用后台会话启动上传任务。

一旦上传任务从后台会话开始,即使您的应用程序被终止,iOS 也会处理它的完成(除非您显然以身份验证结束)。

我相信这是确保启动 API 调用并确保它在应用程序变为非活动/终止后完成的最接近的方法。我与苹果开发人员就此进行了讨论,他们同意这可能是一个可能的解决方案:)

希望能帮助到你