我正在尝试将Firestore中的图像预加载到模型中
class Post_ {
var postID: String?
var fromUser: DocumentReference?
var toUsers: [DocumentReference] = []
var type: String?
var post: Any? <- To This
var timer: Int?
var createdAt: Timestamp?
}
以便我可以显示而不必等待它加载。
这就是我从Firestore中提取它的方式:
extension Post_ {
static func transform(id: String, dict: [String: Any]) -> Post_ {
return Post_(
postID: id,
fromUser: dict["fromUser"] as! DocumentReference,
toUsers: dict["toUsers"] as! [DocumentReference],
type: dict["type"] as! String,
post: UIImage(data: Functions.getData(url: dict["post"] as! String))!,
timer: dict["timer"] as! Int,
createdAt: dict["createdAt"] as! Timestamp
)
}
}
这就是我要尝试的方法,但它一直崩溃
static func getData(url: String) -> Data {
var post: Data?
URLSession.shared.dataTask(with: URL(string: url)!) { (data, res, error) in
if let e = error {
print(#function + ": " + e.localizedDescription)
} else {
if let d = data {
post = d
}
}
}
if let p = post {
return p
} else {
return Data()
}
}
但这不起作用。一直崩溃,说没错