0

I want to download data from Firebase Database and save it into CoreData. Because this takes a few seconds I wanted to present a Lottie animation during the downloading and saving process. The animation works, but during this process the app doesn't play the animation. Does anyone know how to solve this?

How I set up the Lottie Animation

let lottieView: AnimationView = {
    let lottieView = AnimationView()
    lottieView.animation = Animation.named("animation")
    lottieView.loopMode = .loop
    lottieView.translatesAutoresizingMaskIntoConstraints = false
    return lottieView
}()

When it should be played

var entityName = "Words"
var level = "Beginner"

Database.database().reference().child("Words").child(level).observe(.childAdded) { (snapshot) in
    self.lottieView.play()
    if let dict = snapshot.value as? [String: Any] {
        let word = Word(original: "\(dict["original"]!)", translated: "\(dict["translated"]!)", level: "\(dict["level"]!)", phase: "1", lastQuery: dateFormatter.string(from: date), learned: false)
        allWords.append(word)
        self.saveWord(entity: newEntityName, word: word)
        self.lottieView.stop()
    }
}

How I save the words

func saveWord(entity: String, word: Word) {
    guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
        return
    }

    let context = appDelegate.persistentContainer.viewContext

    let entityName = entity

    guard let newEntity = NSEntityDescription.entity(forEntityName: entityName, in: context) else {
        return
    }

    let newWord = NSManagedObject(entity: newEntity, insertInto: context)

    let original = word.original
    let translated = word.translated
    let level = word.level
    let phase = "1"
    let lastQuery = word.lastQuery
    let learned = false

    newWord.setValue(original, forKey: "original")
    newWord.setValue(translated, forKey: "translated")
    newWord.setValue(level, forKey: "level")
    newWord.setValue(phase, forKey: "phase")
    newWord.setValue(lastQuery, forKey: "lastQuery")
    newWord.setValue(learned, forKey: "learned")

    do {
        try context.save()
        print("Saved: \(original)")
    } catch {
        print(error)
    }
}
Max
  • 27
  • 5
  • 1
    I don't know anything about Lottie but I see you call play in the closure of your database call which means it starts _after_ the data has been downloaded so you should call play before you make the database call – Joakim Danielson Dec 20 '19 at 15:48
  • Also make sure you doing your `UI` work on `main` Thread. – vpoltave Dec 20 '19 at 15:49
  • I tried both, but it changed nothing. It is like the app puts the downloading and saving process into the foreground and has then not enough power to also play the animation. – Max Dec 21 '19 at 05:47

0 Answers0