这是我的注册视图控制器,我首先将其上传了头像。我的代码正在运行,没有错误,但是在Firebase的存储中没有创建任何类似于“ IMAGES”的文件夹,规则是: storage picture
service firebase.storage {match /b/{bucket}/o {
match /{allPaths=**} {
allow read, write: if request.auth != null;
} }}
import UIKit
导入Firebase 导入FirebaseStorage
SignUpViewController类:UIViewController,UITextFieldDelegate {
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var tapToChangeProfileButton: UIButton!
var imageReference: StorageReference{
return Storage.storage().reference().child("images")
}
var imagePicker:UIImagePickerController!
@IBAction func ContinueButton(_ sender: UIButton) {
if emailTextField.text == "" {
let alertController = UIAlertController(title: "Error",message: "Please enert your emiail and password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
present(alertController, animated: true, completion: nil)
}
else {
Auth.auth().createUser(withEmail: emailTextField.text!, password: passwordTextField.text!) { (user, error) in
if error == nil {
print("You have successfully signed up")
let vc = self.storyboard?.instantiateViewController(withIdentifier: "HomeController")
self.present(vc!, animated: true, completion: nil)
} else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController,animated: true, completion: nil)
}
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
usernameTextField.delegate = self
emailTextField.delegate = self
passwordTextField.delegate = self
let imageTap = UITapGestureRecognizer(target: self, action: #selector(openImagePicker))
profileImageView.isUserInteractionEnabled = true
profileImageView.addGestureRecognizer(imageTap)
profileImageView.layer.cornerRadius = profileImageView.bounds.height / 2
profileImageView.clipsToBounds = true
//tapToChangeProfileButton.addTarget(self, action: #selector(openImagePicker), for: .touchUpInside)
imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.sourceType = .photoLibrary
imagePicker.delegate = self
}
@objc func openImagePicker(_ sender:Any) {
self.present(imagePicker, animated: true, completion: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
usernameTextField.becomeFirstResponder()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
usernameTextField.resignFirstResponder()
emailTextField.resignFirstResponder()
passwordTextField.resignFirstResponder()
NotificationCenter.default.removeObserver(self)
}
@objc func handleSignUp() {
guard let username = usernameTextField.text else { return }
guard let email = emailTextField.text else { return }
guard let pass = passwordTextField.text else { return }
guard let image = profileImageView.image else { return }
Auth.auth().createUser(withEmail: email, password: pass) { user, error in
if error == nil && user != nil {
print("User created!")
self.uploadProfileImage(image) { url in
if url != nil {
let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
changeRequest?.displayName = username
changeRequest?.photoURL = url
changeRequest?.commitChanges { error in
if error == nil {
print("User display name changed!")
self.saveProfile(username: username, profileImageURL: url!) { success in
if success {
self.dismiss(animated: true, completion: nil)
}
}
} else {
print("Error: \(error!.localizedDescription)")
}
}
}else {
//error unable to upload profile image
}
}
} else {
print("Error: \(error!.localizedDescription)")
}
}
}
let filename = "earth.jpg"
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.75) else { return }
let uploadProfileImage = imageReference.child(filename)
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!
}
} else {
// failed
completion(nil)
}
}
}
func saveProfile(username:String, profileImageURL:URL, completion: @escaping ((_ success:Bool)->())) {
guard let uid = Auth.auth().currentUser?.uid else { return }
let databaseRef = Database.database().reference().child("users/profile/\(uid)")
let userObject = [
"username": username,
"photoURL": profileImageURL.absoluteString
] as [String:Any]
databaseRef.setValue(userObject) { error, ref in
completion(error == nil)
}
}}extension SignUpViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
picker.dismiss(animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
if let pickedImage = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
self.profileImageView.image = pickedImage
}
picker.dismiss(animated: true, completion: nil)
}}