我需要在用户终止应用程序(强制关闭)时进行 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/