如何在循环中调用childByAutoId一次?(Swift)
因为我一次点击就将多个图像上传到firebase,所以我创建了一个循环,直到所有图像都上传完毕。一旦我上传了图像到存储器,我想在实时firebase中保存URL。这就是我所拥有的:如何在循环中调用childByAutoId一次?(Swift),swift,firebase,firebase-realtime-database,imageurl,Swift,Firebase,Firebase Realtime Database,Imageurl,因为我一次点击就将多个图像上传到firebase,所以我创建了一个循环,直到所有图像都上传完毕。一旦我上传了图像到存储器,我想在实时firebase中保存URL。这就是我所拥有的: @IBAction func postFinalButton(_ sender: Any) { ProgressHUD.show() ProgressHUD.animationType = .circleRotateChase ProgressHUD.colorAnim
@IBAction func postFinalButton(_ sender: Any) {
ProgressHUD.show()
ProgressHUD.animationType = .circleRotateChase
ProgressHUD.colorAnimation = #colorLiteral(red: 0.337254902, green: 0.6156862745, blue: 0.9803921569, alpha: 1)
ProgressHUD.colorHUD = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0)
startUploading(completion: {
print("Done!!!")
ProgressHUD.showSucceed()
})
}
func sendDataToDatabase(photoUrl: String, ref: DatabaseReference, index: Int) {
print("okbud")
let name = "photoUrl"+String(index)
ref.setValue([name: photoUrl, "caption": "buddy"], withCompletionBlock: {
(error, ref) in
if error != nil {
ProgressHUD.showError(error?.localizedDescription)
return
}
ProgressHUD.showSucceed()
})
}
func startUploading(completion: @escaping FileCompletionBlock) {
if ImagesOnClick.count == 0 {
completion()
return;
}
block = completion
uploadImage(forIndex: 0)
}
func uploadImage(forIndex index:Int) {
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newImagesRef = postsReference.childByAutoId()
if index < ImagesOnClick.count {
/// Perform uploading
let data = ImagesOnClick[index]!.pngData()
let fileName = String(format: "%@.png", String(newImagesRef.key!))
FirFile.shared.upload(data: data!, withName: fileName, block: { (url) in
/// After successfully uploading call this method again by increment the **index = index + 1**
print(url ?? "Couldn't not upload. You can either check the error or just skip this.")
self.sendDataToDatabase(photoUrl: url!, ref: newImagesRef, index: index)
self.uploadImage(forIndex: index + 1)
})
return;
}
if block != nil {
block!()
}
}
class FirFile: NSObject {
/// Singleton instance
static let shared: FirFile = FirFile()
/// Path
let kFirFileStorageRef = Storage.storage().reference(forURL: "gs://loginpage-227bd.appspot.com")
/// Current uploading task
var currentUploadTask: StorageUploadTask?
func upload(data: Data,
withName fileName: String,
block: @escaping (_ url: String?) -> Void) {
// Create a reference to the file you want to upload
let fileRef = kFirFileStorageRef.child(fileName)
/// Start uploading
upload(data: data, withName: fileName, atPath: fileRef) { (url) in
block(url)
}
}
func upload(data: Data,
withName fileName: String,
atPath path:StorageReference,
block: @escaping (_ url: String?) -> Void) {
// Upload the file to the path
self.currentUploadTask = path.putData(data, metadata: nil) { (metaData, error) in
guard let metadata = metaData else {
// Uh-oh, an error occurred!
block(nil)
return
}
// Metadata contains file metadata such as size, content-type.
// let size = metadata.size
// You can also access to download URL after upload.
path.downloadURL { (url, error) in
guard let downloadURL = url else {
// Uh-oh, an error occurred!
block(nil)
return
}
block(downloadURL.absoluteString)
}
}
}
func cancel() {
self.currentUploadTask?.cancel()
}
}
}
@iAction func postFinalButton(\uSender:Any){
ProgressHUD.show()
ProgressHUD.animationType=.Circlerotatechbase
ProgressHUD.colorAnimation=#colorLiteral(红色:0.337254902,绿色:0.6156862745,蓝色:0.9803921569,alpha:1)
ProgressHUD.colorHUD=#colorLiteral(红色:1,绿色:1,蓝色:1,alpha:0)
启动加载(完成:{
打印(“完成!!!”)
ProgressHUD.showSucceed()
})
}
func sendDataToDatabase(photoUrl:String,ref:DatabaseReference,index:Int){
印刷品(“okbud”)
let name=“photoUrl”+字符串(索引)
ref.setValue([name:photoUrl,“caption:“buddy”]),withCompletionBlock:{
(错误,参考)在
如果错误!=nil{
ProgressHUD.淋浴错误(错误?.localizedDescription)
回来
}
ProgressHUD.showSucceed()
})
}
func startUploading(完成:@escaping FileCompletionBlock){
如果ImagesOnClick.count==0{
完成()
回来
}
块=完成
上载映像(用于索引:0)
}
func上传图像(forIndex:Int){
设ref=Database.Database().reference()
让postsReference=ref.child(“posts”)
让newImagesRef=postsReference.childByAutoId()
如果索引Void){
//创建对要上载的文件的引用
让fileRef=kFirFileStorageRef.child(文件名)
///开始上传
上传(数据:数据,名称:fileName,路径:fileRef){(url)在
块(url)
}
}
func上传(数据:数据,
withName文件名:String,
atPath路径:StorageReference,
块:@escaping(uurl:String?->Void){
//将文件上载到路径
self.currentUploadTask=path.putData(数据,元数据:nil){(元数据,错误)位于
guard let metadata=metadata else{
//哦,发生了一个错误!
区块(无)
回来
}
//元数据包含文件元数据,如大小、内容类型。
//让size=metadata.size
//您还可以在上传后访问下载URL。
path.downloadURL{(url,错误)位于
guard let downloadURL=url else{
//哦,发生了一个错误!
区块(无)
回来
}
块(下载URL.absoluteString)
}
}
}
func cancel(){
self.currentUploadTask?.cancel()
}
}
}
但是,图像的存储方式如下所示:
当我希望它们像这样存储时:
我该怎么做?我声明了一个变量:
var childByAutoId = String()
然后当viewDidLoad
I将函数childByAutoId()
分配给变量childByAutoId
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newImagesRef = postsReference.childByAutoId()
childByAutoId = newImagesRef.key!
最后:
let ref = Database.database().reference()
let postsReference = ref.child("posts")
let newImagesRef = postsReference.child(childByAutoId)
如果您有任何问题,请发表评论 请不要重复发布同一问题多次。如果您有更多信息要添加,请单击上一个问题下的
edit
链接进行更改。这是一个完全不同的问题,我的第一个问题是询问如何将多个图像上载到存储器,而这是询问如何在一个childbyautoidA下将图像URL保存到Firebase。您可能不想使用问题中提出的任何一种结构。其次,问题中的代码对我们没有太大帮助,因为它与向Firebase写入数据没有直接关系,例如,我们不知道这些函数做什么self.sendDataToDatabase
,self.uploadImage
或FirFile.shared.upload
。更重要或可能最重要的是,您需要从firebase函数获取下载url(存储图像的位置),firebase函数实际将图像存储在firebase存储中。这似乎被省略了。《Firebase入门指南》中的代码适用于您尝试执行的操作。请查看该代码,用更多详细信息更新问题,我们将进行查看。@Jay我刚刚将我的问题编辑为我的所有代码,现在,当我按下post按钮时,所有图像都会以childbyautoid存储到firebase存储中,如图所示。这是答案吗?如果是这样的话,这段代码的目的是什么还不清楚。如果你想添加更多细节,请解释一下目的,并将其添加到你的问题中。@Jay:请看我的答案,我的建议就在这里
self.sendDataToDatabase(photoUrl: url!, ref: newImagesRef, index: index)