如何从Firebase下载URL?没有收到错误但也没有下载?

时间:2018-12-26 16:23:57

标签: swift firebase imagedownload

当使用图像选择器抓取所选图像并将其放置在Firebase存储中时,我希望能够下载URL并代替应用程序内的个人资料图像。不幸的是,当进程到达脚本中的URLSession时,什么也没有发生。没有错误显示,也没有dispatchQueue。该应用程序不会崩溃,而只是跳过所有内容。对代码修复有任何想法或建议吗?

  if let profileImageUploadedData = self.profileImage.image, let uploadData = profileImage.image?.jpegData(compressionQuality: 0.1)
            {

                storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
                    if error != nil
                    {
                        print("Downdloading putData Error: \(error!.localizedDescription)")
                        return
                    }
                    storageRef.downloadURL(completion: { (url, error) in
                        if error != nil
                        {
                            print("DownloadURL ERROR \(error!.localizedDescription)")
                            return
                        }

                        if let profileImageUrl = url?.absoluteString
                        {
                            print("Profile image uploading...")
                            let values = ["profileImageUrl": profileImageUrl]

                            let url = URL(fileURLWithPath: profileImageUrl)
                            URLSession.shared.dataTask(with: url) { (data, response, error) in // ERROR OCCURING NEED TO FIX
                                if error != nil
                                {
                                    print("* URL SESSIONS ERROR: \(error!)")
                                    return
                                }
                                DispatchQueue.main.async
                                {
                                    print("Trying to register profile")
                                    self.registerUserIntoDatabaseWithUID(uid: uid, values: values as [String : AnyObject])
                                    self.profileImage.image = UIImage(data: data!)
                                    print("Dispatch: \(data!)")
                                }

                                print("Profile image successfull uploaded to storage")
                            }
                        }
                    })

                }).resume()
                print("** Profile Image Data Uploaded:\(profileImageUploadedData)")
            }
}

func registerUserIntoDatabaseWithUID(uid: String, values: [String: AnyObject])
{
    print("Registering to database")
    let dataReference = Database.database().reference(fromURL: "URL String")
    let usersReference = dataReference.child("users").child(uid)
    usersReference.updateChildValues(values, withCompletionBlock: { (err, reference) in
        if err != nil
        {
            print(err!)
            return

        }
//            self.profileImage.image = values["profileImageUrl"] as? UIImage
//            self.fetchProfileImage()
        self.dismiss(animated: true, completion: nil)
            print("Saved user sussccessfully in database")

        })

    }
}

1 个答案:

答案 0 :(得分:0)

这是一个很大的问题,实际上是在询问许多不同的答案,所以让我们只关注一个;

  

如何验证用户身份,获取存储在Firebase数据库中的网址   引用存储在Firebase Storage中的图像,然后下载该图像   图片。

我们在这里

首先-验证用户

Auth.auth().signIn(withEmail: user, password: pw, completion: { (auth, error) in
    if let x = error {
       //handle an auth error
    } else {
        if let user = auth?.user {
            let uid = user.uid
            self.loadUrlFromFirebaseDatabase(withUid: uid)
        }
    }
})

现在用户已通过身份验证,请从Firebase数据库获取图像位置网址

func loadUrlFromFirebaseDatabase(withUid: String) {
    let thisUserRef = self.ref.child("users").child(withUid)
    let urlRef = thisUserRef.child("url")
    urlRef.observeSingleEvent(of: .value, with: { snapshot in
        if let url = snapshot.value as? String {
            self.loadImageUsingUrl(url: url)
        } else {
            print("no image for user")
        }
    })
}

现在我们已经在Firebase Storage中找到了图像的位置,获取它

func loadImageUsingUrl(url: String) {
    let storage = Storage.storage()
    let imageRef = storage.reference(forURL: url)
    imageRef.getData(maxSize: 1 * 1024 * 1024) { data, error in
        if let error = error {
            print("error downloading \(error)")
        } else {
            if let image = UIImage(data: data!) {
                //do something with the image
            } else {
                print("no image")
            }
        }
    }
}