我试图从firebase加载数据。我成功加载了诸如usename和email之类的数据,但不知怎的,它无法加载图像。我附加了我用来从firebase加载数据的代码。请帮忙。谢谢。
代码:
import UIKit
import FirebaseDatabase
import Firebase
class ProfileVC: UIViewController {
@IBOutlet weak var currentphoto: UIImageView!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var BioOrEmailLabel: UILabel!
var databasereff : DatabaseReference!
override func viewDidLoad() {
super.viewDidLoad()
databasereff = Database.database().reference()
if let userid = Auth.auth().currentUser?.uid
{
databasereff.child("users").child(userid).observeSingleEvent(of: .value, with: { (snapshot) in
let dict = snapshot.value as? [String:Any]
let username = dict?["username"] as? String
let email = dict?["email"] as? String
if let photourl = dict?["profileimageUrl"] as? String
{
let url = URL(string: photourl)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
if error != nil{
print(error?.localizedDescription)
return
}
OperationQueue.main.addOperation {
self.currentphoto.image = UIImage(data: data!)
}
}).resume()
}
self.usernameLabel.text = username
self.BioOrEmailLabel.text = email
})
{
(error) in
print(error.localizedDescription)
}
}
// Do any additional setup after loading the view.
}
}
答案 0 :(得分:0)
您需要创建FIRStorage
引用以从 Firebase数据库中检索文件。
首先:
import FirebaseStorage
第二个采用存储参考:
var storage: FIRStorage!
然后初始化
storage = FIRStorage.storage()
现在:
let dbRef = database.reference().child("myFiles")
dbRef.observeEventType(.ChildAdded, withBlock: { (snapshot) in
// Get download URL from snapshot
let downloadURL = snapshot.value() as! String
// Create a storage reference from the URL
let storageRef = storage.referenceFromURL(downloadURL)
// Download the data, assuming a max size of 1MB (you can change this as necessary)
storageRef.dataWithMaxSize(1 * 1024 * 1024) { (data, error) -> Void in
// Create a UIImage, add it to the array
let pic = UIImage(data: data)
picArray.append(pic)
})
})
在你的情况下,路径是不同的,所以只需改变路径和干杯!
参考:from here