123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611 |
- //
- // UserDetailsViewController.swift
- // Learn Genie
- //
- // Created by Suraj Kumar Mandal on 03/09/21.
- //
- import UIKit
- import Toast_Swift
- import Alamofire
- class UserDetailsViewController: UIViewController {
-
- @IBOutlet var nameLabel: UILabel!
- @IBOutlet var nameTF: UITextField!
- @IBOutlet var emailLabel: UILabel!
- @IBOutlet var emailTF: UITextField!
- @IBOutlet var dobLabel: UILabel!
- @IBOutlet var dobTF: UITextField!
- @IBOutlet var genderLabel: UILabel!
- @IBOutlet var genderTF: UITextField!
- @IBOutlet var mobileLabel: UILabel!
- @IBOutlet var mobileTF: UITextField!
- @IBOutlet var stateLabel: UILabel!
- @IBOutlet var stateTF: UITextField!
- @IBOutlet var districtLabel: UILabel!
- @IBOutlet var districtTF: UITextField!
- @IBOutlet var submitButton: CustomButton!
-
- var viewModel = UserDetailsViewModel()
- let stateData = DBManager.sharedInstance.database.objects(StateModel.self)
- let districtData = DBManager.sharedInstance.database.objects(DistrictModel.self)
- let userData = UserDefaults.standard.dictionary(forKey: Constant.userData)
- let genderData = [String](arrayLiteral: "Male", "Female", "Third Gender", "Will not specify")
- var pageMode = String() //Register / Profile
- fileprivate let customPicker = ToolbarPickerView()
-
- var stateArray = [String]()
- var stateIdArray = [Int]()
- var districtArray = [String]()
-
- var stateId = 1 //default
- var districtId = 1 //default
- var gender = "Will not specify"
- var dateOfBirth = "01/01/2021"
- var mobile = "9999999999"
-
- var activeTextField = 0
-
- override func viewDidLoad() {
- super.viewDidLoad()
-
- // Do any additional setup after loading the view.
- viewModel.delegate = self
- ApiManager.generateCookie()
- print(pageMode)
- }
-
- override func viewWillAppear(_ animated: Bool) {
- setupUI()
- setupUserData()
- }
-
- func setupUI() {
- let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.dismissKeyboard))
- view.addGestureRecognizer(tap)
- }
-
- func setupUserData() {
- //Set text field title name
- nameLabel.text = Helper.translateText(inputText: "Enter Name")
- emailLabel.text = Helper.translateText(inputText: "Email")
- dobLabel.text = Helper.translateText(inputText: "Enter Date of Birth")
- genderLabel.text = Helper.translateText(inputText: "Select Gender")
- mobileLabel.text = Helper.translateText(inputText: "Mobile")
- stateLabel.text = Helper.translateText(inputText: "Select State")
- districtLabel.text = Helper.translateText(inputText: "Select District")
- if pageMode == "Profile" {
- submitButton.setTitle(Helper.translateText(inputText: "UPDATE"), for: .normal)
- } else {
- submitButton.setTitle(Helper.translateText(inputText: "SUBMIT"), for: .normal)
- }
-
- //Set text field data
- if pageMode == "Profile" {
- let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self)
- if let row = userModelDB.firstIndex(where: {$0.email == self.userData?["email"] as? String}) {
- nameTF.text = userModelDB[row].name
- emailTF.text = userModelDB[row].email
- let dateString = userModelDB[row].dateOfBirth
- let requiredFormat = dateString.toDateString(inputDateFormat: "yyyy-MM-dd'T'HH:mm:ssZ", ouputDateFormat: Constant.dateFormat)
- dobTF.text = requiredFormat
- genderTF.text = userModelDB[row].gender
- mobileTF.text = userModelDB[row].mobile
- stateTF.text = getStateName(id: userModelDB[row].stateId)
- self.stateId = userModelDB[row].stateId
- districtTF.text = getDistrictName(id: userModelDB[row].districtId)
- self.districtId = userModelDB[row].districtId
- }
- }
- nameTF.text = userData?["name"] as? String
- emailTF.text = userData?["email"] as? String
- dobTF.datePicker(target: self,
- doneAction: #selector(doneAction),
- cancelAction: #selector(cancelAction),
- datePickerMode: .date)
- createPickerView()
- nameTF.delegate = self
- emailTF.delegate = self
- dobTF.delegate = self
- genderTF.delegate = self
- mobileTF.delegate = self
- stateTF.delegate = self
- districtTF.delegate = self
- districtTF.isUserInteractionEnabled = false
- stateArray.removeAll()
- stateIdArray.removeAll()
- getState()
- }
-
- @objc func dismissKeyboard() {
- self.view.endEditing(true)
- }
-
- func createPickerView() {
- self.genderTF.inputView = self.customPicker
- self.genderTF.inputAccessoryView = self.customPicker.toolbar
-
- self.stateTF.inputView = self.customPicker
- self.stateTF.inputAccessoryView = self.customPicker.toolbar
-
- self.districtTF.inputView = self.customPicker
- self.districtTF.inputAccessoryView = self.customPicker.toolbar
-
- self.customPicker.delegate = self
- self.customPicker.dataSource = self
- self.customPicker.toolbarDelegate = self
- }
-
- @objc
- func cancelAction() {
- self.dobTF.resignFirstResponder()
- }
-
- @objc
- func doneAction() {
- if let datePickerView = self.dobTF.inputView as? UIDatePicker {
- let dateFormatter = DateFormatter()
- dateFormatter.dateFormat = Constant.dateFormat
- let dateString = dateFormatter.string(from: datePickerView.date)
- self.dobTF.text = dateString
- self.dateOfBirth = dateString
-
- print(datePickerView.date)
- print(dateString)
-
- self.dobTF.resignFirstResponder()
- }
- }
-
- func getStateName(id:Int) -> String {
- var stateName = String()
- if let row = stateData.firstIndex(where: {$0.id == id}) {
- stateName = stateData[row].stateName
- }
- return stateName
- }
-
- func getDistrictName(id:Int) -> String {
- var districtName = String()
- if let row = districtData.firstIndex(where: {$0.id == id}) {
- districtName = districtData[row].districtName
- }
- return districtName
- }
-
- func getState() {
- for state in stateData {
- let id = state.id
- let name = state.stateName
- self.stateIdArray.append(id)
- self.stateArray.append(name)
- }
- }
-
- func getDistrict(stateId:Int) {
- for district in districtData {
- if district.stateId == stateId {
- let name = district.districtName
- self.districtArray.append(name)
- }
- }
- }
-
- func getStateId(name: String) -> Int {
- var id = Int()
- for state in stateData {
- if name == state.stateName {
- id = state.id
- }
- }
- return id
- }
-
- func getDistrictId(name: String) -> Int {
- var id = Int()
- for district in districtData {
- if name == district.districtName {
- id = district.id
- }
- }
- return id
- }
-
- func checkValidation() {
- if nameTF.text?.isEmpty == true {
- self.view.makeToast(Helper.translateText(inputText: "Enter a valid name, 3 or more characters long"))
- }
- else if emailTF.text?.isEmpty == true && emailTF.text?.isValidEmail == false {
- self.view.makeToast(Helper.translateText(inputText: "Enter valid email"))
- }
- // else if dobTF.text?.isEmpty == true {
- // self.view.makeToast(Helper.translateText(inputText: "Select your date of birth"))
- // }
- // else if genderTF.text?.isEmpty == true {
- // self.view.makeToast(Helper.translateText(inputText: "Select your gender"))
- // }
- // else if mobileTF.text?.isEmpty == true {
- // self.view.makeToast(Helper.translateText(inputText: "Enter Mobile Number"))
- // }
- // else if mobileTF.text?.count != 10 {
- // self.view.makeToast(Helper.translateText(inputText: "Enter Valid Mobile Number"))
- // }
- // else if stateTF.text?.isEmpty == true {
- // self.view.makeToast(Helper.translateText(inputText: "Select your state"))
- // }
- // else if districtTF.text?.isEmpty == true {
- // self.view.makeToast(Helper.translateText(inputText: "Select your district"))
- // }
- else {
- if pageMode == "Profile" {
- updateStudent()
- } else {
- saveStudent()
- }
- }
- }
-
-
- /*
- // 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.
- }
- */
-
- @IBAction func submitButtonAction(_ sender: Any) {
- if Reachability.isConnectedToNetwork() {
- checkValidation()
- } else {
- Alert.showInternetFailureAlert(on: self)
- }
- }
-
- }
- extension UserDetailsViewController: UIPickerViewDelegate, UIPickerViewDataSource {
- // MARK: UIPickerView Delegation
-
- func numberOfComponents(in pickerView: UIPickerView) -> Int {
- return 1
- }
-
- func pickerView( _ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
- switch activeTextField
- {
- case 1:
- return genderData.count
- case 2:
- return stateArray.count
- case 3:
- return districtArray.count
- default:
- return districtArray.count
-
- }
- }
-
- func pickerView( _ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
- switch activeTextField{
- case 1:
- return genderData[row]
- case 2:
- return stateArray[row]
- case 3:
- return districtArray[row]
- default:
- return districtArray[row]
- }
- }
-
- func pickerView( _ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
-
- switch activeTextField{
- case 1:
- genderTF.text = genderData[row]
- break
-
- case 2:
- stateTF.text = stateArray[row]
- break
- case 3:
- districtTF.text = districtArray[row]
- break
- default:
- districtTF.text = districtArray[row]
- break
- }
- }
- }
- extension UserDetailsViewController: UITextFieldDelegate {
- // when user select a textfield, this method will be called
- func textFieldDidBeginEditing(_ textField: UITextField) {
- switch textField {
- case genderTF:
- activeTextField = 1
- customPicker.reloadAllComponents()
- case stateTF:
- activeTextField = 2
- customPicker.reloadAllComponents()
- case districtTF:
- activeTextField = 3
- customPicker.reloadAllComponents()
- default:
- activeTextField = 0
- }
- }
- }
- extension UserDetailsViewController: ToolbarPickerViewDelegate {
- func didTapDone() {
- switch activeTextField {
- case 1:
- let row = self.customPicker.selectedRow(inComponent: 0)
- self.customPicker.selectRow(row, inComponent: 0, animated: false)
- self.genderTF.text = self.genderData[row]
- self.genderTF.resignFirstResponder()
- case 2:
- let row = self.customPicker.selectedRow(inComponent: 0)
- self.customPicker.selectRow(row, inComponent: 0, animated: false)
- self.stateTF.text = self.stateArray[row]
- districtTF.isUserInteractionEnabled = true
- self.districtTF.text = nil
- districtArray.removeAll()
- getDistrict(stateId: self.stateIdArray[row])
- self.stateId = getStateId(name: self.stateArray[row])
- self.stateTF.resignFirstResponder()
- case 3:
- let row = self.customPicker.selectedRow(inComponent: 0)
- self.customPicker.selectRow(row, inComponent: 0, animated: false)
- self.districtTF.text = self.districtArray[row]
- self.districtId = getDistrictId(name: self.districtArray[row])
- self.districtTF.resignFirstResponder()
- default:
- return
- }
- }
-
- func didTapCancel() {
- switch activeTextField{
- case 1:
- self.genderTF.text = nil
- self.genderTF.resignFirstResponder()
- case 2:
- self.stateTF.text = nil
- self.stateTF.resignFirstResponder()
- case 3:
- self.districtTF.text = nil
- self.districtTF.resignFirstResponder()
- default:
- return
- }
- }
- }
- extension UserDetailsViewController {
-
- func saveStudent() {
- ActivityIndicator.start(style: .large, backColor: UIColor.black.withAlphaComponent(0.5), baseColor: UIColor.white)
- let topicData = DBManager.sharedInstance.database.objects(TopicModel.self)
- if topicData.count != 0 {
- let topicId = topicData[0].id
- let levelId = topicData[0].levelId
-
- let url = "\(ApiUrl.BASE_URL + ApiUrl.API_STUDENT)/save.json"
- print(url)
- let userIdentifier = UserDefaultsConstant.getValueFromUserDefults(for: Constant.userIdentifier) ?? ""
- let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? ""
- let headers: HTTPHeaders = [
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Cookie": "\(Constant.CookieName) = \(cookieValue)"
- ]
- print(headers)
-
- if mobileTF.text?.isEmpty == false {
- self.mobile = mobileTF.text!
- } else if genderTF.text?.isEmpty == false {
- self.gender = genderTF.text!
- } else if dobTF.text?.isEmpty == false {
- self.dateOfBirth = dobTF.text!
- }
-
- let params: Parameters?
- params = [
- "appleUserIdentifier" : userIdentifier,
- "name" : nameTF.text ?? "",
- "mobile" : mobile,
- "email" : emailTF.text ?? "",
- "username" : emailTF.text?.stringBefore("@") ?? "",
- "password" : emailTF.text?.stringBefore("@") ?? "",
- "gender" : gender,
- "dateOfBirth" : dateOfBirth,
- "state" : self.stateId,
- "district" : self.districtId,
- "topic" : topicId,
- "level" : levelId,
- "role" : 2
- ]
- print(params!)
-
- AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
- switch response.result {
- case .success(let value):
- ActivityIndicator.stop()
- print(value)
- let userData = value as! NSDictionary
-
- let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber;
- let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber;
- let dateCreated = userData.value(forKey: "dateCreated") as? String ?? "";
- let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? "";
-
- let district = userData.value(forKey: "district") as? NSObject;
- let districtId = district?.value(forKey: "id") as! NSNumber;
-
- let email = userData.value(forKey: "email") as? String ?? "";
- let enabled = userData.value(forKey: "enabled") as! NSNumber;
- let gender = userData.value(forKey: "gender") as? String ?? "";
- let id = userData.value(forKey: "id") as! NSNumber;
-
- let level = userData.value(forKey: "level") as? NSObject;
- let levelId = level?.value(forKey: "id") as! NSNumber;
- let mobile = userData.value(forKey: "mobile") as? String ?? "";
- let name = userData.value(forKey: "name") as? String ?? "";
- let password = userData.value(forKey: "password") as? String ?? "";
- let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber;
-
- let role = userData.value(forKey: "role") as? NSObject;
- let roleId = role?.value(forKey: "id") as! NSNumber;
-
- let state = userData.value(forKey: "state") as? NSObject;
- let stateId = state?.value(forKey: "id") as! NSNumber;
-
- let topic = userData.value(forKey: "topic") as? NSObject;
- let topicId = topic?.value(forKey: "id") as! NSNumber;
- let username = userData.value(forKey: "username") as? String ?? "";
- let appleUserIdentifier = userData.value(forKey: "appleUserIdentifier") as? String ?? "";
-
-
- var userModel = [UserDetailsModel]()
- let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: appleUserIdentifier)
- userModel.append(newUserModel)
- DBManager.sharedInstance.addData(objs: userModel)
- let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self)
- print("user count")
- print(userModelDB.count)
-
- UserDefaultsConstant.setIntValueInUserDefaults(objValue: Int(truncating: id), for: Constant.studentId)
- //Navigate to Home
- DispatchQueue.main.async {
- let loaderVC = self.storyboard?.instantiateViewController(withIdentifier:"LoadingAnimationViewController" ) as! LoadingAnimationViewController
- self.navigationController?.pushViewController(loaderVC, animated: true)
- }
- case .failure(let error):
- ActivityIndicator.stop()
- print(error)
- }
- }
- }
- }
-
- func updateStudent() {
- ActivityIndicator.start(style: .large, backColor: UIColor.black.withAlphaComponent(0.5), baseColor: UIColor.white)
- let topicData = DBManager.sharedInstance.database.objects(TopicModel.self)
- let studentId = UserDefaultsConstant.getIntValueFromUserDefults(for: Constant.studentId) as! Int
- if topicData.count != 0 {
- let topicId = topicData[0].id
- let levelId = topicData[0].levelId
-
- let url = "\(ApiUrl.BASE_URL + ApiUrl.API_STUDENT)/update.json"
- print(url)
- let userIdentifier = UserDefaultsConstant.getValueFromUserDefults(for: Constant.userIdentifier) ?? ""
- let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? ""
- let headers: HTTPHeaders = [
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Cookie": "\(Constant.CookieName) = \(cookieValue)"
- ]
- print(headers)
-
- let params: Parameters?
- params = [
- "appleUserIdentifier" : userIdentifier,
- "id" : studentId,
- "name" : nameTF.text ?? "",
- "mobile" : mobileTF.text ?? "",
- "email" : emailTF.text ?? "",
- "username" : emailTF.text?.stringBefore("@") ?? "",
- "password" : emailTF.text?.stringBefore("@") ?? "",
- "gender" : genderTF.text ?? "",
- "dateOfBirth" : dobTF.text ?? "",
- "state" : self.stateId,
- "district" : self.districtId,
- "topic" : topicId,
- "level" : levelId,
- "role" : 2
- ]
- print(params!)
-
- AF.request(url, method: .put, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
- switch response.result {
- case .success(let value):
- ActivityIndicator.stop()
- print(value)
- let userData = value as! NSDictionary
-
- let accountExpired = userData.value(forKey: "accountExpired") as! NSNumber;
- let accountLocked = userData.value(forKey: "accountLocked") as! NSNumber;
- let dateCreated = userData.value(forKey: "dateCreated") as? String ?? "";
- let dateOfBirth = userData.value(forKey: "dateOfBirth") as? String ?? "";
-
- let district = userData.value(forKey: "district") as? NSObject;
- let districtId = district?.value(forKey: "id") as! NSNumber;
-
- let email = userData.value(forKey: "email") as? String ?? "";
- let enabled = userData.value(forKey: "enabled") as! NSNumber;
- let gender = userData.value(forKey: "gender") as? String ?? "";
- let id = userData.value(forKey: "id") as! NSNumber;
-
- let level = userData.value(forKey: "level") as? NSObject;
- let levelId = level?.value(forKey: "id") as! NSNumber;
- let mobile = userData.value(forKey: "mobile") as? String ?? "";
- let name = userData.value(forKey: "name") as? String ?? "";
- let password = userData.value(forKey: "password") as? String ?? "";
- let passwordExpired = userData.value(forKey: "passwordExpired") as! NSNumber;
-
- let role = userData.value(forKey: "role") as? NSObject;
- let roleId = role?.value(forKey: "id") as! NSNumber;
-
- let state = userData.value(forKey: "state") as? NSObject;
- let stateId = state?.value(forKey: "id") as! NSNumber;
-
- let topic = userData.value(forKey: "topic") as? NSObject;
- let topicId = topic?.value(forKey: "id") as! NSNumber;
- let username = userData.value(forKey: "username") as? String ?? "";
- let appleUserIdentifier = userData.value(forKey: "appleUserIdentifier") as? String ?? "";
-
-
- var userModel = [UserDetailsModel]()
- let newUserModel = UserDetailsModel(accountExpired: Int(truncating: accountExpired), accountLocked: Int(truncating: accountLocked), dateCreated: dateCreated, dateOfBirth: dateOfBirth, districtId: Int(truncating: districtId), email: email, enabled: Int(truncating: enabled), gender: gender, id: Int(truncating: id), levelId: Int(truncating: levelId), mobile: mobile, name: name, password: password, passwordExpired: Int(truncating: passwordExpired), roleId: Int(truncating: roleId), stateId: Int(truncating: stateId), topicId: Int(truncating: topicId), username: username, appleIdentifier: appleUserIdentifier)
- DBManager.sharedInstance.deleteFromDb(object: userModel)
- userModel.append(newUserModel)
- DBManager.sharedInstance.addData(objs: userModel)
- let userModelDB = DBManager.sharedInstance.database.objects(UserDetailsModel.self)
- print("user count")
- print(userModelDB.count)
-
- //Navigate to Home
- DispatchQueue.main.async {
- //self.dismiss(animated: true, completion: nil)
- let homeVC = self.storyboard?.instantiateViewController(withIdentifier:"DashboardViewController" ) as! DashboardViewController
- self.navigationController?.pushViewController(homeVC, animated: true)
- }
- case .failure(let error):
- ActivityIndicator.stop()
- print(error)
- self.showToastMessage(message: Helper.translateText(inputText: "Failed to update profile data, please try again later"))
- }
- }
- }
- }
- }
- extension UserDetailsViewController : UserDetailsViewProtocol {
- func showAlert(title: String, message: String) {
- Alert.showAlert(on: self, with: title, message: message)
- }
-
- func stopActivityIndicator() {
- //activityIndicator.stopAnimating()
- }
-
- func showToastMessage(message: String) {
- self.view.makeToast(message)
- }
- }
|