CoreBluetooth in Background at Scheduled Time

 ̄綄美尐妖づ 提交于 2019-12-04 04:16:33

I know I've already accepted an answer for this (sorry!), but I've found a solution:

[[UIApplication sharedApplication] setMinimumBackgroundFetchInterval:60*5]; // Every 5 minutes, minimum

in:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

and adding fetch to UIBackgroundModes, which iOS then calls:

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler

every 15-240 minutes (yeah, it varies a lot, but it's better than nothing). Every time I am called to perform a fetch, I connect to the peripheral, sync and send its data to the server, then disconnect. Since I'm sending this data from the BLE peripheral to a server for processing/storage, I'm presuming that this is a legitimate (AppStore worthy) use of fetch.

CAVEAT: application:performFetchWithCompletionHandler: will not be called until iOS establishes a user usage pattern for the app. In other words, you need to keep the app around (not delete it) for about 24 hours or so before the application:performFetch... method gets called. Boy, did it take a while to figure that out!

UPDATE: Apple has accepted my app that used this solution (approved May 2014).

You can't. A backgrounded app cannot start any transactions, it can only react to incoming requests (data notifications, connection events...) In the background the application is effectively not running and even in case of BLE events it has only 8 seconds to go back to sleep, otherwise it is completely terminated for breaking the policy.

The only case when your app can stay alive for a while is when it uses the beginBackgroundTaskWithName:expirationHandler: API. But even in that case it has only 10 minutes to complete or it gets killed.

If you want to synchronize while in background, then the transaction must be started on the external peripheral's side. Easiest is to stay connected and send a notification to the central every once in a while. That will wake it up and it can proceed with reading the characteristics it needs. But there are several other ways to implement it. The final solution has to be designed to best meet your needs. If you have a concrete idea, then please submit it as a separate question.

https://developer.apple.com/hardwaredrivers/BluetoothDesignGuidelines.pdf

I'm pretty sure you guys have seen this, but just in case you haven't. Perhaps on the BLE Peripheral end you can save power by increasing the connection interval (page 22).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!