WeatherKit and SwiftUI

I'm trying out weather kit and I'm using swiftUI

I have a view that accepts a CurrentWeather type value in initailizer

I cannot find a way to initialize a CurrentWeather

How can I preview It?

This won't work:

// forecaster and forecast is defined by me
struct WeatherView_Previews: PreviewProvider {
    static var previews: some View { // <- static
        WeatherView(weather: await forecaster.forcast(latitude: 0, longtitude: 0)) // <- concurrency
    }
}
Answered by Developer Tools Engineer in 717709022

Hi,

Using concurrency to provide data for your previews will work fine for the default, live preview; but is unlikely to work well for the Selectable one nor the variations.

If you want your preview to be usable in those more static cases then you will need to refactor things such that you can pass in basic types to your view rather than something that takes time to be generated or fetched.

Hard to give more than general advice unless I know more about what your WeatherView is doing, but an example would be to use previews on a view within your WeatherView by refactoring out the parts that actually depends on the weather and give it an initializer like what this snippet from the FoodTruck app uses (this was a sample app used for many of the WWDC presentations):

struct RecommendedParkingSpotCard: View {
    var parkingSpot: ParkingSpot
    var condition: WeatherCondition
    var temperature: Measurement<UnitTemperature>
    var symbolName: String
    <…>

Accepted Answer

Hi,

Using concurrency to provide data for your previews will work fine for the default, live preview; but is unlikely to work well for the Selectable one nor the variations.

If you want your preview to be usable in those more static cases then you will need to refactor things such that you can pass in basic types to your view rather than something that takes time to be generated or fetched.

Hard to give more than general advice unless I know more about what your WeatherView is doing, but an example would be to use previews on a view within your WeatherView by refactoring out the parts that actually depends on the weather and give it an initializer like what this snippet from the FoodTruck app uses (this was a sample app used for many of the WWDC presentations):

struct RecommendedParkingSpotCard: View {
    var parkingSpot: ParkingSpot
    var condition: WeatherCondition
    var temperature: Measurement<UnitTemperature>
    var symbolName: String
    <…>

WeatherKit and SwiftUI
 
 
Q