当用户按下主页按钮时在服务器中保存日期

Save Date in server when user press home button

我想在用户触摸主页按钮时将应用程序中使用的所有数据保存在服务器中(使用 API 调用)。我将观察者设置为

[[NSNotificationCenter defaultCenter]  addObserver:self selector:@selector(saveData) name:UIApplicationDidEnterBackgroundNotification object:nil];

saveData方法用于将数据发送到服务器。 api 调用无效。当用户关闭应用程序时调用 API 的任何方式。

我已经启动了后台任务

- (void)applicationDidEnterBackground:(UIApplication *)application
{


      bgTask = [application beginBackgroundTaskWithName:@"MyTask" expirationHandler:^{

[self saveData];
            // Clean up any unfinished task business by marking where you
            // stopped or ending the task outright.

        }];

    // Start the long-running task and return immediately.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // Do the work associated with the task, preferably in chunks.

        [application endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    });
}

然后在 saveData 方法中添加以下行

 [application endBackgroundTask:bgTask];
            bgTask = UIBackgroundTaskInvalid;