如何在Firestore中使用对象将数据设置为数组 [英] How to set data to a Array with objects in Firestore

查看:81
本文介绍了如何在Firestore中使用对象将数据设置为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要做的是将所有数据设置为Firestore中的数组,如下所示:
Firestore

What I want to do is to set all data to my array in Firestore, it would look something like this: Firestore

但是我所做的事情给了我这个错误:

But what I have done gives me this error:

*** Terminating app due to uncaught exception 'FIRInvalidArgumentException', reason: 'Unsupported type: _SwiftValue'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010b8d71e6 __exceptionPreprocess + 294
    1   libobjc.A.dylib                     0x000000010af6c031 objc_exception_throw + 48
    2   test collectionview                 0x00000001092e7dda -[FSTUserDataConverter parseScalarValue:context:] + 2169
    3   test collectionview                 0x00000001092e729c -[FSTUserDataConverter parseData:context:] + 792
    4   test collectionview                 0x00000001092e735b __42-[FSTUserDataConverter parseData:context:]_block_invoke + 94
    5   CoreFoundation                      0x000000010b87ac50 __NSArrayEnumerate + 592
    6   test collectionview                 0x00000001092e7122 -[FSTUserDataConverter parseData:context:] + 414
    7   test collectionview                 0x00000001092e65e3 __46-[FSTUserDataConverter parsedSetData:options:]_block_invoke + 346
    8   libswiftCore.dylib                  0x000000010e8a0af1 _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtFTf4dgn_n + 289
    9   libswiftCore.dylib                  0x000000010e703b11 _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtF + 17
    10  libswiftCore.dylib                  0x000000010e7040cb _T0s26_SwiftDeferredNSDictionaryC23enumerateKeysAndObjectsySi7options_ys9UnmanagedVyyXlG_AGSpys5UInt8VGtXB5usingtFTo + 43
    11  test collectionview                 0x00000001092e6303 -[FSTUserDataConverter parsedSetData:options:] + 467
    12  test collectionview                 0x00000001092dc0aa -[FIRDocumentReference setData:options:completion:] + 147
    13  test collectionview                 0x00000001092dbf1a -[FIRDocumentReference setData:] + 92
    14  test collectionview                 0x00000001091e8f85 _T019test_collectionview25NewExerciseViewControllerC08doneWithD6ActionySo15UIBarButtonItemCF + 7845
    15  test collectionview                 0x00000001091e91cc _T019test_collectionview25NewExerciseViewControllerC08doneWithD6ActionySo15UIBarButtonItemCFTo + 60
    16  UIKit                               0x000000010c46a3e8 -[UIApplication sendAction:to:from:forEvent:] + 83
    17  UIKit                               0x000000010ce6f209 __45-[_UIButtonBarTargetAction _invoke:forEvent:]_block_invoke + 154
    18  UIKit                               0x000000010ce6f142 -[_UIButtonBarTargetAction _invoke:forEvent:] + 154
    19  UIKit                               0x000000010c46a3e8 -[UIApplication sendAction:to:from:forEvent:] + 83
    20  UIKit                               0x000000010c5e57a4 -[UIControl sendAction:to:forEvent:] + 67
    21  UIKit                               0x000000010c5e5ac1 -[UIControl _sendActionsForEvents:withEvent:] + 450
    22  UIKit                               0x000000010c5e4a09 -[UIControl touchesEnded:withEvent:] + 580
    23  UIKit                               0x000000010c4df0bf -[UIWindow _sendTouchesForEvent:] + 2729
    24  UIKit                               0x000000010c4e07c1 -[UIWindow sendEvent:] + 4086
    25  UIKit                               0x000000010c484310 -[UIApplication sendEvent:] + 352
    26  UIKit                               0x000000010cdc56af __dispatchPreprocessedEventFromEventQueue + 2796
    27  UIKit                               0x000000010cdc82c4 __handleEventQueueInternal + 5949
    28  CoreFoundation                      0x000000010b879bb1 __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE0_PERFORM_FUNCTION__ + 17
    29  CoreFoundation                      0x000000010b85e4af __CFRunLoopDoSources0 + 271
    30  CoreFoundation                      0x000000010b85da6f __CFRunLoopRun + 1263
    31  CoreFoundation                      0x000000010b85d30b CFRunLoopRunSpecific + 635
    32  GraphicsServices                    0x000000011147aa73 GSEventRunModal + 62
    33  UIKit                               0x000000010c469057 UIApplicationMain + 159
    34  test collectionview                 0x00000001091f19a7 main + 55
    35  libdyld.dylib                       0x000000010f1c6955 start + 1
    36  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

我已经为自己的运动模型做了建模。像这样:

I have made a model for my "exercise" like this:

import Foundation
import Firestore

protocol  DocumentSerializable {
    init?(dictionary:[String:Any])
}


struct Exercise {
    var title: String
    var language: String
    var translated: String
    var uid: String
    var userId: String
    var dueDate: Int
    var lastOpen: Int
    var words: Array<Any>
    
    var dictionary:[String:Any] {
        return [
            "title":title,
            "language":language,
            "translated":translated,
            "uid":uid,
            "userId":userId,
            "dueDate":dueDate,
            "lastOpen":lastOpen,
            "words":words
        ]
    }
}

extension Exercise : DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard let title = dictionary["title"] as? String,
            let language = dictionary["language"] as? String,
            let translated = dictionary["translated"] as? String,
            let uid = dictionary["uid"] as? String,
            let userId = dictionary["userId"] as? String,
            let dueDate = dictionary["dueDate"] as? Int,
            let lastOpen = dictionary["lastOpen"] as? Int,
            let words = dictionary["words"] as? Array<Any>
        
            else {return nil}
        
        self.init(title: title, language: language, translated: translated, uid: uid, userId: userId, dueDate: dueDate, lastOpen: lastOpen, words: words)
    }
}

以及类似单词的模型:

import Foundation
import Firestore

protocol  DocumentSerializable2 {
    init?(dictionary:[String:Any])
}

struct Word {
    var translation: String
    var word: String
   
    var dictionary:[String:Any] {
        return [
            "translation":translation,
            "word":word
            
        ]
    }
}

extension Word : DocumentSerializable {
    init?(dictionary: [String : Any]) {
        guard let translation = dictionary["translation"] as? String,
            let word = dictionary["word"] as? String
            
            else {return nil}
        
        self.init(translation: translation, word: word)
    }
}

我已经尝试使用此代码来设置数据,并且它对所有数据都可以正常工作,除了单词part:

I have tried this code to set the data and it does work fine for all the data except for the words part:

let newExercise = Exercise(title: exerciseTitleTxt.text!, language: language1Txt.title(for: .normal)!, translated: language2Txt.title(for: .normal)!, uid: "test", userId: uid!, dueDate: dueDateMiliseconds, lastOpen: Date().millisecondsSince1970, words: wordsArray)

       db.collection("exercises").document("test2").setData(newExercise.dictionary)

要将单词放入 wordsArray中,我是不是在这样做:

To get the words into the "wordsArray" am I doing like this:

let word = Word(translation: translationTxt.text!, word: wordTxt.text!)
wordsArray.append(word)

所以我自己的猜测是,我需要更改在练习中保存单词的方式模型,但我无法确定如何做到这一点。

So my own guess is that I need to change the way I am saving the words in the Exercise model but I can not wrap my head around how exactly I would do that.

感谢您的提前帮助!

推荐答案

这是因为您的 words 参数是Word对象的数组- Array< Word> [Word] 。 Firebase不知道如何序列化它。您需要做的就是将单词数组转换为词典数组。

This is because your words parameter is an array of Word objects - Array<Word> or [Word]. Firebase doesn't know how to serialise it. What you need to do is convert your array of Words to an array of dictionaries.

var dictionary:[String:Any] {
      return [
          ...
          "words" : words.map({$0.dictionary})
      ]
}

这篇关于如何在Firestore中使用对象将数据设置为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆