我正在制作一个社交媒体应用程序,并且使用firebase添加数据库。我遵循了一个教程,它在数据库中并没有用户,在存储中也没有照片个人资料。我认为我没有在注册控制器databasephoto中引入数据库 storagephoto我也可以发布主视图控制器代码
class 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 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)")
}
}
}
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 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)
}
}
//this is in my post viewcontroller
import UIKit
import Firebase
protocol NewPostVCDelegate {
func didUploadPost(withID id:String)
}
class NewPostViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var doneButton: UIBarButtonItem!
@IBOutlet weak var textView: UITextView!
var delegate:NewPostVCDelegate?
@IBAction func handlePostButton(_ sender: Any) {
// https://clout2-39505.firebaseio.com/
guard let user = Auth.auth().currentUser else { return }
print(user)
let postRef = Database.database().reference().child("posts").childByAutoId()
let postObject = [
"author": [
"uid": user.providerID,
"username": user.email,
"photoURL": "path"
],
"text": textView.text,
"timestamp": [".sv":"timestamp"]
] as [String:Any]
postRef.setValue(postObject, withCompletionBlock: {error, ref in
if error == nil{
self.delegate?.didUploadPost(withID: ref.key!)
self.dismiss(animated: true, completion: nil)
} else {
//Handle the error
}
})
}
@IBAction func handleCancelButton(_ sender: Any){
self.dismiss(animated: true, completion: nil)
}
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
textView.resignFirstResponder()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {super.dismiss(animated: flag, completion: completion)
})
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.becomeFirstResponder()
// Remove the nav shadow underline
navigationController?.navigationBar.shadowImage = UIImage()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destination.
// Pass the selected object to the new view controller.
}
*/
}