Home > other >  iOS flutter workmanager fails when trying to execute http.get in background
iOS flutter workmanager fails when trying to execute http.get in background

Time:11-15

I have a project whereby I need the iOS to check a due date from an api in the background and schedule a notification on that date, however, whenever the code hits the http.get call it stops in Xcode. I have to run in Xcode to be able to simulate the background fetch.

Here is my main.dart:


import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:workmanager/workmanager.dart' as w;

List<String> accountList = [];
List<String> notificationList = [];
List<dynamic> dateInfo = [];
List<dynamic> accountInfo;
SharedPreferences myPrefs;
bool switchOne = true;
bool switchTwo = true;
bool switchThree = true;
//this is the name given to the background fetch
const simplePeriodicTask = "simplePeriodicTask";
w.Workmanager workmanager = w.Workmanager();

 Future<void> main() async {
   WidgetsFlutterBinding.ensureInitialized();
   await workmanager.initialize(callbackDispatcher, isInDebugMode: true);
   await NotificationService().initialize();
   runApp(BWSApp());
 }

 void setSwitches() async {

   WidgetsFlutterBinding.ensureInitialized();
   myPrefs = await SharedPreferences.getInstance();

   switchOne = (myPrefs.getBool('switchOne') ?? false);
   switchTwo = (myPrefs.getBool('switchTwo') ?? false);
   switchThree = (myPrefs.getBool('switchThree') ?? false);

   if(myPrefs.getStringList('accounts') != null){
      for(var i = 0; i < myPrefs.getStringList('accounts').length; i  ){
        accountList.add(myPrefs.getStringList('accounts')[i]);
        notificationList.add(myPrefs.getStringList('notificationId')[i]);
        http.Response result = await http.get(Uri.parse("https://reqres.in/api/users?page=2"));
        print("doesn't even get here");
        _getDueDate(json.decode(result.body), myPrefs.getStringList('notificationId')[i]);
      }
    }
 }

void callbackDispatcher() {
   print("callBackDispatcher");
  workmanager.executeTask((task, inputData) async{
    setSwitches();
    return Future.value(true);
  });
}

And here is my AppDelegate.swift:

import UIKit
import Flutter
import workmanager
import shared_preferences

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {


    GeneratedPluginRegistrant.register(with: self)

    WorkmanagerPlugin.register(with: self.registrar(forPlugin: "be.tramckrijte.workmanager.WorkmanagerPlugin")!)

    UNUserNotificationCenter.current().delegate = self

    UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))


    WorkmanagerPlugin.setPluginRegistrantCallback { registry in
        AppDelegate.registerPlugins(with: registry)
        FLTSharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "io.flutter.plugins.sharedpreferences.SharedPreferencesPlugin")!)


    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }

    static func registerPlugins(with registry: FlutterPluginRegistry) {
               GeneratedPluginRegistrant.register(with: registry)
          }

    override func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
         completionHandler(.alert)
     }

}

In Xcode I simulate the background fetch and I can print something until it reaches the http.get then at that point it looks like it just stops. Any help appreciated.

CodePudding user response:

I simply needed to put my setSwitches function as a Future.

  • Related