【问题标题】:If app sends a http request during termination, will the server receive it?如果app在终止期间发送http请求,服务器会收到吗?
【发布时间】:2015-07-15 02:35:54
【问题描述】:

我想知道,如果我的 iOS 应用程序正在终止,如果我发送 HTTP 请求通知服务器用户下线,服务器会收到此请求吗?

我的代码如下:

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    NSMutableDictionary *para = [[NSMutableDictionary alloc]initWithCapacity:0];
    [para setObject:[[NSUserDefaults standardUserDefaults] valueForKey:@"UserBindId"] forKey:@"unionId"];
    [para setObject:@(0) forKey:@"OnlineState"];
    [Post updateOnlineWithParameters:para withBlock:^(NSDictionary *commitResult, NSError *error) {
        NSLog(@"applicationWillTerminate = %@", commitResult);
    }];
}

【问题讨论】:

  • 当你尝试你的代码时会发生什么?
  • @MatthewBurke - 这通常是一个谨慎的问题(坦率地说,OP 应该已经描述了他的代码的结果),但这是一种经验测试不谨慎的情况.一个积极的结果(这很有可能)并不一定意味着这种模式是安全的(因为它不是)。解决请求和应用程序终止之间的这种竞争的最安全方法是简单地要求操作系统多一点时间来运行有限长度的任务。
  • @Rob - 好点。在了解提问者观察到的内容的更多细节后,我打算提出比赛条件。但这并不是回答问题的最佳方法。

标签: ios http


【解决方案1】:

请参阅 Executing Finite-Length Tasks 示例,了解如何在应用进入后台模式时让应用请求一点额外时间(最多 3 分钟,这对于您的目的应该绰绰有余)。

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    bgTask = [application beginBackgroundTaskWithName:@"GoingOffline" expirationHandler:^{
        // Well, we ran out of time before network request finished ... handle that however you want

        // but tell the OS that we understand, and that the background task is done

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

    NSDictionary *para = @{@"unionID"     : [[NSUserDefaults standardUserDefaults] valueForKey:@"UserBindId"],
                           @"OnlineState" : @0};

    [Post updateOnlineWithParameters:para withBlock:^(NSDictionary *commitResult, NSError *error) {
        // when done, tell the OS that the background task is done

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

我尝试稍微简化您的参数(不需要可变字典......您可以使用字典文字),因此请根据您的需要进行调整。但希望你能按照这里的基本思路,如果你想在应用进入后台时做某事,你必须请求权限。

【讨论】:

  • 谢谢。但是,(应用程序进入后台)和(应用程序将终止)之间有什么不同吗?如果应用终止,应用会得到 3 分钟任务吗?
  • 请参阅Execution States 了解应用程序生命周期的讨论。底线,如果用户刚刚离开您的应用程序,上述将保持应用程序在后台运行以完成网络请求,并且在此之前它不会被暂停或终止。如果用户手动终止了您的应用程序(例如双击主页按钮并向上滑动;或关闭设备电源),那么所有赌注都将关闭,您保证请求被发送的机会为零。
【解决方案2】:

您无法使用 http 请求从客户端提供故障安全用户在线/离线状态功能。正如 Rob 所说,如果应用程序被终止(强制退出或崩溃等),您将无能为力。提供这种功能的方法是使用网络套接字,它是电话和服务器之间的“恒定”双向通信。这样在服务器端就可以检查连接是否丢失了,说明客户端已经下线了。 自己创建这样的服务需要相当长的时间。幸运的是Firebase 提供了这样的软件和后端即服务。这是天赐之物。 This page 描述了如何管理离线和在线状态。这就像馅饼一样简单。

【讨论】:

    猜你喜欢
    • 2019-09-23
    • 1970-01-01
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多