上下文类型“无效”不能与字典文字一起使用

时间:2018-11-05 15:54:58

标签: ios swift firebase

在我重新启动我的项目而没有进行任何更改之前出现此错误,以前从未听说过。

func toDictionary() -> [String : Any] {

    let newPostRef = Database.database().reference().child("posts").childByAutoId()
    let newPostKey = newPostRef.key

    // 1. save image
    if let imageData = image.jpegData(compressionQuality: 0.5) {
        let storage = Storage.storage().reference().child("images/\(newPostKey)")

        storage.putData(imageData).observe(.success, handler: { (snapshot) in
            self.downloadURL = snapshot.metadata?.downloadURL()?.absoluteString

        return [ <- The Error appears here!!!
        "text" : text,
        "imageDownloadURL" : downloadURL,
        "numberOfLikes" : numberOfLikes,
        "numberOfDislikes" : numberOfDislikes
    ]
        }
    )}
}

也许以下几行代码有帮助,因为我只读到由于任何错误的String或类似的东西而导致发生此错误的信息...

var text: String = ""
private var image: UIImage!
var downloadURL: String?
var numberOfLikes = 0
var numberOfDislikes = 0
let ref: DatabaseReference!

init(snapshot: DataSnapshot){
    ref = snapshot.ref
    if let value = snapshot.value as? [String : Any] {
        text = value["text"] as! String
        downloadURL = value["imageDownloadURL"] as? String
        numberOfLikes = value["numberOfLikes"] as! Int
        numberOfDislikes = value["numberOfDislikes"] as! Int
    }
}

1 个答案:

答案 0 :(得分:0)

问题在于Firebase函数observe是异步的,因此您不能使用同步return语句从中返回值。您需要声明您的函数以使用完成处理程序。

func toDictionary(completion: @escaping ([String:Any])->()) {

    let newPostRef = Database.database().reference().child("posts").childByAutoId()
    let newPostKey = newPostRef.key

    // 1. save image
    if let imageData = image.jpegData(compressionQuality: 0.5) {
        let storage = Storage.storage().reference().child("images/\(newPostKey)")

        storage.putData(imageData).observe(.success, handler: { (snapshot) in
            self.downloadURL = snapshot.metadata?.downloadURL()?.absoluteString
            let snapShotDict = ["text" : text, "imageDownloadURL" : downloadURL, "numberOfLikes" : numberOfLikes, "numberOfDislikes" : numberOfDislikes ]
            completion(snapShotDict)
        }
    )}
}

然后像这样访问它:

toDictionary(completion: { dict in
    // You can only use `dict` inside the completion handler closure
    print(dict)
})