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

标签 ios swift appdelegate applicationwillterminate

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

在应用委托(delegate)中,我添加了以下代码。

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("-----")
                  }
}

但是,没有进行调用。并通过 documentation ,我发现我只有 5 秒才能完成此方法中的任务,最重要的是,调用 api 不是这里要完成的任务。所以我想知道,这样做的方法是什么。

最佳答案

这是一个双重问题

第 1 阶段:确保 API 调用在每次用户终止应用程序时/在应用程序变为事件状态之前启动

您始终可以在您的 appdelegate 中使用 iOS 应用程序expiration handler 后台模式

声明 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")
}

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

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

虽然过期处理程序可以确保您有足够的时间开始 API 调用,但它不能确保 API 调用成功完成。如果 API 调用花费的时间更长,并且请求正在进行中并且时间用完了怎么办??

确保 API 调用一旦开始就成功的唯一方法是确保为 URLSession

使用正确的配置

根据文档

Background sessions let you perform uploads and downloads of content in the background while your app isn't running.

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

所以利用后台 session 并使用上传任务。与其拥有一个普通的获取/发布 API,您将使用一些参数点击它,不如让您的后端开发人员接受一个文件并将所有参数数据放入该文件(如果有的话),然后使用后台 session 启动上传任务。

一旦上传任务以后台 session 开始,即使您的应用被终止,iOS 也会处理它的完成(除非您显然最终遇到身份验证挑战)。

我认为这是您可以确保启动 API 调用并确保在应用程序处于非事件/终止状态时完成调用的最接近方法。我与苹果开发人员就此进行了讨论,他们同意这可能是一个可能的解决方案:)

希望对你有帮助

关于ios - 当用户终止应用程序时,我可以进行 api 调用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55234914/

相关文章:

ios - 编写第二个排行榜

ios - Swift:我应该为 Firebase 管理器类使用静态成员吗​​?好的程序设计

swift - 无法将 Swift 隐式解包可选声明为常量

ios - Swift 显示应用内购买的促销代码 View 不执行任何操作

ios - 如何将rightBarButtonItem传递给TabBarController中的所有ViewController?

ios - 快速组合 : How to specify the Error type of tryMap(_:)?

ios - 使用 xcode 布局约束将显示元素放置在另一个显示元素中

Swift:将包含自定义标签的单元格添加到 UITableView

Swift appdelegate 错误 - appdelegate 未确认协议(protocol)

ios - iOS Objective-C 中 Singleton 类和 AppDelegate 类的关系