Cannot Preview This File, App May Have Crashed -- Occurs When Inputting Specific Line of Code

Cannot preview this file, app may have crashed -- Occurs when inputting specific line of code

You need to set context for the preview in the same way as for application, so here is a solution

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
let context = (UIApplication.shared.delegate as! AppDelegate)
.persistentContainer.viewContext
return ContentView()
.environment(\.managedObjectContext, context)
}
}

How can I solve that cannot preview in this file?

Your views need the @EnvironmentObject even in previews:

struct FirstView_Previews: PreviewProvider {
static var previews: some View {
FirstView()
.environmentObject(ViewModel())
}
}

struct SecondView_Previews: PreviewProvider {
static var previews: some View {
SecondView()
.environmentObject(ViewModel())
}
}

The preview process appears to have crashed using bundle to decode local json file

Your Movie1 structure is wrong. All your var in Movie1 should be String?.
No Double, no Int

Here is the code that works for me:

struct Movie1:Codable {
var MOVIE_ID:String
var NAME:String
var ALIAS:String?
var ACTORS:String?
var COVER:String?
var DIRECTORS:String?
var DOUBAN_SCORE:String? // <-- here
var DOUBAN_VOTES:String? // <-- here
var GENRES:String?
var IMDB_ID:String?
var LANGUAGES:String?
var MINS:String? // <-- here
var OFFICIAL_SITE:String?
var REGIONS:String?
var RELEASE_DATE:String?
var SLUG:String?
var STORYLINE:String?
var TAGS:String?
var YEAR:String?
var ACTOR_IDS:String?
var DIRECTOR_IDS:String?
}

struct ContentView: View {
@State var movieData: [Movie1] = []

var body: some View {
HStack {
Text("hello")
if !movieData.isEmpty {
Text(movieData[0].ACTORS ?? "none")
}
}
.onAppear {
if let datas: [Movie1] = Bundle.main.decode(filename: "movieData1.json") {
movieData = datas
}
}
}
}

// do what @Paulw11 is suggesting, use do/try/catch with [T]?
extension Bundle{
func decode<T:Codable>(filename:String) -> [T]? {
guard let url = Bundle.main.url(forResource: filename, withExtension: nil),
let data = try? Data(contentsOf: url),
let getResponse = try? JSONDecoder().decode([T].self, from: data)
else {
return nil
}
return getResponse
}
}

data in your "movieData1.json" file (note the start "[" and end "]"):

[
{
"MOVIE_ID":"27021694",
"NAME":"耶尔玛",
"ALIAS":"",
"ACTORS":"比莉·派佩/布伦丹·考威尔/约翰·麦克米兰",
"COVER":"",
"DIRECTORS":"西蒙·斯通",
"DOUBAN_SCORE":"8.2",
"DOUBAN_VOTES":"187",
"GENRES":"剧情/戏曲",
"IMDB_ID":"tt6847880",
"LANGUAGES":"英语",
"MINS":"0",
"OFFICIAL_SITE":"http://ntlive.nationaltheatre.org.uk/productions/ntlout22-yerma",
"REGIONS":"英国",
"RELEASE_DATE":"2017/8/31",
"SLUG":"72FZ3FZ3b",
"STORYLINE":"A young woman is driven to the unthinkable by her desperate desire to have a child in Simon Stone’s radical production of Lorca’s achingly powerful masterpiece.",
"TAGS":"NTLive/女性/舞台剧/戏剧/英国/英国国家剧院现场/BilliePiper/NTL",
"YEAR":"2017",
"ACTOR_IDS":"比莉·派佩:1049548|Maureen Beattie:|布伦丹·考威尔:1022987|约翰·麦克米兰:1319678|Charlotte Randle:|Thalissa Teixeira:",
"DIRECTOR_IDS":"西蒙·斯通:1336274"
}
]

EDIT1: adding a new element.

Adding a new var is no problem at all. In your Movie1 struct:

struct Movie1:Codable {
var isFavored:Bool // <---
var MOVIE_ID:String
....
}

and at the same time you need to modify your data to include this new element, like this:

[
{
"isFavored": true,
"MOVIE_ID":"27021694",
...
}
]

If you do not want your data to have a isFavored element, then give it an initial value
in the Movie1 struct, and use CodingKeys to omit this isFavored That will remove the JSON coding and decoding of isFavored:

struct Movie1:Codable {
var MOVIE_ID:String
var NAME:String
var ALIAS:String?
var ACTORS:String?
var COVER:String?
var DIRECTORS:String?
var DOUBAN_SCORE:String?
var DOUBAN_VOTES:String?
var GENRES:String?
var IMDB_ID:String?
var LANGUAGES:String?
var MINS:String?
var OFFICIAL_SITE:String?
var REGIONS:String?
var RELEASE_DATE:String?
var SLUG:String?
var STORYLINE:String?
var TAGS:String?
var YEAR:String?
var ACTOR_IDS:String?
var DIRECTOR_IDS:String?

var isFavored: Bool = false // <--- here

// note the missing isFavored
enum CodingKeys: String, CodingKey {
case MOVIE_ID, NAME,ALIAS,ACTORS,COVER,DIRECTORS,DOUBAN_SCORE
case DOUBAN_VOTES,GENRES,IMDB_ID,LANGUAGES,MINS,OFFICIAL_SITE
case REGIONS,RELEASE_DATE,SLUG,STORYLINE,TAGS,YEAR,ACTOR_IDS,DIRECTOR_IDS
}

}

Xcode 13.2.1 Preview Not Working but Simulator Works

Suddenly It fixed, maybe the last update from apple through a software update called "Command Line Tools for Xcode". Before I have also tried a fresh OSX installation but the issue has not gone at all.

Check Software Update from system preference.


Thanks to the great community.

SwiftUI: I get a preview error in the Canvas when trying to load local JSON Data

OK, These are the Moment where I guess I feel really stupid. Turns out the JSON file was badly Formate, After the Details Lines there shouldn't be a ,

Thanks for Reading and trying to help. I Hope the next Person can See this and sollte it quicker than me

How to resolve SwiftUI failed to update preview issue?

strangely, the issue was gone after I start the tutorial all over from the beginning. SwiftUI Preview works as expect now

SwiftUI Preview crashes with Core Data 'NSInvalidArgumentException'

Since I have tried all other possibilities and nothing has helped, I have created a new project and checked CoreData.

Then I created the main class in the CoreData file and replaced Item with Game in "ContentView".

Also in the PersistenceController I replaced the Item with Game under the var preview : PersistenceController and created all classes with codegen "Manual/None".

Now everything works.

SwiftUI: Automatic preview updating paused, always

The problem with all the given answers is that you need to check or uncheck your script in debug mode if you want to make the preview work.

Here is a convenient alternative using the environment variables.

This is really simple

Embed all the content of your script in an if statement that check if we're using the preview or not. If we're in preview, then don't run the content of your script, otherwise, let's run it. And you don't have to sacrifice your script for release versions only.

Here is the template :

if [ $ENABLE_PREVIEWS == "NO" ]
then
# your code to execute here
else
echo "Skipping the script because of preview mode"
fi

And below a full example that I use to bump my build version number

# xcode-build-bump.sh
# @desc Auto-increment the build number every time the project is run.
# @usage
# 1. Select: your Target in Xcode
# 2. Select: Build Phases Tab
# 3. Select: Add Build Phase -> Add Run Script
# 4. Paste code below in to new "Run Script" section
# 5. Drag the "Run Script" below "Link Binaries With Libraries"
# 6. Insure that your starting build number is set to a whole integer and not a float (e.g. 1, not 1.0)
if [ $ENABLE_PREVIEWS == "NO" ]
then
buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "${PROJECT_DIR}/${INFOPLIST_FILE}")
buildNumber=$(($buildNumber + 1))
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "${PROJECT_DIR}/${INFOPLIST_FILE}"
else
echo "Skipping Bump of version"
echo $ENABLE_PREVIEWS
fi


Related Topics



Leave a reply



Submit