Cannot preview in this file - App may have crashed

Hi,


I am working with SwiftUI, and am new to Xcode, and Swift at all.

I did the SwiftUI essentials Tutorial, and done the Controls and Views part.


Now I am stuck on my own creation app.

I try to get data from an local .json file which I stored in the Resources folder.

In the preview View, I pass in the data of index 0, but while rendering the preview it always crashes, and cannot build a preview.


I almost copied all the files from the BuildingListsAndNavigations project.


This is my View where I try to post from the json file


import SwiftUI

struct UserRow : View {
    var user: User

    var body: some View {
        Text(user.name)
    }
}

#if DEBUG
struct UserRow_Previews : PreviewProvider {
    static var previews: some View {
        UserRow(user: userData[0])
    }
}
#endif



here is the data.swift file


import UIKit
import SwiftUI
import CoreLocation

let userData: [User] = load("users.json")

func load<T: Decodable>(_ filename: String, as type: T.Type = T.self) -> T {
    let data: Data
    
    guard let file = Bundle.main.url(forResource: filename, withExtension: nil)
        else {
            fatalError("Couldn't find \(filename) in main bundle.")
    }
    
    do {
        data = try Data(contentsOf: file)
    } catch {
        fatalError("Couldn't load \(filename) from main bundle:\n\(error)")
    }
    
    do {
        let decoder = JSONDecoder()
        return try decoder.decode(T.self, from: data)
    } catch {
        fatalError("Couldn't parse \(filename) as \(T.self):\n\(error)")
    }
}


Why does it crash? Did I miss something?

Replies

Can you include the code where you actually call UserRow (and presumably load a User object from userData?

Hi @eren93

I'm having this exact same issue! Were you ever able to get to the bottom of it?
I am facing the same issue, tried many ways like restarting the system, creating new project etc. Still the issue exists.
You aren't searching the resources folder. Lets say your data is called 'data.json' and is saved with this path Main Bundle > resources > data.json, your code is searching for the file in the main bundle, not the resources folder. I'd recommend you just put the file in the main bundle to make your life simpler.

Try clicking the Target Membership. I waisted at least 2 hours on this unfriendly issue until finally find the solution.