将映像从firebase存储传输到firebase数据库

时间:2017-03-26 14:21:46

标签: swift xcode firebase

我在每个用户的firebase存储中都有一张个人资料图片。以下是参考资料:

profilePicRef = FIRStorage.storage().reference().child((FIRAuth.auth()?.currentUser.uid)!+"/profile_pic.jpg")

我希望能够从我的存储中访问图片并使用以下路径将其放入我的数据库中:

@IBAction func Post(_ sender: AnyObject) {

   let postObject: Dictionary<String, Any> = [

         "userpic" : ""
    ]

FIRDatabase.database().reference().child("posts").child(self.loggedInUser!.uid).childByAutoId().setValue(postObject)

 }

我不清楚“userpic”

旁边的引号是什么

1 个答案:

答案 0 :(得分:1)

数据库本身不适合存储照片(但是你可以在技术上做base64 encoding of an image,如果图像非常小,这可能会更好。)

我发现最适合个人资料图片的方法是根据UID存储Firebase存储。当我想上传图片时,我先调整它的大小:

// from https://stackoverflow.com/a/29138120/1822214.  Only for square images.
func resizeWith(_ width: CGFloat) -> UIImage? {
    let imageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))))
    imageView.contentMode = .scaleAspectFit
    imageView.image = self
    UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, scale)
    guard let context = UIGraphicsGetCurrentContext() else { return nil }
    imageView.layer.render(in: context)
    guard let result = UIGraphicsGetImageFromCurrentImageContext() else { return nil }
    UIGraphicsEndImageContext()
    return result
}

然后我像上传一样:

    func uploadProfilePic(_ uid: String, image: UIImage?, completion: @escaping (Bool) -> ())
        // compress with moderate quality (between 0 and 1)
        let data: Data = UIImageJPEGRepresentation(image!, 0.5)!
        let profileRef = storageRef.child("users/\(uid)/profile.jpg")

        let metadata = FIRStorageMetadata()
        metadata.contentType = "image/jpg"

        // Upload the file
        let uploadTask = profileRef.put(data, metadata: metadata) { metadata, error in
            if (error != nil) {
                // Uh-oh, an error occurred!
                print("there was an error uploading the profile pic!")
                print(error)
                // completion with failure... :(
                completion(false)
            } else {
                // Metadata contains file metadata such as size, content-type, and download URL.
                let downloadURL = metadata!.downloadURL
                // completion with success!
                completion?(true)
            }
        }
    }

我希望这可以让你开始,如果你有任何问题,请告诉我。