简体   繁体   English

将图片从设备上传到Firebase

[英]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. 我一直试图将图像上传到Firebase,然后将其设置为用户的个人资料图片。 For some reason the url address of the image is null and I believe it is something related to the metadata in this function: 出于某种原因,图片的url地址为null,并且我相信它与该函数中的元数据有关:

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 在complition中返回的url为nil或错误!= nil,metaData == nil

Below is the working code to add an image to firebase storage and database for later use using Swift 4 以下是将图像添加到Firebase存储和数据库中以供以后使用Swift 4使用的工作代码

func uploadProfileImage(){ 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. 这是一种快速解决方案,可以上传具有给定文件名的图像,然后获取URL并将其存储在此用户个人资料中。

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
                }
            }
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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