【问题标题】:Sending BLE device data to server in background在后台向服务器发送 BLE 设备数据
【发布时间】:2019-04-07 18:26:31
【问题描述】:

我开发了一个从 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

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

【问题讨论】:

    标签: objective-c bluetooth-lowenergy mqtt core-bluetooth


    【解决方案1】:

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

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

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

    特别注意标题为Use Background Execution Modes Wisely的部分,具体如下:

    在被唤醒后,应用有大约 10 秒 的时间来完成一项任务。理想情况下,它应该尽快完成任务并允许自己再次挂起。在后台花费过多时间执行的应用程序可能会被系统限制或终止。

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

    【讨论】:

    • 但是如果我需要以特定的时间间隔来做,它支持这种机制吗?据我了解,设备必须说:“嘿,你有一些心率。你想读这个吗?” (例如)。
    • 如您所说,该设备会为您提供您随后处理的数据。我不认为你可以在特定的时间间隔被调用,除非你控制设备并且可以添加一个“ping”特性。
    • 是否可以在获取方法“performFetchWithCompletionHandler”中执行此操作?它有一个间隔。这不是一个严格的间隔,但是我可以用这种方法进行扫描、连接、写入、读取和发送到服务器吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    相关资源
    最近更新 更多