现在,当我点击选择图像操作时,我选择一个图像,一旦图像选择器关闭,它就会直接进入数据库。如何使它成为两个不同的功能,以便一个按钮选择一个图像而另一个按钮上传它?
@IBAction func pickImage(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
{
//after its completed
}
@objc(imagePickerController:didFinishPickingMediaWithInfo:) func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any])
{
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage
{
myImageView.image = image
}
else
{
//error
}
self.dismiss(animated: true, completion: nil)
let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!){
storageRef.putData(uploadData, metadata: nil, completion:
{
(metadata, error) in
if error != nil {
print("error")
return
}
else {
let downloadURL = metadata?.downloadURL()?.absoluteString
self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text,"Article": self.mainText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Download URL": (downloadURL)])
}
}
)
}
答案 0 :(得分:1)
从您当前的代码看,您在UIImagePickerController
按钮操作中添加了pickImage
的委托方法这也是错误的委托方法也应该添加,因为您的其他类实例方法意味着它必须是在pickImage
按钮之外。
@IBAction func pickImage(_ sender: Any) {
let image = UIImagePickerController()
image.delegate = self
image.sourceType = UIImagePickerControllerSourceType.photoLibrary
image.allowsEditing = false
self.present(image, animated: true)
}
//Add didFinishPickingMediaWithInfo here
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
if let image = info[UIImagePickerControllerOriginalImage] as? UIImage {
myImageView.image = image
}
else {
//error
}
self.dismiss(animated: true, completion: nil)
}
现在添加新按钮操作uploadImage
并添加FIRStorage
代码。之后,只需将此操作与上传按钮绑定即可。
@IBAction func uploadImage(_ sender: Any) {
let storageRef = Storage.storage().reference().child("images/\(NSUUID().uuidString)/image.png")
if let uploadData = UIImagePNGRepresentation(self.myImageView.image!){
storageRef.putData(uploadData, metadata: nil, completion: { (metadata, error) in
if error != nil {
print("error")
return
}
else {
let downloadURL = metadata?.downloadURL()?.absoluteString
self.ref?.child("Posts").childByAutoId().setValue(["Title": self.titleText.text,"Article": self.mainText.text, "Author": self.authorText.text, "Date": self.dateText.text, "Download URL": (downloadURL)])
}
})
}
}