iOS平台Flutter Workmanager后台执行http.get请求失败如何解决
问题原因及修复方案
1. 核心问题:异步任务未等待导致后台进程提前终止
你当前在workmanager的任务回调中调用异步方法setSwitches()时没有加await,导致任务还没执行到http请求就提前向系统返回了任务完成状态,iOS会立刻杀掉后台任务进程,所以http请求刚触发就被中断。
修复代码:
首先修改setSwitches的返回值类型为Future<void>,同时新增异常捕获避免未处理错误导致崩溃:
Future<void> setSwitches() async { WidgetsFlutterBinding.ensureInitialized(); myPrefs = await SharedPreferences.getInstance(); try { switchOne = (myPrefs.getBool('switchOne') ?? false); switchTwo = (myPrefs.getBool('switchTwo') ?? false); switchThree = (myPrefs.getBool('switchThree') ?? false); if(myPrefs.getStringList('accounts') != null){ final accounts = myPrefs.getStringList('accounts')!; final notificationIds = myPrefs.getStringList('notificationId')!; for(var i = 0; i < accounts.length; i++){ accountList.add(accounts[i]); notificationList.add(notificationIds[i]); // 新增请求层面的异常捕获 try { http.Response result = await http.get(Uri.parse("https://reqres.in/api/users?page=2")); print("请求完成,状态码:${result.statusCode}"); _getDueDate(json.decode(result.body), notificationIds[i]); } catch (e) { print("HTTP请求异常:$e"); } } } } catch (e) { print("后台任务执行异常:$e"); } }
然后修改callbackDispatcher,等待setSwitches执行完成再返回任务状态:
void callbackDispatcher() { print("callBackDispatcher"); workmanager.executeTask((task, inputData) async{ await setSwitches(); // 新增await等待异步任务全部执行完成 return Future.value(true); }); }
2. iOS权限配置检查
- 打开Xcode项目,进入
Signing & Capabilities标签,添加Background Modes能力,勾选 Background fetch 和 Remote notifications 两个选项 - 检查
Info.plist中的网络权限配置,如果你后续会用到HTTP请求,需要添加NSAppTransportSecurity的相关例外规则,纯HTTPS请求可忽略该配置
3. 后台模拟注意事项
用Xcode触发后台fetch模拟时,需要先把应用切到后台,不要在前台运行状态下触发模拟,避免系统行为和实际后台场景不一致。
内容的提问来源于stack exchange,提问作者Kristin Vernon
相关产品推荐
相关产品推荐

