Ios 快速从firebase存储上传个人图像
我的代码为每个人提供一个资产图像作为图片,我如何更改它以使其从firebase检索每个人的图像Ios 快速从firebase存储上传个人图像,ios,swift,firebase,firebase-realtime-database,firebase-storage,Ios,Swift,Firebase,Firebase Realtime Database,Firebase Storage,我的代码为每个人提供一个资产图像作为图片,我如何更改它以使其从firebase检索每个人的图像 import UIKit import Firebase class usersScreenVC: UITableViewController { let cellId = "cellId" var users = [User]() override func viewDidLoad() { super.viewDidLoad() n
import UIKit
import Firebase
class usersScreenVC: UITableViewController {
let cellId = "cellId"
var users = [User]()
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(handleCancel))
tableView.register(UserCell.self, forCellReuseIdentifier: cellId)
fetchUser()
}
func fetchUser() {
FIRDatabase.database().reference().child("Users").observe(.childAdded, with: { (snapshot) in
if let dictionary = snapshot.value as? [String: AnyObject] {
let user = User()
self.users.append(user)
user.DisplayName = dictionary["Display Name"] as? String
user.SubtitleStatus = dictionary["SubtitleStatus"] as? String
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}, withCancel: nil)
}
//
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
//
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// let cell = UITableViewCell(style: .subtitle, reuseIdentifier: cellId)
//
let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
let user = users[indexPath.row]
cell.textLabel?.text = user.DisplayName
cell.detailTextLabel?.text = user.SubtitleStatus
cell.imageView?.image = UIImage(named: "Home Button")
if let profileImageURL = user.profileImageURL{
let url = URL(string: profileImageURL)
URLSession.shared.dataTask(with: url!, completionHandler: { (data, response, error) in
//this mean download hit an error so lets return out.
if error != nil {
//print(error)
return
}
DispatchQueue.main.async(execute: {
cell.imageView?.image = UIImage(data: data!)
})
}).resume()
}
return cell
}
class UserCell: UITableViewCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
}//class
**您需要先将资产映像发送到firebase** 在发送图像的位置调用此函数
func uploadImageToFB (image : UIImage){
let imageData = UIImageJPEGRepresentation(image, 1.0)
let metadata = StorageMetadata()
metadata.contentType = "image/jpeg"
let imagePath = Auth.auth().currentUser!.uid + "/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
//StorageRef is FIRDatabaseRefrence here you need to pass your storage url given in Firebase Console //
storageRef.child(imagePath).putData(imageData!, metadata: metadata, completion: { (metadata, error) in
if let error = error {
print("Error uploading photo: \(error)")
return
}else{
let autoID = self.ref.childByAutoId().key
print(metadata ?? "")
let userID : String = Auth.auth().currentUser!.uid
let ImageRef : DatabaseReference = self.statusRef.child(userID)
let imageUrls = [
"imageUrl" : metadata?.downloadURL()?.absoluteString
] as [String : Any]
let userInfo = ["UserID":userID,
"userName":Auth.auth().currentUser!.displayName]
//Here Image Ref is FIRDatabaseRefrence upto the node you need to set your image
ImageRef.child("UserInfo").updateChildValues(userInfo)
ImageRef.child("Images").child(autoID).setValue(imageUrls)
}
})
}
现在,当从firebase获取时,您将获得您的imageurl并使用它
希望它对你有用我失踪了
user.profileImageURL=字典[“profileImageURL”]as?String我的firebase充满了用户和图像,图像url是String,我不确定是否存在;如果模拟器加载的所有图片都是cell.imageView?.image=UIImage(名为“Home Button”)图像,而不是在上一个VC上使用图像选择器拾取的图像,则没有错误,我认为可能需要等待加载,但我等待了5分钟User.profileImageURL=dictionary[“profileImageURL”]as?Stringthink我想我错过了^如果您将观察者设置为child changed,则可能会发生这种情况,您需要将时间与图像一起存储,并且在获取时需要根据时间对数组进行排序。
let imageData = UIImageJPEGRepresentation(image , 0.0)
let storage = Storage.storage()
let uploadRef = storage.reference().child("images/\(UUID().uuidString).jpg")
uploadRef.putData(imageData!, metadata: nil) { metadata,
error in
if error == nil {
print("successfully uploaded Image")
url = (metadata?.downloadURL()?.absoluteString)!
print("AhmedRabie \(url)")
self.activityIndecator.stopAnimating()
}
else {
print("UploadError \(String(describing: error))")
}
}