【问题标题】:Swift and Firebase: Value of type User has no member asDict()Swift 和 Firebase:用户类型的值没有成员 asDict()
【发布时间】:2021-04-30 14:55:30
【问题描述】:

我是 Swift 和 Firebase 的新手。我正在尝试编写将用户结构转换为字典形式的代码,并将其保存到 Firebase 数据库。我想尝试使用 JSONEncoder 将 UserClass 转换为字典形式,尽管我收到错误“User 类型的值没有成员 asDict()”。这是程序的代码。

这是 Firebase 存储服务的模块:

import Foundation
import Firebase
import FirebaseAuth
import FirebaseStorage


class StorageService {
    
    static var storage = Storage.storage()
    
    static var storageRoot = storage.reference(forURL: "link to firebase")
    
    static var storageProfile = storageRoot.child("profile")
    
    static func storageProfileId(userId: String) -> StorageReference{
        return storageProfile.child(userId)
    }
    
    static func saveProfileImage(userId: String, username: String, email: String, imageData: Data, metaData:StorageMetadata, storageProfileImageRef:StorageReference, onSuccess: @escaping(_ user: UserClass) -> Void, onError: @escaping(_ errorMessage:String) -> Void){
        
        storageProfileImageRef.putData(imageData, metadata: metaData){
            (StorageMetadata, error) in
            
            if error != nil{
                onError(error!.localizedDescription)
            }
            
            storageProfileImageRef.downloadURL{
                (url, error) in
                
                if let metaImageUrl = url?.absoluteString {
                    if let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest() {
                        changeRequest.photoURL = url
                        changeRequest.displayName = username
                        changeRequest.commitChanges {
                            (error) in
                            if error != nil {
                                onError(error!.localizedDescription)
                                return
                            }
                        }
                    }
                    let firestoreUserId = AuthService.getUserId(userId: userId)

                    let user = UserClass.init(uid: userId, email: email, profileImageUrl: metaImageUrl, username: username, searchName: username.splitString(), description: "")

                    
                    guard let dict: [String: Any] = try?user.asDict() else {return}
                    
                    firestoreUserId.setData(dict){
                        (error) in
                        if error != nil {
                            onError(error!.localizedDescription)
                            return
                        }
                    }
                    onSuccess(user)
            }
        }
    
        }
    }
}

这是用户结构:

struct UserClass {
    var uid:String
    var email:String
    var profileImageUrl:String
    var username:String
    var searchName:[String]
    var description:String
}

这里是 JSON 编码器的扩展

extension Encodable{
    func asDict() throws -> [String: Any] {
        let data = try JSONEncoder().encode(self)
        guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any]
        else{
           throw NSError()
        }
        return dictionary
    }
}

这可能是一个小错误,我还没有看到。我试图为它找到几天的解决方案,但没有运气。我将感谢各位同行和更有经验的程序员提供的任何帮助。

【问题讨论】:

  • 你的问题不在SwiftUI框架,是Swift。

标签: swift firebase


【解决方案1】:

也许你忘记遵守Encodable

struct UserClass: Encodable {
    var uid:String
    var email:String
    var profileImageUrl:String
    var username:String
    var searchName:[String]
    var description:String
}

【讨论】:

    【解决方案2】:

    请不要在使用 Firestore 时手动映射数据 - 这是一种反模式。这是一个comprehensive article,详细说明了如何

    • 为您的数据建模
    • 以类型安全的方式映射您的数据

    简而言之:

    struct User: Codable, Identifiable {
      var id: String?
      var email: String
      var profileImageUrl: String
      var username: String
      var searchName: [String]
      var description: String
    }
    
    func fetchUser(documentId: String) {
      let docRef = db.collection("users").document(documentId)
      docRef.getDocument { document, error in
        if let error = error as NSError? {
          self.errorMessage = "Error getting document: \(error.localizedDescription)"
        }
        else {
          if let document = document {
            do {
              self.user = try document.data(as: User.self) 
            }
            catch {
              print(error)
            }
          }
        }
      }
    }
    
    func addUser() {
        let collectionRef = db.collection("users")
        do {
          let newDocReference = try collectionRef.addDocument(from: self.user)
          print("User stored with new document reference: \(newDocReference)")
        }
        catch {
          print(error)
        }
      }
    

    【讨论】:

      猜你喜欢
      • 2020-09-09
      • 1970-01-01
      • 2016-09-18
      • 1970-01-01
      • 1970-01-01
      • 2018-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多