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": "[email protected]"],
encoding: JSONEncoding.default,
headers: contentHeader).responseJSON { (response) -> Void in
print("-----")
}
}
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.
If you need to execute code when your app isn't running, there are several options open to you depending on what you're trying to do. Background fetch will let your app run in the background for about 30 seconds at scheduled intervals. The goal of this is to fetch data and prepare your UI for when the app runs next.
Examples of API callsOnce the server validates that the correct username and password have been provided, the user is granted access to the application. Another context to think about API calls in is when you go to book a flight.
Application programming interfaces (APIs) are a way for one program to interact with another. API calls are the medium by which they interact. An API call, or API request, is a message sent to a server asking an API to provide a service or information.
The user initiates an API call that tells the application to do something, then the application will use an API to ask the web server to do something. The API is the middleman between the application and the web server, and the API call is the request.
That’s where API calls come in. What is an API Call? An API call is the process of a client application submitting a request to an API and that API retrieving the requested data from the external server or program and delivering it back to the client. Let’s say your app uses Facebook APIs to extract data and functionality from the platform.
To make an API call to Google’s Cloud Natural Language API, you must include an API key as a query parameter. For example, let’s say you want to find named entities (ie. proper names and common nouns) in a body of text. Then you’d make the following API request, replacing API_KEY with your actual API key:
Made up of a string of letters and numbers that identify the client application making the request, an API key or access token is used to grant or deny requests based on the client’s access permissions, and track the number of requests made for usage and billing purposes.
This is a two fold question
Phase 1: Ensuring API Call starts every time user terminates the app/ before it turns in active
You can always make use of expiration handler
background mode of iOS application
In your appdelegate
declare
var bgTask: UIBackgroundTaskIdentifier = UIBackgroundTaskIdentifier(rawValue: 0);
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")
}
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
Phase 2: Ensuring API call started finishes successfully
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??
The only way you to ensure that API call gets successful once started is to make sure to use proper configuration for URLSession
As per docs
Background sessions let you perform uploads and downloads of content in the background while your app isn't running.
link: https://developer.apple.com/documentation/foundation/nsurlsession?language=objc
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.
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.
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 :)
hope it helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With