ABausG / home_widget

Flutter Package for Easier Creation of Home Screen Widgets
776 stars 213 forks source link

iOS widget doesn't update #89

Closed ismailfateen closed 2 years ago

ismailfateen commented 2 years ago

Hello, my iOS widget won't give me an error (the function returns true), and it won't update the widget either.

I set my group id as group.salamlabs.salamapp.HomeWidget and it is configured correctly.

AppDelegate.swift

import UIKit
import Flutter
import workmanager

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
      UIApplication.shared.setMinimumBackgroundFetchInterval(TimeInterval(60*15))
       //return true

//   if #available(iOS 10.0, *) {
//     UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
//   }
      GeneratedPluginRegistrant.register(with: self)
      UNUserNotificationCenter.current().delegate = self
WorkmanagerPlugin.setPluginRegistrantCallback { registry in
    GeneratedPluginRegistrant.register(with: registry)
}

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

      override func userNotificationCenter(
              _ center: UNUserNotificationCenter,
              willPresent notification: UNNotification,
              withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
               completionHandler(.alert) // shows banner even if app is in foreground
           }

}

HomeWidget.swift

//
//  HomeWidget.swift
//  HomeWidget
//
//  Created by Ismail Fateen on 11/06/2022.
//

import WidgetKit
import SwiftUI

private let widgetGroupId = "group.salamlabs.salamapp.HomeWidget"

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> ExampleEntry {
        ExampleEntry(date: Date(), title: "Placeholder Title", message: "Placeholder Message")
    }

    func getSnapshot(in context: Context, completion: @escaping (ExampleEntry) -> ()) {
        let data = UserDefaults.init(suiteName:widgetGroupId)
        let entry = ExampleEntry(date: Date(), title: data?.string(forKey: "title") ?? "No tiTLE sET", message: data?.string(forKey: "message") ?? "No meSSaGE sEt")
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        getSnapshot(in: context) { (entry) in
            let timeline = Timeline(entries: [entry], policy: .atEnd)
            completion(timeline)
        }
    }
}

struct ExampleEntry: TimelineEntry {
    let date: Date
    let title: String
    let message: String
}

struct HomeWidgetExampleEntryView : View {
    var entry: Provider.Entry
    let data = UserDefaults.init(suiteName:widgetGroupId)

    var body: some View {
        VStack.init(alignment: .leading, spacing: nil, content: {
            Text(entry.title).bold().font(.title)
            Text(entry.message)
                .font(.body)
                .widgetURL(URL(string: "homeWidgetExample://message?message=\(entry.message)&homeWidget"))
        }
        )
    }
}

@main
struct HomeWidgetExample: Widget {
    let kind: String = "HomeWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            HomeWidgetExampleEntryView(entry: entry)
        }
        .configurationDisplayName("My Widget")
        .description("This is an example widget.")
    }
}

struct HomeWidgetExample_Previews: PreviewProvider {
    static var previews: some View {
        HomeWidgetExampleEntryView(entry: ExampleEntry(date: Date(), title: "Example Title", message: "Example Message"))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}

Code that “updates” the widget:

                  await HomeWidget.setAppGroupId(
                      "group.salamlabs.salamapp.HomeWidget");
                  await HomeWidget.saveWidgetData("title", "yes");
                  await HomeWidget.saveWidgetData("message", "no");
                  var result = await HomeWidget.updateWidget(
                      iOSName: "HomeWidget", name: "HomeWidget");
                  print(result.toString()); // prints `true`, doesn't update

flutter doctor -v

[✓] Flutter (Channel stable, 2.10.5, on macOS 13.0 22A5266r darwin-arm, locale
    en-EG)
    • Flutter version 2.10.5 at /opt/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5464c5bac7 (8 weeks ago), 2022-04-18 09:55:37 -0700
    • Engine revision 57d3bac3dd
    • Dart version 2.16.2
    • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version
    32.1.0-rc1)
    • Android SDK at /Users/ismailfateen/Library/Android/sdk
    • Platform android-32, build-tools 32.1.0-rc1
    • Java binary at: /Applications/Android
      Studio.app/Contents/jre/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.4.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • CocoaPods version 1.11.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build
      11.0.12+0-b1504.28-7817840)

[✓] IntelliJ IDEA Community Edition (version 2022.1.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart

[✓] VS Code (version 1.68.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.42.0

[✓] Connected device (2 available)
    • iPhone SE (3rd generation) (mobile) • 393BE168-DDAA-4F01-9ED8-63624660D2FD
      • ios            • com.apple.CoreSimulator.SimRuntime.iOS-15-5 (simulator)
    • Chrome (web)                        • chrome
      • web-javascript • Google Chrome 102.0.5005.61

[✓] HTTP Host Availability
    • All required HTTP hosts are available

• No issues found!
Sparko-Sol commented 2 years ago

@ismailfateen did you find any solution? I am also getting the same issue.

ismailfateen commented 2 years ago

Sorry I haven't updated/closed this issue yet. It's apparently because I only added the groupId to the HomeWidgetExtension, but it should be added to the Runner target as well, hope that helps!

ismailfateen commented 2 years ago

@Sparko-Sol

Sparko-Sol commented 2 years ago

@ismailfateen I tried but it's still not working. Can you explain a little bit more? Data has been sent to the widget but the widget is not showing that data.

AleksanderFranczak commented 2 years ago

@ismailfateen That helped me a lot, after adding the same group id to runner and my extension It worked like a charm, thanks!