当用户终止应用程序时,我可以进行 api 调用吗? [英] Can I make an api call when the user terminates the app?

查看:31
本文介绍了当用户终止应用程序时,我可以进行 api 调用吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to make an API call when the user terminates the app (force close). The straight forward implementation I did is as below.

在应用委托中,我添加了以下代码.

In the app delegate, I added the following code.

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

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

However, the call is not being made. And on going through the documentation, I have found that I get only 5 seconds for completing the task in this method and above all, making api call is not a task to be done here. So I wonder, what would be the way to do this.

推荐答案

这是一个双重问题

阶段 1:确保 API 调用在用户每次终止应用时/在应用激活之前启动

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

You can always make use of expiration handler background mode of iOS application In your appdelegate

声明var bgTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0);

在你的 appdelegate 中

and in your 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 调用

Background expiration handler will ensure you will get enough time to start your API call every time you put your application turns inactive or gets terminated

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

虽然到期处理程序可以确保您有足够的时间来启动 API 调用,但它无法确保 API 调用的成功完成.如果 API 调用需要更长的时间,并且请求正在进行且时间用完怎么办?

Though expiration handler might ensure that you get enough time to start your API call it can't ensure the successful completion of API call. What if API call takes longer and while the request is in flight and time runs out??

确保 API 调用一旦启动就成功的唯一方法是确保对 URLSession

The only way you to ensure that API call gets successful once started is to make sure to use proper configuration for 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

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

So make use of Background session and use upload task. Rather than having a plain get/post API which you will hit with some parameter, ask your backend developer to accept a file and put all your param data in that file (if you have any) and start an upload task with background session.

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

Once the upload task starts with background session iOS will take care of its completion (unless u end up in a authentication challenge obviously) even after your app is killed.

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

This I believe is the closest you can get to ensure starting a API call and ensuring it finishes once app gets inactive/terminated. I kind a had a discussion with a apple developer regarding the same, and they agreed that this can be a probable solution :)

希望能帮到你

这篇关于当用户终止应用程序时,我可以进行 api 调用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆