У меня проблема при регистрации новых пользователей и попытке загрузить их фотографию - PullRequest
0 голосов
/ 19 февраля 2019

Проблема в том, что когда я регистрирую нового пользователя, он выдает ошибку, что пользователь уже зарегистрирован, даже если я удалю всех своих пользователей в консоли Parse.И самое интересное в том, что приложение все еще регистрирует нового пользователя.Я думаю, что это из-за изображений.Я получаю следующие ошибки на консоли отладки:

2019-02-19 07: 06: 56.920225-0500 Парк ООН [7147: 1581137] [Ошибка]: не удается зарегистрировать пользователя, который уже подписываетвверх.(Код: 202, Версия: 1.17.2)

2019-02-19 07: 06: 57.916999-0500 Парк ООН [7147: 1582281] [Ошибка]: Пользователь не может быть сохранен, если он уже не зарегистрирован,Позвоните сначала.(Код: -1, версия: 1.17.2) Ошибка при попытке загрузить userPicture

2019-02-19 07: 07: 01.019057-0500 UN Park [7147: 1582274] [Ошибка]: пользователь не может бытьсохранены, если они уже не зарегистрированы.Позвоните сначала.(Код: -1, версия: 1.17.2) Ошибка при попытке загрузить carPhoto

import UIKit
import Parse
import ProgressHUD
import SVProgressHUD

class RegisterVC: UIViewController, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate {

    // MARK: - Properties

    let UNALDomain : String = "@unal.edu.co"
    var picker = UIImagePickerController()
    var pickerOne = UIImagePickerController()
    var pickerTwo = UIImagePickerController()

    // MARK: - IB-Outlets

    @IBOutlet weak var fullnameTextField: UITextField!
    @IBOutlet weak var emailTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var phoneTextField: UITextField!
    @IBOutlet weak var IDTextField: UITextField!
    @IBOutlet weak var careerTextField: UITextField!
    @IBOutlet weak var carManufacturerTextField: UITextField!
    @IBOutlet weak var carSeriesTextField: UITextField!
    @IBOutlet weak var carModelTextField: UITextField!
    @IBOutlet weak var carVINTextField: UITextField!
    @IBOutlet weak var carColourTextField: UITextField!
    @IBOutlet weak var carLicensePlate: UITextField!
    @IBOutlet weak var userPhoto: UIImageView!
    @IBOutlet weak var carPhoto: UIImageView!

    // MARK: - Methods: viewDidLoad

    override func viewDidLoad() {
        super.viewDidLoad()
        /// - Tag: Hide Toolbar
        self.navigationController?.isToolbarHidden = true
        /// - Tag: Set Delegates
        setDelegates()
        /// - Tag: Add Keyboard Toolbar
        addInputAccessoryForTextFields(textFields: [fullnameTextField, emailTextField, passwordTextField, phoneTextField, IDTextField, careerTextField, carManufacturerTextField, carSeriesTextField, carModelTextField, carVINTextField, carColourTextField, carLicensePlate], dismissable: true, previousNextable: true)
    }

    // MARK: - Methods: viewDidAppear

    override func viewDidAppear(_ animated: Bool) {
        /// - Tag: Hide Toolbar
        self.navigationController?.isToolbarHidden = true
        /// - Tag: Set Delegates
        setDelegates()
        /// - Tag: Add Keyboard Toolbar
        addInputAccessoryForTextFields(textFields: [fullnameTextField, emailTextField, passwordTextField, phoneTextField, IDTextField, careerTextField, carManufacturerTextField, carSeriesTextField, carModelTextField, carVINTextField, carColourTextField, carLicensePlate], dismissable: true, previousNextable: true)
    }

    // MARK: - Methods: setDelegates

    func setDelegates() {
        fullnameTextField.delegate = self
        emailTextField.delegate = self
        passwordTextField.delegate = self
        phoneTextField.delegate = self
        IDTextField.delegate = self
        careerTextField.delegate = self
        carManufacturerTextField.delegate = self
        carSeriesTextField.delegate = self
        carModelTextField.delegate = self
        carVINTextField.delegate = self
        carColourTextField.delegate = self
        carLicensePlate.delegate = self
    }

    //  MARK: - Methods: hideKeyboard

    /// - Tag: Hide Keyboard if the user touches anywhere outside them.

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        self.view.endEditing(true)
    }

    /// - Tag: Navigate between TextFields and Hide Keyboard after pressing Return on the last one.

    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if let nextField = textField.superview?.viewWithTag(textField.tag + 1) as? UITextField {
            nextField.becomeFirstResponder()
        } else {
            textField.resignFirstResponder()
        }
        return false
    }

    /// - Tag: Toolbar with “Previous” and “Next” for Keyboard inputAccessoryView.

    func addInputAccessoryForTextFields(textFields: [UITextField], dismissable: Bool = true, previousNextable: Bool = false) {
        for (index, textField) in textFields.enumerated() {
            let toolbar: UIToolbar = UIToolbar()
            toolbar.sizeToFit()
            var items = [UIBarButtonItem]()
            if previousNextable {
                /// - Tag: Navigate to the previous TextField after tapping "Anterior".
                let previousButton = UIBarButtonItem(image: UIImage(named: "BackwardArrow"), style: .plain, target: nil, action: nil)
                previousButton.width = 50
                if textField == textFields.first {
                    previousButton.isEnabled = false
                } else {
                    previousButton.target = textFields[index - 1]
                    previousButton.action = #selector(UITextField.becomeFirstResponder)
                }
                /// - Tag: Navigate to the next TextField after tapping "Siguiente".
                let nextButton = UIBarButtonItem(image: UIImage(named: "ForwardArrow"), style: .plain, target: nil, action: nil)
                nextButton.width = 50
                if textField == textFields.last {
                    nextButton.isEnabled = false
                } else {
                    nextButton.target = textFields[index + 1]
                    nextButton.action = #selector(UITextField.becomeFirstResponder)
                }
                items.append(contentsOf: [previousButton, nextButton])
            }
            /// - Tag: Dismiss Keyboard after tapping the "Terminado".
            let spacer = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
            let doneButton = UIBarButtonItem(barButtonSystemItem: .done, target: view, action: #selector(UIView.endEditing))
            items.append(contentsOf: [spacer, doneButton])
            toolbar.setItems(items, animated: false)
            textField.inputAccessoryView = toolbar
        }
    }

    // MARK: - Navigation: registerButtonPressed

    @IBAction func registerButtonPressed(_ sender: UIBarButtonItem) {
        SVProgressHUD.show()
        if (emailTextField.text?.contains(UNALDomain))! {
            let user = PFUser()
            user.username = String(emailTextField.text!)
            user.password = String(emailTextField.text!)
            user.email = String(emailTextField.text!)
            user["fullName"] = String(fullnameTextField.text!)
            user["phone"] = String(phoneTextField.text!)
            user["ID"] = String(IDTextField.text!)
            user["career"] = String(careerTextField.text!)
            user["carManufacturer"] = String(carManufacturerTextField.text!)
            user["carSeries"] = String(carSeriesTextField.text!)
            user["carModel"] = String(carModelTextField.text!)
            user["carVIN"] = String(carVINTextField.text!)
            user["carColour"] = String(carColourTextField.text!)
            user["carLicensePlate"] = String(carLicensePlate.text!)
        /// - Tag: Upload userPhoto Image to Parse
            if let userPhotoImageData = userPhoto.image!.pngData() {
                let userPhotoImageFile = PFFileObject(name: "userPicture.png", data: userPhotoImageData)
                user["userPhoto"] = userPhotoImageFile
                user.saveInBackground { (success, error) in
                    if success {
                        print("userPicture uploaded successfully")
                    } else {
                        print("Error while attempting to upload userPicture")
                    }
                }
            }
        /// - Tag: Upload carPhoto Image to Parse
            if let carPhotoImageData = carPhoto.image!.pngData() {
                let carPhotoImageFile = PFFileObject(name: "carPicture.png", data: carPhotoImageData)
                user["carPhoto"] = carPhotoImageFile
                user.saveInBackground { (success, error) in
                    if success {
                        print("carPhoto uploaded successfully")
                    } else {
                        print("Error while attempting to upload carPhoto")
                    }
                }
            }
            user.signUpInBackground { (sucess, error) in
                if error != nil {
            /// - Tag: Registration Failed
                    SVProgressHUD.dismiss()
                    ProgressHUD.showError("Error: \(String(describing: error))")
                } else {
            /// - Tag: Registration Successful
                    SVProgressHUD.dismiss()
                    self.performSegue(withIdentifier: "signUpButtonPressed", sender: self)
                    ProgressHUD.showSuccess("Bienvenido!")
                }
            }
        } else {
            SVProgressHUD.dismiss()
            ProgressHUD.showError("Error: dirección de correo inválida")
        }
    }

    // MARK: - Methods: imagePickerController

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        if picker == pickerOne  {
            if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                userPhoto.image = image
            }
        } else if picker == pickerTwo {
                if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
                carPhoto.image = image
                }
            }
        self.dismiss(animated: true, completion: nil)
    }

    // MARK: - Navigation: chooseUserPhotoButtonPressed

    @IBAction func chooseUserPhotoButtonPressed(_ sender: UIButton) {
        self.picker = pickerOne
        pickerOne.delegate = self
        pickerOne.sourceType = UIImagePickerController.SourceType.photoLibrary
        pickerOne.allowsEditing = true
        self.present(pickerOne, animated: true, completion: nil)
    }

    // MARK: - Navigation: chooseCarPhotoButtonPressed

    @IBAction func chooseCarPhotoButtonPressed(_ sender: UIButton) {
        self.picker = pickerTwo
        pickerTwo.delegate = self
        pickerTwo.sourceType = UIImagePickerController.SourceType.photoLibrary
        pickerTwo.allowsEditing = true
        self.present(pickerTwo, animated: true, completion: nil)
    }

}

Я ожидаю, что после того, как администратор введет все свои данные и выберет userPicture и carPicture he 'Вы сможете зарегистрироваться, и его данные будут сохранены на сервере Parse, чтобы впоследствии их можно было найти на другом View Controller.

...