Firebase将URL上传到实时数据库

时间:2019-01-12 19:29:35

标签: swift firebase firebase-realtime-database firebase-storage

我正在尝试将图像URL从Firebase存储上传到实时数据库。

这是代码

  @IBOutlet weak var jobTitle: UITextField!
@IBOutlet weak var companyName: UITextField!
@IBOutlet weak var jobLocation: UITextField!
@IBOutlet weak var ImageView1stPoster: UIImageView!
var imageUploaded = Data()
var URLtoRealtime = ""

 func addPost() {
    ref.child("Poster").childByAutoId().setValue(["jobName": jobTitle.text as Any,
                                                 "companyTitle": companyName.text as Any,
                                                 "jobLocation": jobLocation.text as Any,
                                                 "firstPoster": URLtoRealtime as Any,
                                                /*,
         "timeStamp":[".sv":"timestamp"]*/]
        as[String:Any])
}


//  DoneButton to submit everthing :)
@IBAction func DoneButton(_ sender: Any) {
  uploadImageToFirebase(imageData: imageUploaded)
    createAlert(title: "Post has been submitted", message: "Going to home page")
    addPost()

}


func uploadImageToFirebase(imageData: Data) {
    // References and vars
    let StorageRefrenece = Storage.storage().reference()
    let currentUser = Auth.auth().currentUser
    let posterImageRef = StorageRefrenece.child("posters").child(currentUser!.uid).child("posterOne.jpg")

    let uploadMetaData = StorageMetadata()
    uploadMetaData.contentType = "image/jpeg"

    // putData to put data to the server using MetaData to orignize everthing.
    posterImageRef.putData(imageData, metadata: uploadMetaData) { (uploadedImageMeta, error) in
        if error != nil {
            print("Error Took place \(String(describing: error?.localizedDescription))")
            return
        } else {
            print("metaData of uploaded image \(uploadMetaData)")
        }
    }

    posterImageRef.downloadURL { (url, error) in
        if (error != nil) {
            // Handle any errors
            print(error!.localizedDescription)
            print("NOOOPPPEEE")
        } else {
            // Get the download URL for 'images/stars.jpg'
            print("Working Good")
            let UrlString = url!.absoluteString
            print(UrlString)
            self.URLtoRealtime = UrlString
        }

    }


}

我正在尝试使URLString = URLtoRealtime数据,然后 将帖子添加到firebase。 但是发生的是它在执行addPost()函数之前 self.URLtoRealtime = UrlString

我不知道如何使程序执行addpost()函数之前的上一行代码。

1 个答案:

答案 0 :(得分:2)

当触摸完成按钮时,您正在异步将图像上传到Firebase并下载URL。但是,正如您所指出的,到addPost时,该URL尚未下载-您想要一个接一个地下载。

@IBAction func DoneButton(_ sender: Any) {
    uploadImageToFirebase(imageData: imageUploaded) { [weak self] (url, error) in
        if let url = url {
            createAlert(title: "Post has been submitted", message: "Going to home page")
            self?.URLtoRealtime = url.absoluteString
            self?.addPost()
        } else {
            self?.createAlert(title: "Post could not be submitted", message: "Try again")
        }
    }
}

我们可以在上载方法中添加一个完成参数,以便在URL的上载和下载完成后可以addPost

func uploadImageToFirebase(imageData: Data, completion: @escaping (URL?, Error?) -> ()) {

    guard let uid = Auth.auth().currentUser?.uid else { return completion(nil, nil) }

    let posterImageRef = Storage.storage().reference(withChild: "posters/\(uid)/posterOne.jpg")
    let uploadMetaData = StorageMetadata(dictionary: [ "contentType": "image/jpeg" ])

    posterImageRef.putData(imageData, metadata: uploadMetaData) { (metadata, error) in
        if let ref = metadata?.storageReference {
            ref.downloadURL(completion: { (url, error) in
                completion(url, error)
            })
        } else {
            completion(nil, error)
        }
    }
}