在后台向服务器发送 BLE 设备数据

Sending BLE device data to server in background

我开发了一个从 BLE 设备读取数据并将此数据发送到 MQTT 代理(服务器)的应用程序。但是当应用程序进入后台时,数据发送在 3 分钟后停止(我使用后台任务)。我如何增加这个时间。或者,也许有一种官方机制,Apple 提倡并且不会拒绝在 App Store 上的确认步骤,用于从 BLE 读取数据并在不受时间限制的后台将此数据发送到服务器?

我的后台任务:

AYBackgroundTask.h

@interface AYBackgroundTask : NSObject

@property (assign) UIBackgroundTaskIdentifier identifier;
@property (strong, nonatomic) UIApplication *application;

+ (void)run:(void(^)(void))handler;

- (void)begin;
- (void)end;

@end

AYBackgroundTask.m

@implementation AYBackgroundTask

+ (void)run:(void(^)(void))handler {
  AYBackgroundTask *task = [[AYBackgroundTask alloc] init];
  [task begin];
  handler();
}

- (void)begin {
  self.identifier = [self.applicationn beginBackgroundTaskWithExpirationHandler:^{
    [self end];
  }];
}

- (void)end {
  if (self.identifier != UIBackgroundTaskInvalid) {
    [self.application.application endBackgroundTask:self.identifier];
  }
  self.identifier = UIBackgroundTaskInvalid;
}

@end

这里有谁遇到过这个问题? 最好的祝福, 安东.

总而言之,beginBackgroundTaskWithExpirationHandler 不起作用 - 使用 Core Bluetooth Background Processing for iOS Apps。仔细阅读它,因为如果您错过了一点,您可能不会出错 - 它会默默地失败。

您需要首先将此添加到您的 Info.plist:

<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
</array>

请特别注意标题为 Use Background Execution Modes Wisely 的部分,特别是:

Upon being woken up, an app has around 10 seconds to complete a task. Ideally, it should complete the task as fast as possible and allow itself to be suspended again. Apps that spend too much time executing in the background can be throttled back by the system or killed.

虽然 MQTT 很棒,但您可能需要切换到 NSURLSessionUploadTask,因为上传是在 OS 的其他地方异步进行的,因此时间不会计入您的 10 秒。