0

I'm trying to get SwiftUI Previews working (with already downloaded API data) so that I don't need to run the app in simulator. Not sure what is wrong/how to go about it.

I've seen a few YouTube and (a lot) of SO on how to get this done but still hitting a wall. Appreciate pointers. (Note: 1st time trying to learn SwiftUI by porting a view of my app)

The data is going to be read-only, so there's no use for @State or @Bindings I believe and shouldn't be part of the @EnvironmentObject as well?

The YouTube's I've seen and google links are mainly using (locally stored) JSON files and they work.

eg: https://www.youtube.com/watch?v=hfjZNwayXfg and https://www.youtube.com/watch?v=EycwLxTU-EA

@available(iOS 13, *)
struct avatarView: View {
  let weeklySummary: [HelperIntervalsIcu.icuWeeklyData]
  
  func getAvatarPic() -> UIImage? {
      if let avatarUrl = weeklySummary.last?.icuAvatar {
        let avatarPicName = URL(fileURLWithPath: avatarUrl).lastPathComponent
        let avatarPicImage = HelperIntervalsIcu.loadAvatarPic(fileName: avatarPicName)
        return avatarPicImage
      }
    return nil
  }
  
  func getUserName() -> String {
    if let userName = weeklySummary.last?.icuName {
      return userName.prefix(1).capitalized + userName.dropFirst()
    }
    return "User Name Placeholder"
  }
  
  var body: some View {
    HStack {

      if let image = getAvatarPic() {
        Image(uiImage: image)
      } else {
        Image("profile-200x200")
      }
      Text(getUserName())
      Spacer()
    }
    
  }
}

@available(iOS 13.0, *)
struct IntervalsWeeklyView_Previews: PreviewProvider {
    static var previews: some View {
      let weeklySummary = HelperIntervalsIcu.loadWeeklySummaryFromFile()
      avatarView(weeklySummary: weeklySummary)
     
    }
}

The Preview just shows this

enter image description here

But when running in the simulator, it will work.

enter image description here

The data within HelperIntervalsIcu.icuWeeklyData is from a struct

  struct icuWeeklyData : Codable {
    var icuName : String
    var icuAvatar : String
  } 
app4g
  • 670
  • 4
  • 24
  • Simulator and preview have different environments and real locations in file system – Asperi Jul 14 '22 at 06:53
  • @Asperi oh man.. this is a real ‍♂️ moment after going down this rabbit hole. Found this, https://stackoverflow.com/q/59437497/14414215 but can't get it to print out the path. Any ideas – app4g Jul 14 '22 at 07:07
  • 1
    That's bad way... Apple designed explicit place for Preview resources. See this https://stackoverflow.com/a/63932269/12299030. And actually Preview is not for testing... it is for UI preview. – Asperi Jul 14 '22 at 07:11
  • TQ for the link. My UIKit project doesn't have this folder at all. Is manually adding it a possibility? Also - I am using the Canvass Preview for UI Preview (on already downloaded API data) so I can have faster feedback on the views layout etc. – app4g Jul 14 '22 at 07:20

0 Answers0