我目前正在使用 expo sdk-version 32 开发适用于iOS的应用。我必须定期从我的应用程序调用REST服务。为此,我尝试利用新的BackgroundFetch API。
这是我的代码:
const BACKGROUND_LOCATION_SENDING_TASK = "BACKGROUND_LOCATION_SENDING_TASK";
async function initBackgroundLocationSending() {
console.log("initBackgroundLocationSending()");
TaskManager.defineTask(BACKGROUND_LOCATION_SENDING_TASK, () => {
// this console.log does never get called ...
console.log("BACKGROUND_LOCATION_SENDING_TASK");
// i will implement real fetch logic here when i found out how to get this function called.
return BackgroundFetch.Result.NewData;
});
console.log("is task registered ... ");
let isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
console.log("isRegistered: ", isRegistered);
if(isRegistered) {
console.log("unregister task ...");
await BackgroundFetch.unregisterTaskAsync(BACKGROUND_LOCATION_SENDING_TASK);
console.log("Done");
}
console.log("is task registered ... ");
isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
console.log("isRegistered: ", isRegistered);
console.log("register task ...");
await BackgroundFetch.registerTaskAsync(BACKGROUND_LOCATION_SENDING_TASK);
console.log("OK");
console.log("is task registered ... ");
isRegistered = await TaskManager.isTaskRegisteredAsync(BACKGROUND_LOCATION_SENDING_TASK);
console.log("isRegistered: ", isRegistered);
console.log("set minimum interval ...");
await BackgroundFetch.setMinimumIntervalAsync(60);
console.log("OK");
console.log("get status ... ");
const status = await BackgroundFetch.getStatusAsync();
console.log("status: ", status);
}
从 App.js 内部调用该函数的控制台输出:
: initBackgroundLocationSending()
: is task registered ...
: isRegistered: true
: unregister task ...
: OK
: is task registered ...
: isRegistered: false
: register task ...
: OK
: is task registered ...
: isRegistered: true
: set minimum interval ...
: OK
: get status ...
: status: 3
根据expo's background-fetch documentation,我了解到状态:3 表示BackgroundFetch.Status.Available
。
我的 app.json 中的 iOS 部分:
...
"ios": {
"supportsTablet": true,
"bundleIdentifier": "xxx-yyy-zzz",
"infoPlist": {
"UIBackgroundModes": [
"location",
"fetch"
],
"NSLocationWhenInUseUsageDescription": "... (replaced)",
"NSLocationAlwaysAndWhenInUseUsageDescription": "... (replaced)",
"NSLocationAlwaysUsageDescription": "... (replaced)"
}
},
...
我的测试设备是带有iOS 12.1.3的iPhone 6s。
我想念什么?为什么即使几分钟后它也根本不运行任务?
顺便说一句:我使用expo's background location没问题