Realm sync with swiftUI widget?

How we can use realm sync in swiftUI widget? I used the same method to opening realm from swiftUI app by flexibleSyncConfiguration in getTimeline function but as user login on the main app it seems it can’t find the user on the widget.

In above link you said we can’t use realm sync instead we can use realm local.
Something has changes since then?

struct Provider: TimelineProvider {
    func placeholder(in context: Context) -> SimpleEntry {
        SimpleEntry(date: Date())
    }

func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
    let entry = SimpleEntry(date: Date())
    completion(entry)
}

func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
 
    if let user = app.currentUser {
        let config = user.flexibleSyncConfiguration(initialSubscriptions: { subs in
            if let _ = subs.first(named: "allTasks") {
                return
            } else {
                subs.append(QuerySubscription<TASK>(name: "allTasks") {
                    $0.owner_id == user.id
                })
            }
        })
        
        
        Realm.asyncOpen(configuration: config) { result in
            switch result {
            case .success(let realm):
                let allTasks = realm.objects(TASK.self)
                
           
                let timelineEntries = allTasks.map { section in
                    SimpleEntry(name: section.name)
                }
                
               
                let timeline = Timeline(entries: Array(timelineEntries), policy: .atEnd)
                completion(timeline)
                
            case .failure(let error):
                print("Failed to open Realm: \(error.localizedDescription)")

            }
            
        }
        
        
        
    }
    
}
}

struct SimpleEntry: TimelineEntry {
    let date: Date
}

struct taskWidgetEntryView : View {
    var entry: Provider.Entry

var body: some View {
    Text(entry.date, style: .time)
}
}

struct taskWidget: Widget {
    let kind: String = "taskWidget"

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

struct taskWidget_Previews: PreviewProvider {
    static var previews: some View {
        taskWidgetEntryView(entry: SimpleEntry(date: Date()))
            .previewContext(WidgetPreviewContext(family: .systemSmall))
    }
}
2 Likes

Hi, have you found the solution to this?