最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swiftui - Loading image data for Preview - Stack Overflow

programmeradmin2浏览0评论

Im trying to load sample date for view Previews in SwiftUI from a SwiftData model. I created an extension to the SwiftData model show below to load sample data for Previews as shown below. In the app imageData is stored in the SwiftData model by using the getDataFrom function I listed below as well which loads the image from URL, converts to Data and saves in SwiftData. I'm stuck on how to load imageData for a View Preview???

@Model class BookWithMatchingData: Identifiable, Codable, Hashable { 
    var author: String
    var isbn13gd: String
    var title: String
    @Attribute(.externalStorage) var imageData: Data?
...

// create sample data for preview
extension BookWithMatchingData {
    static var sample: [BookWithMatchingData] {
        [
            BookWithMatchingData(
                isbn13gd: "9781538724736",
                title: "Sample Title",
                author: "Sample Author",
                //imageData: ????
            )

        ]
    }
}
//
func getDataFrom(url: String) async -> Data? {
        do {
            let (data, _) = try await URLSession.shared.data(from: URL(string: url)!)
            return data
        } catch {
            print("Error fetching data: \(error)")
            return nil
        }
    }

Im trying to load sample date for view Previews in SwiftUI from a SwiftData model. I created an extension to the SwiftData model show below to load sample data for Previews as shown below. In the app imageData is stored in the SwiftData model by using the getDataFrom function I listed below as well which loads the image from URL, converts to Data and saves in SwiftData. I'm stuck on how to load imageData for a View Preview???

@Model class BookWithMatchingData: Identifiable, Codable, Hashable { 
    var author: String
    var isbn13gd: String
    var title: String
    @Attribute(.externalStorage) var imageData: Data?
...

// create sample data for preview
extension BookWithMatchingData {
    static var sample: [BookWithMatchingData] {
        [
            BookWithMatchingData(
                isbn13gd: "9781538724736",
                title: "Sample Title",
                author: "Sample Author",
                //imageData: ????
            )

        ]
    }
}
//
func getDataFrom(url: String) async -> Data? {
        do {
            let (data, _) = try await URLSession.shared.data(from: URL(string: url)!)
            return data
        } catch {
            print("Error fetching data: \(error)")
            return nil
        }
    }
Share Improve this question asked Mar 17 at 18:47 user1233894user1233894 1,7761 gold badge12 silver badges11 bronze badges 3
  • There is a specific asset catalog in your project for previews so you could add an image to that catalog and load it from there instead – Joakim Danielson Commented Mar 17 at 19:17
  • Note, @Model class already conforms to Identifiable and Hashable, no need to do it again. There are a number of SO posts on how to use SwiftData with Previews, search for them. See also, hackingwithswift/quick-start/swiftdata/…. What have you tried? – workingdog support Ukraine Commented Mar 18 at 0:08
  • To clarify, for the Preview, are you trying to load the imageData that is already stored in the model or are you trying to load the imageData from the remote url or are you trying to simply show a mock image without making any url calls? – Andrei G. Commented Mar 18 at 19:08
Add a comment  | 

1 Answer 1

Reset to default 0

Apple has provided PreviewModifier so you can create and quickly reuse preview Context

struct SwiftDataPreview: PreviewModifier {

    static func makeSharedContext() async throws -> Context {
        // Mock/In-Memory container code
    }
    
    typealias Context = ModelContainer

    
    func body(content: Content, context: Context) -> some View {
        content
            .modelContainer(context)
            .task {
               // create and insert sample models
            }
    }
}

extension PreviewTrait where T == Preview.ViewTraits {
    @MainActor static var swiftDataNull: Self = .modifier(SwiftDataPreview())
}

Then you can use it anywhere

#Preview(traits: .swiftDataNull) { // <--- Here
    ContentView()
}
发布评论

评论列表(0)

  1. 暂无评论