How to set data to a Array with objects in Firestore

我的梦境 提交于 2020-06-27 17:35:29

问题


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)
    }
}

and a model for the words like this:

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)
    }
}

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)

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.

Thanks for the help in advance!


回答1:


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})
      ]
}


来源:https://stackoverflow.com/questions/51951473/how-to-set-data-to-a-array-with-objects-in-firestore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!