简体   繁体   中英

Upload image from device to firebase

I've been trying to upload an image to Firebase and then set it to be the profile picture of an user. For some reason the url address of the image is null and I believe it is something related to the metadata in this function:

func uploadProfileImage(_ image:UIImage, completion: @escaping((_url:URL?)->()))
{

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

    let storageRef = Storage.storage().reference().child("user/\(uid)")

    guard let imageData = image.jpegData(compressionQuality: 0.5) else {return}


    let metaData = StorageMetadata()
    metaData.contentType = "image/jpg"

    storageRef.putData(imageData, metadata: metaData) { metaData, error in
        if error == nil, metaData != nil {

            storageRef.downloadURL { url, error in
                completion(url)
                // success!
            }
        }
    }
}

the url returned in complition is nil or error != nil, metaData == nil

Below is the working code to add an image to firebase storage and database for later use using Swift 4

func uploadProfileImage(){

    let storedImage = storagebaseRef.child("yourLocation")

    if let uploadData = UIImageJPEGRepresentation(yourImg, 1) 
    {
        storedImage.putData(uploadData, metadata: nil, completion: { (metadata, error) in
            if error != nil {

            }
            storedImage.downloadURL(completion: { (url, error) in
                if error != nil {
                }

                if let urlText = url?.absoluteString {                      
                        self.databaseRef.child("yourLocation").updateChildValues(["pic" : urlText], withCompletionBlock: { (error, ref) in
                           if error != nil {                        
                               self.showAlert(message: "Please Try Again", title: "Error")
                               return
                           }
                        })
                }           
            })       
        })
    }  
}

Here's a quick solution to upload an image with a given filename and then grab the URL and store it in this users profile.

It wasn't clear what the use of the metadata was in the question.

This is untested so there maybe a typo.

func setUsersPhotoURL(withImage: UIImage, andFileName: String) {
    guard let imageData = withImage.jpegData(compressionQuality: 0.5) else { return }
    let storageRef = Storage.storage().reference()
    let thisUserPhotoStorageRef = storageRef.child("this users uid").child(andFileName)

    let uploadTask = thisUserPhotoStorageRef.putData(imageData, metadata: nil) { (metadata, error) in
        guard let metadata = metadata else {
            print("error while uploading")
            return
        }

        thisUserPhotoStorageRef.downloadURL { (url, error) in
            print(metadata.size) // Metadata contains file metadata such as size, content-type.
            thisUserPhotoStorageRef.downloadURL { (url, error) in
                guard let downloadURL = url else {
                    print("an error occured after uploading and then getting the URL")
                    return
                }

                let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
                changeRequest?.photoURL = downloadURL
                changeRequest?.commitChanges { (error) in
                    //handle error
                }
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM