Swift 将映像从firebase存储传输到firebase数据库
我在firebase存储器中为每个用户存储了一张个人资料图片。以下是参考资料:Swift 将映像从firebase存储传输到firebase数据库,swift,xcode,firebase,Swift,Xcode,Firebase,我在firebase存储器中为每个用户存储了一张个人资料图片。以下是参考资料: profilePicRef = FIRStorage.storage().reference().child((FIRAuth.auth()?.currentUser.uid)!+"/profile_pic.jpg") 我希望能够从存储器中访问图片,并使用以下路径将其放入数据库: @IBAction func Post(_ sender: AnyObject) { let postObject: Dicti
profilePicRef = FIRStorage.storage().reference().child((FIRAuth.auth()?.currentUser.uid)!+"/profile_pic.jpg")
我希望能够从存储器中访问图片,并使用以下路径将其放入数据库:
@IBAction func Post(_ sender: AnyObject) {
let postObject: Dictionary<String, Any> = [
"userpic" : ""
]
FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).childByAutoId().setValue(postObject)
}
@IBAction func Post(u发送方:AnyObject){
让postObject:字典=[
“userpic”:”
]
FIRDatabase.database().reference().child(“posts”).child(self.loggedInUser!.uid).childByAutoId().setValue(postObject)
}
我不清楚“userpic”旁边的引号中是什么内容数据库本身并不适合存储照片(但是从技术上来说,你可以做一个简单的选择,如果图像非常小,这可能会更好) 我发现最适合配置文件图像的方法是基于UID将它们存储在Firebase存储中。当我想上传图像时,我会先调整它的大小:
// from https://stackoverflow.com/a/29138120/1822214. Only for square images.
func resizeWith(_ width: CGFloat) -> UIImage? {
let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
imageView.contentMode = .scaleAspectFit
imageView.image = self
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
guard let context = UIGraphicsGetCurrentContext() else { return nil }
imageView.layer.render(in: context)
guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
UIGraphicsEndImageContext()
return result
}
然后我像这样上传它:
func uploadProfilePic(_ uid: String, image: UIImage?, completion: @escaping (Bool) -> ())
// compress with moderate quality (between 0 and 1)
let data: Data = UIImageJPEGRepresentation(image!, 0.5)!
let profileRef = storageRef.child("users/\(uid)/profile.jpg")
let metadata = FIRStorageMetadata()
metadata.contentType = "image/jpg"
// Upload the file
let uploadTask = profileRef.put(data, metadata: metadata) { metadata, error in
if (error != nil) {
// Uh-oh, an error occurred!
print("there was an error uploading the profile pic!")
print(error)
// completion with failure... :(
completion(false)
} else {
// Metadata contains file metadata such as size, content-type, and download URL.
let downloadURL = metadata!.downloadURL
// completion with success!
completion?(true)
}
}
}
我希望这能让你开始,如果你有任何问题,请告诉我