Home > Enterprise >  Cannot use Task to make TimelineEntry inside getTimeline
Cannot use Task to make TimelineEntry inside getTimeline

Time:09-20

I am making widgets for WatchOS and i am struggling with the getTimeline and getSnapshot functions for TimelineProvider

The error: Type of expression is ambiguous without more context

This is the code inside getTimeline

Task {
    let price = try? await service.fetchPrices()
    if let priceSingle = price?.current {
       let entry = Entry(date: Date(), price: priceSingle, priceItems: price?.today!, isPlaceholder: false)
       let timeline = Timeline(entries: [entry], policy: TimelineReloadPolicy.after(Date().addingTimeInterval(60*30)))
       completion(timeline)
    } else {
         let entry = Entry.placeholder
         let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 2)))
         completion(timeline)   
        }
    }

The error happend when i added this line

let entry = Entry(date: Date(), price: priceSingle, priceItems: price?.today!, isPlaceholder: false)

Works fine when creating widgets for iOS. Maybe its a bug?

CodePudding user response:

It's because of price?.today! you cannot force wrapped optional like this, you need to write it like this (price?.today)!.

But this will crash your app if it's nil. So better to optionally wrapped using the nil-coalescing operator.

price?.today ?? [] //If it is an array
price?.today ?? "" //If it is a string

You haven't added Entry so I'm not sure what is the type of todayproperty but you can pass some default value after the ?? like above.

  • Related