问题
I develop an application that reading data from BLE device and send this data to MQTT broker (server). But when application entering to the background, data sending stopped after 3 minutes (I use Background Tasks). How I can increase this time. Or maybe there is an official mechanism, that Apple promotes and will not reject on the confirmation step on App Store, for reading data from BLE and sending this data to the server in the background that not limited by time?
My Background Task:
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
There is here who faced with this problem? Best regards, Anton.
回答1:
To summarise, beginBackgroundTaskWithExpirationHandler
will not work - use Core Bluetooth Background Processing for iOS Apps. Read it thoroughly as you likely won't get errors if you miss a bit out - it will silently fail.
You'll need to start by adding this to your Info.plist
:
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
Pay special attention to the section entitled Use Background Execution Modes Wisely, specifically:
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.
While MQTT is fantastic, you may need to switch to NSURLSessionUploadTask as the upload happens asynchronously elsewhere in the OS so the time won't count against your 10 seconds.
来源:https://stackoverflow.com/questions/55562315/sending-ble-device-data-to-server-in-background