You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1049 lines
42 KiB

//
// RecipientFormViewController.swift
// GMERemittance
//
// Created by Fm-user on 12/22/17.
// Copyright © 2017 Gobal Money Express Co. Ltd. All rights reserved.
//
import UIKit
import SDWebImage
protocol PaginationDelegate {
func updateCurrentIndex(status:String,recipient: Recipient,pageNumber: Int)
}
class RecipientFormViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var textFieldFirstName: UITextField!
@IBOutlet weak var textFieldMiddleName: UITextField!
@IBOutlet weak var textFieldLastName: UITextField!
@IBOutlet weak var textFieldCountry: UITextField!
@IBOutlet weak var textFieldState: UITextField!
@IBOutlet weak var textFieldDistrict: UITextField!
@IBOutlet weak var textFieldCity: UITextField!
@IBOutlet weak var textFieldAddress: UITextField!
@IBOutlet weak var textFieldRelation: UITextField!
@IBOutlet weak var textFieldMobile: UITextField!
@IBOutlet weak var textFieldEmail: UITextField!
@IBOutlet weak var textFieldTransferReason: UITextField!
private var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
private var pickerView = UIPickerView()
private var arrayOftextFields: [UITextField]!
private var activeTextField: UITextField?
private var selectedIndexFor: [String: Int] = [String: Int]()
public var paginationDelegate: PaginationDelegate!
private var recipientviewmodel: RecipientViewModel!
private var createNewRecipient: Bool!
var noInternetDialog: Bool?
var pageNumber: Int?
var recipient: Recipient?
var newRecipient: Recipient?
var pickerData: [String] = [String]()
var pickerDataState: [String] = [String]()
var pickerDataDistrict: [String] = [String]()
var pickerDataRelation: [String] = [String]()
var pickerDataReason: [String] = [String]()
var countryResult = false
var stateResult = false
var districtResult = false
var relationResult = false
var trasferReasonResult = false
private var updateParameters: [String: String] = [String: String] ()
public static var recipientConnectionTimeOutConnectionCheck = 0
var pickerIndex: Int = 0
func createRecipientObject(recipientId: String) -> Recipient{
var recipient = Recipient()
recipient.recipientId = recipientId
recipient.firstName = textFieldFirstName.text
recipient.middleName = textFieldMiddleName.text
recipient.lastName = textFieldLastName.text
recipient.city = textFieldCity.text
recipient.address = textFieldAddress.text
recipient.mobileNumber = textFieldMobile.text
recipient.email = textFieldEmail.text
if createNewRecipient! {
if let index = selectedIndexFor["country"]{
if recipientviewmodel.getCountryId(index: index) != "N/A"{
recipient.country = recipientviewmodel.getCountryId(index: index)
}
}
if let index = selectedIndexFor["relation"]{
recipient.relation = recipientviewmodel.getRelationValue(index: index)
}
if let index = selectedIndexFor["transferReason"]{
recipient.reason = recipientviewmodel.getTransferReasonValue(index: index)
}
if let index = selectedIndexFor["state"]{
recipient.state = recipientviewmodel.getStateValue(index: index)
}
if let index = selectedIndexFor["district"]{
recipient.district = recipientviewmodel.getDistrictValue(index: index)
}
} else {
if let index = selectedIndexFor["country"]{
recipient.country = recipientviewmodel.getCountryName(index: index)
}
if let index = selectedIndexFor["country"]{
recipient.countryId = recipientviewmodel.getCountryId(index: index)
}
if let index = selectedIndexFor["relation"]{
recipient.relationId = recipientviewmodel.getRelationValue(index: index)
}
if let index = selectedIndexFor["relation"]{
recipient.relation = recipientviewmodel.getRelationName(index: index)
}
if let index = selectedIndexFor["transferReason"]{
recipient.reasonId = recipientviewmodel.getTransferReasonValue(index: index)
}
if let index = selectedIndexFor["transferReason"]{
recipient.reason = recipientviewmodel.getTransferReasonName(index: index)
}
if let index = selectedIndexFor["state"]{
recipient.state = recipientviewmodel.getState(index: index)
}
if let index = selectedIndexFor["state"]{
recipient.stateId = recipientviewmodel.getStateValue(index: index)
}
if let index = selectedIndexFor["district"]{
recipient.district = recipientviewmodel.getDistrict(index: index)
}
if let index = selectedIndexFor["district"]{
recipient.districtId = recipientviewmodel.getDistrictValue(index: index)
}
}
return recipient
}
@IBAction func createOrUpdateRecipient(_ sender: Any) {
startLoading()
let textFieldArray = [textFieldFirstName.text, textFieldLastName.text, textFieldCountry.text, textFieldState.text, textFieldDistrict.text, textFieldCity.text, textFieldAddress.text, textFieldRelation.text, textFieldMobile.text, textFieldTransferReason.text]
guard recipientviewmodel.allFieldsFilled(arrayofInfo: textFieldArray as! [String]) else {
self.popUpMessageError(value: 11, message: "Please fill all the fields")
stopLoading()
return
}
if createNewRecipient {
recipientviewmodel.createRecipient()
} else {
recipientviewmodel.updateRecipient(recipientId: (recipient?.recipientId)!, updateParams: updateParameters)
}
activeTextField?.resignFirstResponder()
}
func setPageNumber(pageNumber: Int){
self.pageNumber = pageNumber;
}
@objc func clearKeyboard() {
activeTextField?.resignFirstResponder()
}
override func viewDidLoad() {
super.viewDidLoad()
selectedIndexFor["country"] = 0
selectedIndexFor["transferReason"] = 0
selectedIndexFor["relation"] = 0
selectedIndexFor["state"] = 0
selectedIndexFor["district"] = 0
setUpNavBar(id: 201, title: "Send Money")
noInternetDialog = false
startLoading()
/// TODO: first transaction free message Display
/* tracktransactionviewmodel.internetConnection.value = nil
tracktransactionviewmodel.internetConnection.bind { [unowned self] in
guard $0 != nil else {
return
}
self.enableUserInteractions()
self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
self.popUpMessage(value: 15)
}
tracktransactionviewmodel.fetchTransactionList(recipientId: "", recipientName: "", transactionType: "", startDate: "", endDate: "")
tracktransactionviewmodel.transactionListObtained.bind{ [unowned self] in
guard $0 != nil else {
return
}
self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
self.enableUserInteractions()
guard $0! else {
self.popUpMessageError(value: 10, message: self.tracktransactionviewmodel.getErrorMessage())
return
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let transactionStatus = appDelegate.firstTranscationStatusForProfileForm
if self.tracktransactionviewmodel.getCount() == 0 && transactionStatus == true {
self.popUpMessage(value: 9)
}
}*/
RecipientListViewController.recipientStatus = false
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(clearKeyboard))
view.addGestureRecognizer(tap)
arrayOftextFields = [textFieldFirstName, textFieldMiddleName, textFieldLastName, textFieldCountry, textFieldState, textFieldDistrict, textFieldCity, textFieldAddress, textFieldRelation, textFieldMobile, textFieldEmail, textFieldTransferReason]
for textField in arrayOftextFields {
textField.delegate = self
}
pickerView.delegate = self
pickerView.dataSource = self
guard recipient == nil else {
createNewRecipient = false
recipientviewmodel = RecipientViewModel(recipient: recipient!)
setUpAnotherLoginListener(genericviewmodel: recipientviewmodel)
if let firstName = recipient?.firstName{
textFieldFirstName.text = firstName
}
if let middleName = recipient?.middleName{
textFieldMiddleName.text = middleName
}
if let lastName = recipient?.lastName{
textFieldLastName.text = lastName
}
if let district = recipient?.district{
textFieldDistrict.text = district
}
if let city = recipient?.city{
textFieldCity.text = city
}
if let state = recipient?.state{
textFieldState.text = state
}
if let address = recipient?.address{
textFieldAddress.text = address
}
if let mobileNumber = recipient!.mobileNumber{
textFieldMobile.text = mobileNumber
}
if let email = recipient?.email{
textFieldEmail.text = email
}
if let relation = recipient?.relation{
textFieldRelation.text = relation
}
if let reason = recipient?.reason{
textFieldTransferReason.text = reason
}
recipientviewmodel.recipientConnectionTimeOut.value = nil
/**
connection timeout
*/
recipientviewmodel.recipientConnectionTimeOut.bind { [unowned self] in
guard $0 != nil else {
return
}
self.stopLoading()
if RecipientFormViewController.recipientConnectionTimeOutConnectionCheck == 0{
RecipientFormViewController.recipientConnectionTimeOutConnectionCheck = RecipientFormViewController.recipientConnectionTimeOutConnectionCheck+1
self.popUpMessage(value: 27)
self.textFieldCountry.text = ""
self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
}
}
self.startLoading()
internetCheck()
self.setUpListener()
self.cddListBindCall()
fetchCountryList()
recipientviewmodel.fetchCDDListFor(cddName: cddCode.Province.rawValue, param: ["countryId": (recipient?.countryId)!])
if let stateId = recipient?.stateId {
recipientviewmodel.fetchCDDListFor(cddName: cddCode.District.rawValue, param: [ "countryId": (recipient?.countryId)!, "provinceId": stateId])
}
fetchRelationList()
fetchTransferReason()
return
}
createNewRecipient = true
recipientviewmodel = RecipientViewModel()
recipientviewmodel.recipientConnectionTimeOut.value = nil
/**
connection timeout
*/
recipientviewmodel.recipientConnectionTimeOut.bind { [unowned self] in
guard $0 != nil else {
return
}
self.stopLoading()
if RecipientFormViewController.recipientConnectionTimeOutConnectionCheck == 0{
RecipientFormViewController.recipientConnectionTimeOutConnectionCheck = RecipientFormViewController.recipientConnectionTimeOutConnectionCheck+1
self.popUpMessage(value: 27)
self.textFieldCountry.text = ""
self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
}
}
setUpAnotherLoginListener(genericviewmodel: recipientviewmodel)
internetCheck()
self.setUpListener()
cddListBindCall()
fetchCountryList()
fetchTransferReason()
fetchRelationList()
}
/**
Api request to fetch list of country
*/
func fetchCountryList(){
if recipientviewmodel.getCountryList().count == 0 {
recipientviewmodel.fetchListOfCountry()
}
}
/**
Api request to fetch transfer reason
*/
func fetchTransferReason() {
if recipientviewmodel.getTransferReason().count == 0 {
recipientviewmodel.fetchCDDListFor(cddName: cddCode.TransferReason.rawValue, param: ["": ""])
}
}
/**
Api request to fetch states
*/
func fetchStates() {
recipientviewmodel.fetchCDDListFor(cddName: cddCode.Province.rawValue, param: ["countryId": recipientviewmodel.getCountryId(index: selectedIndexFor["country"]!)])
}
/**
Api request to fetch district
*/
func fetchDistrict() {
recipientviewmodel.fetchCDDListFor(cddName: cddCode.District.rawValue, param: [ "countryId": recipientviewmodel.getCountryId(index: selectedIndexFor["country"]!), "provinceId": recipientviewmodel.getStateValue(index: selectedIndexFor["state"]!)])
}
/**
Api request to fetch list of relation
*/
func fetchRelationList() {
if recipientviewmodel.getRelationList().count == 0 {
recipientviewmodel.fetchCDDListFor(cddName: cddCode.Relation.rawValue, param: ["": ""])
}
}
override func viewDidDisappear(_ animated: Bool) {
RecipientListViewController.recipientStatus = false
}
/**
Check internet connection
*/
func internetCheck(){
recipientviewmodel.internetConnection.bind { [unowned self] in
guard $0 != nil else {
return
}
if !self.noInternetDialog! {
self.stopLoading()
self.popUpMessage(value: 15)
self.textFieldCountry.text = ""
self.textFieldCountry.leftViewMode = UITextFieldViewMode.never
}
self.stopLoading()
self.noInternetDialog = true
}
}
/**
bind call for recipient both create and update
*/
func setUpListener() {
recipientviewmodel.recipientCreatedUpdated.bind { [unowned self] in
guard $0 != nil else {
return
}
guard $0! else {
//self.popUpMessageError(value: 10, message: self.recipientviewmodel.getErrorMessage())
self.stopLoading()
return
}
if self.createNewRecipient {
self.newRecipient = self.recipientviewmodel.getCreatedRecipient()
self.addRecipient()
} else {
self.recipientUpdateMessage()
}
}
/**
bind call for country list
*/
recipientviewmodel.cddCountryListAvailable.bind { [weak self] in
guard $0 != nil else {
return
}
guard $0! else {
// self?.popUpMessageError(value: 10, message: (self?.recipientviewmodel.getErrorMessage())!)
return
}
if self?.recipient != nil {
self?.pickerData = (self?.recipientviewmodel.getCountryNameList())!
if let countryId = self?.recipient?.countryId{
let countryIndex = self?.recipientviewmodel.getIndex(id: countryId)
if let url = self?.recipientviewmodel.getCountryFlagUrlList()[countryIndex!]{
let url = url
self?.selectedIndexFor["country"] = countryIndex
self?.showCountryWithFlag(textField: (self?.textFieldCountry)!, url: url, index: countryIndex!)
}
}
}
self?.countryResult = true
if (self?.createNewRecipient)! {
self?.stopLoading()
} else {
self?.checkResult()
}
}
}
/**
bind call for cddList
- Transfer reason
- relation
- Province
- District
*/
func cddListBindCall(){
recipientviewmodel.cddListAvailable.bind { [weak self] in
guard $0 != nil else {
return
}
guard $0! != 0 else {
// self?.popUpMessageError(value: 10, message: (self?.recipientviewmodel.getErrorMessage())!)
return
}
self?.pickerDataRelation = (self?.recipientviewmodel.getRelationList())!
self?.pickerDataReason = (self?.recipientviewmodel.getTransferReason())!
if !(self?.createNewRecipient)! {
switch $0!{
case 1:
self?.pickerDataReason = (self?.recipientviewmodel.getTransferReason())!
if self?.textFieldTransferReason.text != ""{
if let reasonIndex = self?.pickerDataReason.index(of: (self?.textFieldTransferReason.text)!) {
self?.selectedIndexFor["transferReason"] = reasonIndex
}
}
self?.trasferReasonResult = true
case 2:
self?.pickerDataState = (self?.recipientviewmodel.getStateList())!
if self?.textFieldState.text != "" {
if let stateIndex = self?.pickerDataState.index(of: (self?.textFieldState.text)!){
self?.selectedIndexFor["state"] = stateIndex
}
} else {
self?.selectedIndexFor["state"] = 0
}
self?.stateResult = true
case 3:
self?.pickerDataDistrict = (self?.recipientviewmodel.getDistrictList())!
if self?.textFieldDistrict.text != ""{
if let districtIndex = self?.pickerDataDistrict.index(of: (self?.textFieldDistrict.text)!) {
self?.selectedIndexFor["district"] = districtIndex
}
} else {
self?.selectedIndexFor["district"] = 0
}
self?.districtResult = true
case 4:
self?.pickerDataRelation = (self?.recipientviewmodel.getRelationList())!
self?.selectedIndexFor["relation"] = self?.pickerDataRelation.index(of: (self?.textFieldRelation.text)!)
self?.relationResult = true
default:
return
}
}
if (self?.createNewRecipient)! {
self?.stopLoading()
} else {
self?.checkResult()
}
self?.recipientviewmodel.cddListAvailable.value = nil
}
}
/**
To check all result are available or not after multiple api call..
*/
func checkResult(){
if countryResult == true &&
stateResult == true &&
districtResult == true &&
relationResult == true &&
trasferReasonResult == true {
stopLoading()
}
}
/**
Disable user interaction while fetching data from api
*/
func startLoading(){
disableUserInteractions()
showActivityIndicator(activityIndicator: activityIndicator)
}
/**
Enable user interaction while fetching data from api
*/
func stopLoading(){
self.dismissActivityIndicator(activityIndicator: self.activityIndicator)
self.enableUserInteractions()
}
func addRecipient(){
let alert = UIAlertController(title:"Add", message:"New Receiver profile added successfully" , preferredStyle: .actionSheet)
present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when){
alert.dismiss(animated: true, completion: nil)
if let recipientId = self.self.recipientviewmodel.getCreatedRecipient().recipientId, let pageNumber = self.pageNumber{
self.paginationDelegate.updateCurrentIndex(status: "add",recipient: self.createRecipientObject(recipientId:recipientId),pageNumber: pageNumber)
}
self.navigationController?.popViewController(animated: true)
}
}
func recipientUpdateMessage(){
let alert = UIAlertController(title:"Update", message:"Receiver profile updated successfully" , preferredStyle: .actionSheet)
present(alert, animated: true, completion: nil)
let when = DispatchTime.now() + 2
DispatchQueue.main.asyncAfter(deadline: when){
// your code with delay
alert.dismiss(animated: true, completion: nil)
if let recipientId = self.recipient?.recipientId , let pageNumber = self.pageNumber{
self.paginationDelegate.updateCurrentIndex(status: "update",recipient: self.createRecipientObject(recipientId: (recipientId)),pageNumber: pageNumber)
}
self.navigationController?.popViewController(animated: true)
}
}
@objc func keyboardWillShow(notification: NSNotification) {
var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
keyboardFrame = self.view.convert(keyboardFrame, from: nil)
var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height + 70
self.scrollView.contentInset = contentInset
}
@objc func keyboardWillHide(notification: NSNotification) {
self.scrollView.contentInset = UIEdgeInsets.zero
}
//Doing Picker view button
func pickUp(_ textField : UITextField){
// UIPickerView
self.pickerView = UIPickerView(frame:CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: 216))
self.pickerView.delegate = self
self.pickerView.dataSource = self
//self.pickerView.backgroundColor = UIColor.white
textField.inputView = self.pickerView
// ToolBar
let toolBar = UIToolbar()
toolBar.barStyle = .default
toolBar.isTranslucent = true
toolBar.tintColor = UIColor(red: 92/255, green: 216/255, blue: 255/255, alpha: 1)
toolBar.sizeToFit()
// Adding Button ToolBar
let customButton = UIButton()
var cancel = UIBarButtonItem()
customButton.setTitle("Done", for: .normal)
customButton.addTarget(self, action: #selector(doneClick), for: .touchUpInside)
customButton.setTitleColor(UIColor(hex : 0xED1C24), for: .normal)
customButton.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
cancel = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(self.cancelClick))
cancel.tintColor = UIColor.black
let doneButton = UIBarButtonItem(customView: customButton)
let spaceButton = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil)
toolBar.setItems([cancel,spaceButton, doneButton], animated: false)
toolBar.isUserInteractionEnabled = true
textField.inputAccessoryView = toolBar
}
@objc func doneClick() {
activeTextField?.resignFirstResponder()
self.noInternetDialog = false
if activeTextField == textFieldCountry {
textFieldState.text = ""
textFieldDistrict.text = ""
pickerDataState.removeAll()
pickerDataDistrict.removeAll()
selectedIndexFor["state"] = 0
selectedIndexFor["country"] = pickerIndex
startLoading()
if let index = selectedIndexFor["country"]{
recipientviewmodel.setCountryId(referenceIndex: index)
}
if let index = selectedIndexFor["country"]{
showCountryWithFlag(textField: activeTextField!, url: recipientviewmodel.getCountryFlagUrl(index: index), index: index)
}
if let index = selectedIndexFor["country"]{
updateParameters["country"] = recipientviewmodel.getCountryIdList()[index]
}
fetchStates()
} else if activeTextField == textFieldTransferReason {
if pickerDataReason.count > 0 {
if let transferReason = selectedIndexFor["transferReason"]{
recipientviewmodel.setTransferReason(referenceIndex: transferReason)
}
if let transferReasonIndex = selectedIndexFor["transferReason"]{
textFieldTransferReason.text = pickerDataReason[transferReasonIndex]
}
}
if let transferReason = selectedIndexFor["transferReason"]{
updateParameters["reason"] = recipientviewmodel.getTransferReasonValueList()[transferReason]
}
} else if activeTextField == textFieldRelation {
if pickerDataRelation.count > 0 {
if let relationIndex = selectedIndexFor["relation"]{
recipientviewmodel.setRelation(referenceIndex: relationIndex)
textFieldRelation.text = pickerDataRelation[relationIndex]
}
}
if let relationIndex = selectedIndexFor["relation"]{
updateParameters["relation"] = recipientviewmodel.getRelationValueList()[relationIndex]
}
} else if activeTextField == textFieldState {
textFieldDistrict.text = ""
pickerDataDistrict.removeAll()
selectedIndexFor["district"] = 0
if pickerDataState.count > 0{
if let state = selectedIndexFor["state"]{
recipientviewmodel.setState(referenceIndex: state)
textFieldState.text = pickerDataState[state]
}
}
startLoading()
fetchDistrict()
if let state = selectedIndexFor["state"]{
updateParameters["state"] = recipientviewmodel.getStateValueList()[state]
}
} else if activeTextField == textFieldDistrict {
if pickerDataDistrict.count > 0 {
if let district = selectedIndexFor["district"]{
recipientviewmodel.setDistrict(referenceIndex: district)
textFieldDistrict.text = pickerDataDistrict[district]
updateParameters["district"] = recipientviewmodel.getDistrictValueList()[district]
}
}
}
}
@objc func cancelClick(){
activeTextField?.resignFirstResponder()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "paymentMethod" {
let paymentViewController = segue.destination as! PaymentMethodViewController
paymentViewController.recipient = newRecipient
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
extension RecipientFormViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
activeTextField = textField
if textField == textFieldCountry ||
textField == textFieldRelation ||
textField == textFieldTransferReason ||
textField == textFieldState ||
textField == textFieldDistrict {
if createNewRecipient {
switch textField {
case textFieldCountry:
pickerData = recipientviewmodel.getCountryNameList()
case textFieldRelation:
pickerDataRelation = recipientviewmodel.getRelationList()
case textFieldTransferReason:
pickerDataReason = recipientviewmodel.getTransferReason()
case textFieldState:
pickerDataState = recipientviewmodel.getStateList()
case textFieldDistrict:
pickerDataDistrict = recipientviewmodel.getDistrictList()
default:
return
}
}
pickerView.reloadAllComponents()
switch textField {
case textFieldCountry:
guard pickerData.count > 0 else {
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
return
}
if let index = selectedIndexFor["country"]{
pickUp(textField)
pickerView.selectRow(index, inComponent: 0, animated: true)
recipientviewmodel.setCountryId(referenceIndex: index)
}
case textFieldRelation:
guard pickerDataRelation.count > 0 else {
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
return
}
pickUp(textField)
if textFieldRelation.text != "" {
if let index = pickerDataRelation.index(of: textFieldRelation.text!){
self.selectedIndexFor["relation"] = index
pickerView.selectRow(index, inComponent: 0, animated: true)
}
}
case textFieldTransferReason:
guard pickerDataReason.count > 0 else {
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
return
}
pickUp(textField)
if textFieldTransferReason.text != "" {
if let index = pickerDataReason.index(of: textFieldTransferReason.text!){
self.selectedIndexFor["transferReason"] = index
pickerView.selectRow(index, inComponent: 0, animated: true)
}
}
case textFieldState:
guard pickerDataState.count > 0 else {
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
return
}
pickUp(textField)
if textFieldState.text != ""{
if let index = pickerDataState.index(of: textFieldState.text!){
self.selectedIndexFor["state"] = index
pickerView.selectRow(index, inComponent: 0, animated: true)
}
}
case textFieldDistrict:
guard pickerDataDistrict.count > 0 else {
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Fetching data", message: "Please fill other fields while some data are being loaded")
return
}
pickUp(textField)
if textFieldDistrict.text != ""{
if let index = pickerDataDistrict.index(of: textFieldDistrict.text!) {
self.selectedIndexFor["district"] = index
pickerView.selectRow(index, inComponent: 0, animated: true)
}
}
default:
return
}
}
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
let index: Int = arrayOftextFields.index(of: textField)!
guard index < (arrayOftextFields.count-1) else {
textField.resignFirstResponder()
return true
}
arrayOftextFields[index+1].becomeFirstResponder()
return true
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let newString = (textField.text! as NSString).replacingCharacters(in: range, with: string)
switch textField {
case textFieldFirstName:
recipientviewmodel.updateFirstName(firstName: newString)
case textFieldMiddleName:
recipientviewmodel.updateMiddleName(middleName: newString)
case textFieldLastName:
recipientviewmodel.updateLastName(lastName: newString)
case textFieldCity:
recipientviewmodel.updateCity(city: newString)
case textFieldAddress:
recipientviewmodel.updateAddress(address: newString)
case textFieldMobile:
recipientviewmodel.updateMobile(mobile: newString)
case textFieldEmail:
recipientviewmodel.updateEmail(email: newString)
default:
return false
}
return true
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
switch textField {
case textFieldState:
if textFieldCountry.text == "" {
textFieldCountry.resignFirstResponder()
textField.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Select Country!", message: "Please select the country first.")
return false
} else {
return true
}
case textFieldDistrict:
if textFieldState.text == ""{
textFieldCountry.resignFirstResponder()
textFieldState.resignFirstResponder()
self.popUpMessageInfo(value: 16, title: "Select State/Province!", message: "Please select the State/Province first")
return false
} else {
return true
}
default:
return true
}
}
func textFieldDidEndEditing(_ textField: UITextField) {
if recipient != nil {
switch textField {
case textFieldFirstName:
updateParameters["firstName"] = textField.text!
case textFieldMiddleName:
updateParameters["middleName"] = textField.text!
case textFieldLastName:
updateParameters["lastName"] = textField.text!
case textFieldCountry:
if let index = selectedIndexFor["country"]{
updateParameters["country"] = recipientviewmodel.getCountryId(index: index)
}
case textFieldState:
if let index = selectedIndexFor["state"]{
updateParameters["state"] = recipientviewmodel.getStateValue(index: index)
}
case textFieldDistrict:
if let index = selectedIndexFor["district"]{
updateParameters["district"] = recipientviewmodel.getDistrictValue(index: index)
}
case textFieldCity:
updateParameters["city"] = textField.text!
case textFieldAddress:
updateParameters["address"] = textField.text!
case textFieldRelation:
if let index = selectedIndexFor["relation"]{
updateParameters["relation"] = recipientviewmodel.getRelationValue(index: index)
}
case textFieldMobile:
updateParameters["mobileNumber"] = textField.text!
case textFieldEmail:
updateParameters["email"] = textField.text!
case textFieldTransferReason:
if let index = selectedIndexFor["transferReason"]{
updateParameters["transferReason"] = recipientviewmodel.getTransferReasonValue(index: index)
}
default:
return
}
}
}
}
extension RecipientFormViewController: UIPickerViewDataSource, UIPickerViewDelegate {
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if activeTextField == textFieldCountry {
return pickerData.count
} else if activeTextField == textFieldState{
return pickerDataState.count
} else if activeTextField == textFieldDistrict{
return pickerDataDistrict.count
} else if activeTextField == textFieldRelation{
return pickerDataRelation.count
} else if activeTextField == textFieldTransferReason {
return pickerDataReason.count
} else {
return 0
}
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
if activeTextField == textFieldCountry {
return pickerData[row]
} else if activeTextField == textFieldState{
return pickerDataState[row]
} else if activeTextField == textFieldDistrict {
return pickerDataDistrict[row]
}else if activeTextField == textFieldRelation{
return pickerDataRelation[row]
} else if activeTextField == textFieldTransferReason{
return pickerDataReason[row]
} else {
return ""
}
}
func showCountryWithFlag(textField: UITextField, url: String, index: Int) {
let paddingView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 50))
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 30, height: 30))
imageView.center = paddingView.center
if let flagUrl = URL(string: url) {
imageView.sd_setImage(with: flagUrl, placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
}
paddingView.addSubview(imageView)
textField.leftViewMode = UITextFieldViewMode.always
textField.leftView = paddingView
textField.text = pickerData[index]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if activeTextField == textFieldCountry {
pickerIndex = row
} else if activeTextField == textFieldState{
selectedIndexFor["state"] = row
} else if activeTextField == textFieldDistrict {
selectedIndexFor["district"] = row
} else if activeTextField == textFieldRelation{
selectedIndexFor["relation"] = row
} else if activeTextField == textFieldTransferReason{
selectedIndexFor["transferReason"] = row
}
}
func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat {
return 60
}
func pickerView(_ pickerView: UIPickerView, viewForRow row: Int, forComponent component: Int, reusing view: UIView?) -> UIView {
var myImageView: UIImageView?
let myView = UIView(frame: CGRect(x: 0, y: 0, width: pickerView.bounds.width - 30, height: 60))
let myLabel = UILabel(frame: CGRect(x: 60, y: 0, width: pickerView.bounds.width - 90, height: 60 ))
myView.addSubview(myLabel)
if activeTextField == textFieldCountry{
myLabel.text = pickerData[row]
myImageView = UIImageView(frame: CGRect(x: 0, y: 15, width: 40, height: 40))
myImageView?.sd_setImage(with:URL(string: self.recipientviewmodel.getCountryFlagUrl(index: row)), placeholderImage: nil, options: [.progressiveDownload,.scaleDownLargeImages], completed: nil)
myView.addSubview(myImageView!)
} else if activeTextField == textFieldState {
myLabel.text = pickerDataState[row]
} else if activeTextField == textFieldDistrict {
myLabel.text = pickerDataDistrict[row]
} else if activeTextField == textFieldRelation {
myLabel.text = pickerDataRelation[row]
} else if activeTextField == textFieldTransferReason{
myLabel.text = pickerDataReason[row]
}
return myView
}
}