Generating a download link using firebase

跟風遠走 提交于 2019-12-12 04:57:30

问题


I'm creating an application that lets the user upload an image and then display a direct link in a text field.

Here is the code that is responsible for uploading the image to my bucket and it is triggered when the user's press the upload button.

    @IBAction func upload(_ sender: Any) {

    let imageContained = viewimage.image

    let storage = Storage.storage()
    var storageRef = storage.reference()
    storageRef = storage.reference(forURL: "bucket link")

    var data = NSData()
    data = UIImageJPEGRepresentation(imageContained!, 0.8)! as NSData
    let dateFormat = DateFormatter()
    dateFormat.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let imageName = dateFormat.string(from: NSDate() as Date)
    let imagePath = "images/\(imageName).jpg"

    let mountainsRef = storageRef.child(imagePath)

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

    mountainsRef.putData(data as Data, metadata: metadata)

How would I generate a direct link for the user?


回答1:


Use this below function

 func uploadProfilePic(){
        var data = NSData()
        data = UIImageJPEGRepresentation(ivProfile.image!, 0.8)! as NSData
        // set upload path
        let filePath = "\(userid)" // path where you wanted to store img in storage
        let metaData = FIRStorageMetadata()
        metaData.contentType = "image/jpg"

        self.storageRef = FIRStorage.storage().reference()
        self.storageRef.child(filePath).put(data as Data, metadata: metaData){(metaData,error) in
            if let error = error {
                print(error.localizedDescription)
                return
            }else{
                //store downloadURL
                let downloadURL = metaData!.downloadURL()!.absoluteString

            }
        }

    }



回答2:


Upload function with completion handler.

func uploadMedia(completion: @escaping (_ url: String?) -> Void) { 
    let storageRef = FIRStorage.storage().reference().child("myImage.png")
    if let uploadData = UIImagePNGRepresentation(self.myImageView.image!) {
        storageRef.put(uploadData, metadata: nil) { (metadata, error) in
            if error != nil {
                print("error")
                completion(nil)
            } else {
                completion((metadata?.downloadURL()?.absoluteString)!)) 
                // your uploaded photo url.
            }
       }
 }

Hope it helps



来源:https://stackoverflow.com/questions/44234622/generating-a-download-link-using-firebase

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!