Alexandr Kolesnik
Alexandr Kolesnik

Reputation: 2204

Send request in applicationWillTerminate

In my app I need to send some instructions to server when the user terminated an app. In applicationWillTerminate func I tried to send it, but it never came to server. I tried to use Alamofire and native URLSession but it doesn't work. Does anybody know how can I send it? I use this code

                let request = "\(requestPrefix)setDriverOrderStatus"
    if let url = URL(string:request) {
        var parameters : [String : String] = [:]
        parameters["access_token"] = UserSession.accessToken
        parameters["driver_id"] = UserSession.userID
        parameters["status"] = status
        var req = URLRequest(url: url)
        req.httpMethod = HTTPMethod.put.rawValue
        do {
            req.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted)
        } catch let error {
            print(error.localizedDescription)
        }
        _ = URLSession.shared.dataTask(with: req, completionHandler: { data, response, error in
            guard error == nil else {
                print(error ?? "error")
                return
            }
            guard let data = data else {
                print("Data is empty")
                return
            }
            let json = try! JSONSerialization.jsonObject(with: data, options: [])
            print(json)
        }).resume
    }

Upvotes: 3

Views: 4145

Answers (2)

One solution that worked for me is to add sleep at the end of the applicationWillTerminate function like this :

func applicationWillTerminate(_ application: UIApplication) {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    // Saves changes in the application's managed object context before the application terminates.

    // HERE YOU will make you HTTP request asynchronously
    self.postLogoutHistory()

    // 3 is the number of seconds in which you estimate your request 
    // will be finished before system terminate the app process

    sleep(3)

    print("applicationWillTerminate")

    // self.saveContext()
}

Upvotes: 15

Ketan Parmar
Ketan Parmar

Reputation: 27448

put breakpoint in applicationWillTerminate and check that, function is getting called or not because applicationWillTerminate is not called everytime when application is getting terminated, especially when user quit application manually from multitasking window, applicationWillTerminate will not get called! When system terminates the application at that time applicationWillTerminate will get called and you will got approximately five seconds to complete your task!! So, it is not good idea to perform network related task on applicationWillTerminate!!

Refer Apple Documentation for applicationWillTerminate, It states,

This method lets your app know that it is about to be terminated and purged from memory entirely. You should use this method to perform any final clean-up tasks for your app, such as freeing shared resources, saving user data, and invalidating timers. Your implementation of this method has approximately five seconds to perform any tasks and return. If the method does not return before time expires, the system may kill the process altogether.

For apps that do not support background execution or are linked against iOS 3.x or earlier, this method is always called when the user quits the app. For apps that support background execution, this method is generally not called when the user quits the app because the app simply moves to the background in that case. However, this method may be called in situations where the app is running in the background (not suspended) and the system needs to terminate it for some reason.

After calling this method, the app also posts a UIApplicationWillTerminate notification to give interested objects a chance to respond to the transition.

Upvotes: 0

Related Questions