Xcode将图像保存到存储中,但不将URL存储到Firebase数据库中

时间:2019-06-10 00:30:54

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

我有一个控制器,允许用户发布数据并将其保存到firebase中。当我单击发布并检查Firebase时,除图像(已正确存储在存储器中)之外,我的所有数据均已保存。

我的代码设置为

//该结构在扩展文件中,而不是直接在初始视图控制器内部。

struct Poster: ProducesCardViewModel{
var jobName : String?
var price: Int?
var postName: String?
var imageUrl1: String?
var imageUrl2: String?
var imageUrl3: String?
var uid: String?

init(dictionary: [String: Any]) {
    self.price = dictionary["cost"] as? Int
    self.jobName = dictionary["category"] as? String
    self.postName = dictionary["description"] as? String
    self.imageUrl1 = dictionary["imageUrl1"] as? String
    self.imageUrl2 = dictionary["imageUrl2"] as? String
    self.imageUrl3 = dictionary["imageUrl3"] as? String 
    self.uid = dictionary["fromId"] as? String ?? ""
}

//这是视图控制器开始的地方。

    lazy var image1Button = createButton(selector: #selector(handleSelectPhoto))
    lazy var image2Button = createButton(selector: #selector(handleSelectPhoto))
    lazy var image3Button = createButton(selector: #selector(handleSelectPhoto))

    @objc func handleSelectPhoto(button: UIButton) {
    print("Select photo with button:", button)
    let imagePicker = CustomImagePickerController()
    imagePicker.delegate = self
    imagePicker.imageButton = button
    present(imagePicker, animated: true)
}

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
    let selectedImage = info[.originalImage] as? UIImage
    let imageButton = (picker as? CustomImagePickerController)?.imageButton
    imageButton?.setImage(selectedImage?.withRenderingMode(.alwaysOriginal), for: .normal)
    dismiss(animated: true)

    let filename = UUID().uuidString
    let ref = Storage.storage().reference(withPath: "/JobPostImages/\(filename)")
    guard let uploadData = selectedImage?.jpegData(compressionQuality: 0.75) else { return }

    let hud = JGProgressHUD(style: .dark)
    hud.textLabel.text = "Uploading image..."
    hud.show(in: view)
    ref.putData(uploadData, metadata: nil) { (nil, err) in
        if let err = err {
            hud.dismiss()
            print("Failed to upload image to storage:", err)
            return
        }

        print("Finished uploading image")
        ref.downloadURL(completion: { (url, err) in

            hud.dismiss()

            if let err = err {
                print("Failed to retrieve download URL:", err)
                return
            }

            print("Finished getting download url:", url?.absoluteString ?? "")

///我想下面的代码片段将使我能够访问存储在存储器中的Image URL。

            if imageButton == self.image1Button {
                self.poster?.imageUrl1 = url?.absoluteString
            } else if imageButton == self.image2Button {
                self.poster?.imageUrl2 = url?.absoluteString
            } else {
                self.poster?.imageUrl3 = url?.absoluteString
            }
        })
    }
}


var poster: Poster?

    @objc func handlePost() {
    let timestamp = Int(Date().timeIntervalSince1970)
    guard let image = poster?.imageUrl1 ?? "", let image2 = image2Button.currentImage, let image3 = image3Button.currentImage, let category = JobCategory.text, let description = JobBio.text, let cost = price.text else {
        print("Error")
        return
    }

    guard let uid = Auth.auth().currentUser?.uid else { return }
    self.mapView?.isMyLocationEnabled = true
    let cords = ["Latitude": self.locationManager.location!.coordinate.latitude, "Longitude": self.locationManager.location!.coordinate.longitude]
    let docData: [String: Any] = [
        "cords" : cords,
        "uid": uid,
        "category": category,

//,然后在获得图像URL后,我假设可以在调用以下代码后将其存储。

        "imageUrl1": poster?.imageUrl1 ?? "",
        "imageUrl2": poster?.imageUrl2 ?? "",
        "imageUrl3": poster?.imageUrl3 ?? "",
        "price": cost,
        "description": description,
        "timeStamp": timestamp
    ]

    let hud = JGProgressHUD(style: .dark)
    hud.textLabel.text = "Posting Job"
    hud.show(in: view)
    self.registerUserIntoDatabseWithUID(uid: uid, values: docData as [String : AnyObject])

        print("Finished saving user info")
        self.dismiss(animated: true, completion: {
            print("Dismissal complete")
        })
    hud.dismiss()
}
    private func postJobDataIntoDatabseWithUID(uid: String, values: [String: AnyObject]) {
    let ref = Database.database().reference(fromURL: "https://something-b1651f.firebaseio.com/")
    let usersReference = ref.child("JobPost").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, ref) in
        if err != nil {
            print("err")
            return
        }

        self.dismiss(animated: true, completion: nil)
    })

}

我已经设置了按钮,图像被存储到了Firebase存储中,只是没有存储到数据库本身。我缺少重要的东西吗?我只是不明白,为什么除了将图像存储在存储器中之外,其他所有内容都保存到数据库中。我的数据库读取

    category = "Electronic Help";
description = "Please ";
imageUrl1 = "";
imageUrl2 = "";
imageUrl3 = "";
location =     {
    Latitude = "40.01357523243176";
    Longitude = "-83.00691353726671";
};
price = 2;
timeStamp = 1559701053;
uid = hwCRvdWrRdfOjHg3uv0nokc5YRv2;
}

0 个答案:

没有答案