使用Firebase异步observeSingleEvent方法的完成处理程序异步初始化类

时间:2019-09-11 03:11:40

标签: ios swift firebase firebase-realtime-database async-await

我正在通过Firebase DataSnapshot实例化一个User类。调用初始化程序init(snapshot: DataSnapshot)后,我想通过pictureRefnameRef方法从两个不同的数据库引用(即getFirebasePictureURLgetFirebaseNameString中异步检索值。 '@转义完成处理程序(使用Firebase的observeSingleEvent方法)。但是,控制台给了我两个错误:在初始化所有成员之前由闭包捕获的'self'和在初始化所有存储的属性之前在方法调用'getFirebasePictureURL'中使用的'self' >:

import Firebase

class User {

 var uid: String
 var fullname: String
 var pictureURL: URL

//DataSnapshot Initializer

init(snapshot: DataSnapshot) {

self.uid = snapshot.key

getFirebasePictureURL(userId: uid) { (url) in

    self.getFirebaseNameString(userId: self.uid) { (fullName) in

        self.fullname = fullName
        self.profilePictureURL = url

    }
}

func getFirebasePictureURL(userId: String, completion: @escaping (_ url: URL) -> Void) {

    let currentUserId = userId
    //Firebase database picture reference
    let pictureRef = Database.database().reference(withPath: "pictureChildPath")

    pictureRef.observeSingleEvent(of: .value, with: { snapshot in

        //Picture url string
        let pictureString = snapshot.value as! String

        //Completion handler (escaping)
        completion(URL(string: pictureString)!)

    })

}


func getFirebaseNameString(userId: String, completion: @escaping (_ fullName: String) -> Void) {

    let currentUserId = userId
    //Firebase database name reference
    let nameRef = Database.database().reference(withPath: "nameChildPath")

    nameRef.observeSingleEvent(of: .value, with: { snapshot in

        let fullName = snapshot.value as? String

       //Completion handler (escaping)
        completion(fullName!)

        })
     }
  }

我不太确定在这种情况下应该如何异步初始化它。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

只有在使用默认值初始化的所有存储属性或属性应该是可选的,或者在称为{strong>指定初始化器

的函数init中分配的属性值之前,该类才能初始化。
  

指定的初始化器是类的主要初始化器。指定的初始化程序会完全初始化该类引入的所有属性,并调用适当的超类初始化程序以继续超类链中的初始化过程。

阅读此以获取更多信息。 https://docs.swift.org/swift-book/LanguageGuide/Initialization.html

因此,在您的情况下,您尝试通过转义关闭(异步任务)任务来尝试将fullnamepictureURL作为存储属性,但该任务由于不符合规则而被禁止

正如我之前提到的,您有以下选择

  1. 分配一些默认值
  2. 使用可选值(最好的选项,您可以通过稍后检查可选内容来处理错误)

希望这会有所帮助