快速上传Firebase图片

时间:2018-11-20 14:06:23

标签: ios swift firebase

当我运行代码时,完成处理程序块不起作用。当行工作mediaFolder.child(userId!).putData(data, metadata: nil) { (metadata, error) in图像文件上传到存储中,但代码不在块中运行时。这是我的代码:

if let data = self.profileImage.image?.jpegData(compressionQuality: 0.5)
{
    mediaFolder.child(userId!).putData(data, metadata: nil) { (metadata, error) in
    if error != nil {
      // errror 
    } 
    else {
      //enter code here 
    }
}

1 个答案:

答案 0 :(得分:1)

请参见以下代码,将图像数据上传到存储并获取下载网址

var imgData: NSData = NSData(data: UIImageJPEGRepresentation((self.img_Photo?.image)!, 0.5)!)
self.uploadProfileImageToFirebase(data: imgData)

func uploadProfileImageToFirebase(data:NSData){
    let randomPic = parentVC?.randomString(length: 10)
    let storageRef = Storage.storage().reference().child("Profile_Pics").child("\(userId ?? randomPic).jpg")
    if data != nil {
        storageRef.putData(data as Data, metadata: nil, completion: { (metadata, error) in
            if(error != nil){
                print(error)
                return
            }
            guard let userID = Auth.auth().currentUser?.uid else {
                return
            }
            // Fetch the download URL
            storageRef.downloadURL { url, error in
                if let error = error {
                    // Handle any errors
                    if(error != nil){
                        print(error)
                        return
                    }
                } else {
                    // Get the download URL for 'images/stars.jpg'

                    let urlStr:String = (url?.absoluteString) ?? ""
                    print(urlStr)
                }
            }
        })
    }