You are on page 1of 16

ddddddddddd

let modelName = UIDevice.current.modelName


let systemVersion = UIDevice.current.systemVersion
var countAllForPendingNotification = 0
var totalDocImages = 0
var uploadedDocImages = 0
var isPreviousButtonImagesClicked = false
var firstTimeCall = false

//For DocUpload
var dateCityVenueArrayDoc = NSArray()
var arMainBatchForDoc = [ImageBatchDetailForPassport]()
var selectedDateIDDoc = 0
var selectedCityIDDoc = 0

// For DoubtUpload
var arDateDoubt = [DoubtDateListTBL]()
var arCityDoubt = [DoubtCityListTBL]()
var completionHandler: AWSS3TransferUtilityUploadCompletionHandlerBlock?
var arrMedia = [Data]()

//MARK: ViewController LifeCycle


override func viewDidLoad(){
super.viewDidLoad()
UIApplication.shared.applicationIconBadgeNumber = 0
self.removeHistoryNotifications()
self.addNotfications()
self.addTapGestures()
self.fillMainUploadTab()
self.activateDocDate()
self.deactivateDocCity()
self.deactivateDocCameraBtn()
self.getDocumentsData()
// self.demoAWS()
}

func demoAWS(){
var urlList = [String]();
var itemUploadingIndex = 0
let imageDemo = UIImage(named: "candy_camera")
let imageData = imageDemo?.jpegData(compressionQuality: 0.0)
self.arrMedia.append(imageData!)
self.completionHandler = { (task, error) -> Void in
DispatchQueue.main.async(execute: {
if let error = error {
print("Failed with error: \(error)")
DispatchQueue.main.async {
print("something went wrong")

}
}
else{
urlList.append(aiServiceManager.getAbsoluteS3Url(key:
task.key))
itemUploadingIndex += 1
// DispatchQueue.main.async {
// HIDE_CUSTOM_LOADER()
// }
if self.arrMedia.count > itemUploadingIndex{
aiServiceManager.uploadFilesToAwsS3(fileUrls:
[self.arrMedia[itemUploadingIndex]], completionHandler: self.completionHandler!)
// let appDelegate = UIApplication.shared.delegate as!
AppDelegate
// appDelegate.lblUploadingMessage?.text = "Uploading \
(itemUploadingIndex + 1) of \(self.arrMedia.count) files"
}
if urlList.count == self.arrMedia.count {
print("successfully upload")
print(urlList)
// all files are uploaded. Call the back-end server API
to update portfolio.
// DispatchQueue.main.async {
// HIDE_CUSTOM_LOADER()
// }
// self.callBackendServerAPI(urlList: urlList)
}
}
})
}
if self.arrMedia.count > 0{
aiServiceManager.uploadFilesToAwsS3(fileUrls: [self.arrMedia[0]],
completionHandler: completionHandler!)
// let appDelegate = UIApplication.shared.delegate as! AppDelegate
// appDelegate.lblUploadingMessage?.text = "Uploading \
(itemUploadingIndex + 1) of \(self.arrMedia.count) files"
}
}

override var preferredStatusBarStyle: UIStatusBarStyle {


return .lightContent
}

override func viewWillAppear(_ animated: Bool) {


super.viewWillAppear(animated)
self.appDelegate.allowLandscape = false
let value = UIInterfaceOrientation.portrait.rawValue
UIDevice.current.setValue(value, forKey: "orientation")
UIView.setAnimationsEnabled(true)
self.checkUploadedRecordsForDoc()
}

//MARK: Add Gestures


func addTapGestures(){
let tapGestureDocDate = UITapGestureRecognizer(target: self, action:
#selector(self.tapDocumentDateViewClicked(_:)))
self.viewDocumentDate.addGestureRecognizer(tapGestureDocDate)
let tapGestureDocCity = UITapGestureRecognizer(target: self, action:
#selector(self.tapDocumentCityViewClicked(_:)))
self.viewDocumentCity.addGestureRecognizer(tapGestureDocCity)

//MARK: Add & Remove Notifications


func addNotfications(){
NotificationCenter.default.addObserver(self, selector:
#selector(HomeDoubtVC.historyLogOutShow(_:)), name: NSNotification.Name(rawValue:
"DoubtHistoryLogOutShow"), object: nil)
}

func removeHistoryNotifications(){
NotificationCenter.default.removeObserver(self, name:
NSNotification.Name(rawValue: "DoubtHistoryLogOutShow"), object: nil)
}

//MARK: IBActions

@IBAction func backBtnClicked(_ sender: UIButton) {


self.navigationController?.popViewController(animated: true)
}
@IBAction func contactBtnClicked(_ sender: AnyObject){
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Storyboard", bundle:
nil)
let controller = mainStoryboard.instantiateViewController(withIdentifier:
"ContactUsVC") as! ContactUsVC
self.addChild(controller)
controller.view.frame = self.view.bounds
self.view.addSubview(controller.view)
controller.didMove(toParent: self)
}

@IBAction func btnRefreshClicked(_ sender: Any) {


if self.appDelegate.isUploadingBatchesDoubt == true{
self.view.makeToast(message: "Please wait while Uploading File(s)")
}else {
UIApplication.shared.isIdleTimerDisabled = true
self.uploadDataForDocument()
}
}

@IBAction func btnMainHdrUploadClicked(_ sender: Any) {


self.fillMainUploadTab()
}

@IBAction func btnMainHdrHistoryClicked(_ sender: Any) {


self.activateDocDate()
self.deactivateDocCity()
self.deactivateDocCameraBtn()
self.fillMainHistoryTab()
self.showHistoryVC()
}

//MARK: Doc Upload Actions


@objc func tapDocumentDateViewClicked(_ sender: UITapGestureRecognizer) {
self.activateDocDate()
self.deactivateDocCity()
self.deactivateDocCameraBtn()
if self.arDateDoubt.count == 0{
self.arDateDoubt = DoubtDatabaseHelper.sharedInstance.getDateDoubt()
}
let DropDownDocumentDateArray = DropDown()
for dic in self.arDateDoubt{
if let stateName = dic.examDate{
DropDownDocumentDateArray.dataSource.append(stateName)
}
}
DropDownDocumentDateArray.show()
DropDownDocumentDateArray.selectionAction = { [unowned self] (index, item)
in
self.lblDocumentTestDate.text = item
self.selectedDateIDDoc = Int(self.arDateDoubt[index].dateID)
self.fillUpDocDate()
self.activateDocCity()
self.deactivateDocCameraBtn()
self.checkAllDocValueFill()
}
DropDownDocumentDateArray.anchorView = self.viewDocumentDate
DropDownDocumentDateArray.bottomOffset = CGPoint(x: 0,
y:self.viewDocumentDate.bounds.height)
}

@objc func tapDocumentCityViewClicked(_ sender: UITapGestureRecognizer) {


self.activateDocCity()
self.deactivateDocCameraBtn()
let DropDownDocumentCityArray = DropDown()
self.arCityDoubt =
DoubtDatabaseHelper.sharedInstance.getCityFromSpecificDateDoubt(dateID:
Int64(self.selectedDateIDDoc))
for dic in self.arCityDoubt{
if let stateName = dic.cityName{
DropDownDocumentCityArray.dataSource.append(stateName)
}

}
DropDownDocumentCityArray.show()
DropDownDocumentCityArray.selectionAction = { [unowned self] (index, item)
in
self.lblDocumentTestCity.text = item
self.selectedCityIDDoc = Int(self.arCityDoubt[index].cityID)
self.fillUpDocCity()
self.deactivateDocCameraBtn()
self.checkAllDocValueFill()
}
DropDownDocumentCityArray.anchorView = self.viewDocumentCity
DropDownDocumentCityArray.bottomOffset = CGPoint(x: 0,
y:self.viewDocumentCity.bounds.height)
}

//MARK: DocUpload Camera Button Action


func validationCheckForDoc() -> (Bool, String) {
var error = false
var message = ""
if(self.lblDocumentTestDate.text! == "Test Date"){
error = true
message = datenotSelected
}else if (self.lblDocumentTestCity.text! == "Test City"){
error = true
message = cityNil
}
return (error, message)
}
private func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return UIInterfaceOrientationMask.portrait
}

private func shouldAutorotate() -> Bool {


return true
}

func createDocAndPassToNextVC(){
self.appDelegate.batchDoubtId = self.randomString(length: 25)
print(UIDevice.current.orientation)
var text=""
switch UIDevice.current.orientation{
case .portrait:
text="Portrait"
case .portraitUpsideDown:
text="PortraitUpsideDown"
case .landscapeLeft:
text="LandscapeLeft"
case .landscapeRight:
text="LandscapeRight"
default:
text="Another"
}
print("you have moved: \(text)")
let secondStoryboard: UIStoryboard = UIStoryboard(name: "SecondStoryboard",
bundle: nil)

let vc = secondStoryboard.instantiateViewController(withIdentifier:
"PassportScanDoubtViewController")as! PassportScanDoubtViewController
vc.passSelfVC = self
vc.userid = (UserDefaults.standard.object(forKey: "userId") as! String)
vc.AppBatchId = self.appDelegate.batchDoubtId
vc.FileName = UUID().uuidString
vc.Module = ""
vc.Guestmode = true
let localCapture = self.getCaptureTimeAndCaptureDate()
vc.IsImpersonate = "true"
vc.ImpersonateBy = (UserDefaults.standard.object(forKey: "userId") as!
String)
vc.ImpersonateDate = localCapture.1
vc.DateID = self.selectedDateIDDoc
vc.CityID = self.selectedCityIDDoc
vc.PrimaryInfoID = 0
vc.DeviceID = UIDevice.current.identifierForVendor!.uuidString
vc.UploadedTime = localCapture.0
vc.MarkingType = ""
vc.comeFromUploadScreen = true
vc.TotalCandidates = ""
vc.spkLocation = ""
vc.speakingType = ""
vc.isComeFromDocuments = true
vc.testDate = self.lblDocumentTestDate.text ?? ""
vc.testCity = self.lblDocumentTestCity.text ?? ""
self.navigationController!.pushViewController(vc, animated: true)
}
@IBAction func docUploadCameraClicked(_ sender: AnyObject){
let errorTuple = self.validationCheckForDoc()
if errorTuple.0{
self.showAlertViewForErrorCheck(message: errorTuple.1)
return
}
self.createDocAndPassToNextVC()
}

//MARK: Add Validation Utilities


func fillMainUploadTab(){
self.btnMainUploads.setTitleColor(UIColor(red: 205.0/255.0, green:
9.0/255.0, blue: 21.0/255.0, alpha: 1.0), for: UIControl.State.normal)
self.btnMainHistory.setTitleColor(UIColor(red: 56.0/255.0, green:
56.0/255.0, blue: 56.0/255.0, alpha: 1.0), for: UIControl.State.normal)
self.viewHistory.isHidden = true
}

func fillMainHistoryTab(){
self.btnMainHistory.setTitleColor(UIColor(red: 205.0/255.0, green:
9.0/255.0, blue: 21.0/255.0, alpha: 1.0), for: UIControl.State.normal)
self.btnMainUploads.setTitleColor(UIColor(red: 56.0/255.0, green:
56.0/255.0, blue: 56.0/255.0, alpha: 1.0), for: UIControl.State.normal)
self.viewHistory.isHidden = false
}

func activateDocDate(){
self.selectedDateIDDoc = 0
self.viewDocumentDate.isUserInteractionEnabled = true
self.lblDocumentTestDate.text = "Test Date"
self.lblDocumentTestDate.textColor = self.model.themecolor
self.imgDocumentTestDateDropDown.image = UIImage(named:
"dropdown_arrowred.png")
self.imgIconTestDate.image = UIImage(named: "Availability_red.png")
self.imgDocumentTestDateBottom.backgroundColor = self.model.themecolor
}

func deactivateDocDate(){
self.selectedDateIDDoc = 0
self.viewDocumentDate.isUserInteractionEnabled = false
self.lblDocumentTestDate.text = "Test Date"
self.lblDocumentTestDate.textColor = self.model.disabledGrayColor
self.imgDocumentTestDateDropDown.image = UIImage(named:
"dropdown_lgrey.png")
self.imgIconTestDate.image = UIImage(named: "Availability_lgrey.png")
self.imgDocumentTestDateBottom.backgroundColor =
self.model.disabledGrayColor
}
func fillUpDocDate(){
self.lblDocumentTestDate.textColor = self.model.DarkgrayColor
self.imgDocumentTestDateDropDown.image = UIImage(named:
"dropdown_arrowgrey.png")
self.imgIconTestDate.image = UIImage(named: "Availability_grey.png")
self.imgDocumentTestDateBottom.backgroundColor = self.model.DarkgrayColor
}

func activateDocCity(){
self.selectedCityIDDoc = 0
self.viewDocumentCity.isUserInteractionEnabled = true
self.lblDocumentTestCity.text! = "Test City"
self.lblDocumentTestCity.textColor = self.model.themecolor
self.imgDocumentTestCityDropDown.image = UIImage(named:
"dropdown_arrowred.png")
self.imgIconTestCity.image = UIImage(named: "location_red.png")
self.imgDocumentTestCityBottom.backgroundColor = self.model.themecolor
}
func deactivateDocCity(){
self.selectedCityIDDoc = 0
self.viewDocumentCity.isUserInteractionEnabled = false
self.lblDocumentTestCity.text = "Test City"
self.lblDocumentTestCity.textColor = self.model.disabledGrayColor
self.imgDocumentTestCityDropDown.image = UIImage(named:
"dropdown_lgrey.png")
self.imgIconTestCity.image = UIImage(named: "location_lgrey.png")
self.imgDocumentTestCityBottom.backgroundColor = model.disabledGrayColor
}
func fillUpDocCity(){
self.lblDocumentTestCity.textColor = self.model.DarkgrayColor
self.imgDocumentTestCityDropDown.image = UIImage(named:
"dropdown_arrowgrey.png")
self.imgIconTestCity.image = UIImage(named: "location_grey.png")
self.imgDocumentTestCityBottom.backgroundColor = self.model.DarkgrayColor
}

func activateDocCameraBtn(){
self.btnDocumentCamera.isUserInteractionEnabled = true
self.btnDocumentCamera.alpha = 1.0
}

func deactivateDocCameraBtn(){
self.btnDocumentCamera.isUserInteractionEnabled = false
self.btnDocumentCamera.alpha = 0.2
}

func resetDocAllFields(){
self.activateDocDate()
self.deactivateDocCity()
self.deactivateDocCameraBtn()
}

func checkAllDocValueFill(){
if (self.lblDocumentTestDate.text! != "Test Date") &&
(self.lblDocumentTestCity.text! != "Test City") && self.selectedDateIDDoc != 0 &&
self.selectedCityIDDoc != 0{
self.activateDocCameraBtn()
}else{
self.deactivateDocCameraBtn()
}
}

//MARK: CallBack Notification Functions


@objc func historyLogOutShow(_ notification: NSNotification) {
let when = DispatchTime.now() + 0.5
DispatchQueue.main.asyncAfter(deadline: when) {
let controller:AlertViewController = AlertViewController(nibName:
"AlertViewController", bundle: nil)
controller.message = notification.object as! String
controller.comeFromForgotMpin = true
self.addChild(controller)
controller.view.frame = (self.appDelegate.window?.frame)!
self.view.addSubview(controller.view)
controller.didMove(toParent: self)
}
}

// MARK:- Delegate Function


func cameraMultipleSelectedImageDoubt(_ selectedImageArray: [UIImage]){
print("call CameraMultipleSelectedImageDoubt")
self.firstTimeCall = true
self.resetDocAllFields()
self.isPreviousButtonImagesClicked = false
self.uploadDataForDocument()
}

//MARK: Uploading Doc Functions


func checkUploadedRecordsForDoc(){
let arRemainDoc =
DatabaseHelper.sharedInstance.getMainBatchDocDataForUploading(isUploaded: "False")
if self.appDelegate.isUploadingBatchesDoubt == false{
if arRemainDoc.count > 0{
if self.firstTimeCall == false{
self.fireUploadPendingNotification()
self.firstTimeCall = true
}
}
if self.appDelegate.isUploadingBatchesDoubt == false{
if arRemainDoc.count > 0{
self.previousDocImages.isHidden = false
}else{
self.previousDocImages.isHidden = true
}
}
}
}

func getTotalDocImagesForUpload(){
self.totalDocImages = 0
self.uploadedDocImages = 0
for objMainBatch in self.arMainBatchForDoc{
let arImagesRemaining =
DatabaseHelper.sharedInstance.getRemainingImagesForAppId(appBatchId:
objMainBatch.appBatchId!)
let value = arImagesRemaining.count
self.totalDocImages = self.totalDocImages + value
}
}

func uploadDataForDocument(){
if self.appDelegate.isUploadingBatchesDoubt == false{
self.countAllForPendingNotification = 0
self.appDelegate.isUploadingBatchesDoubt = true
self.arMainBatchForDoc =
DatabaseHelper.sharedInstance.getMainBatchDocDataForUploading(isUploaded: "False")
if self.arMainBatchForDoc.count > 0{
if self.model.isConnectedToNetwork() == true{
self.getTotalDocImagesForUpload()
self.updateProgessViewForDoc()
self.previousDocImages.isHidden = true
self.progressLbl.isHidden = false
self.progressViewDoc.isHidden = false
self.updateProgressViewDocOnHistoryPage(isHide: false, isState:
"Start")
let countMain = 0
self.uploadMainDocument(mainBatchObjForDoc:
self.arMainBatchForDoc[countMain], indexMainBatch: countMain)
}else{
self.appDelegate.isUploadingBatchesDoubt = false
self.previousDocImages.isHidden = false
self.progressLbl.isHidden = true
self.progressViewDoc.isHidden = true
self.updateProgressViewDocOnHistoryPage(isHide: true, isState:
"Stop")
self.countAllForPendingNotification =
self.countAllForPendingNotification + 1
if self.countAllForPendingNotification ==
1{ self.fireUploadPendingNotification() }
}
}else{
self.deleteMainBatchForDoc()
self.appDelegate.isUploadingBatchesDoubt = false
}
}
}

//MARK: Uploading DocUpload Functions


func updateProgessViewForDoc(){
DispatchQueue.main.async {
self.progressLbl.text = "\(self.uploadedDocImages)" + "/" + "\
(self.totalDocImages)"
let getUploadedProgress = Double(self.uploadedDocImages) * 1.0
let finalProgress = getUploadedProgress / Double(self.totalDocImages)
self.progressViewDoc.progress = Float(finalProgress)
self.updateProgressViewDocOnHistoryPage(isHide: false, isState:
"Start")
}
}

func updateProgressViewDocOnHistoryPage(isHide : Bool , isState : String){


let DataDict = ["isHide": isHide, "isState" : isState, "uploadedFiles" :
self.uploadedDocImages, "totalFiles" : self.totalDocImages] as [String : Any]
NotificationCenter.default.post(name:
Notification.Name("refreshProgressBar"), object: nil, userInfo: DataDict)
}

func checkUploadingBatchesForDocument(){
let arRemainUploadDoc =
DatabaseHelper.sharedInstance.getMainBatchDocDataForUploading(isUploaded: "False")
if arRemainUploadDoc.count > 0{
self.previousDocImages.isHidden = false
}
}

func uploadMainDocument(mainBatchObjForDoc : ImageBatchDetailForPassport,


indexMainBatch : Int){
let countImage = 0
let arrImageForDoc = mainBatchObjForDoc.imagesBatchArray?.allObjects as!
[ImagesForPassport]
if arrImageForDoc.count > 0{
self.uploadDocumentDataOneByOne(imageObj: arrImageForDoc[countImage],
indexImage: countImage, mainBatchObjForDoc: mainBatchObjForDoc, arrImageForDoc:
arrImageForDoc, indexMainBatch: indexMainBatch)
}
}

func uploadDocumentDataOneByOne(imageObj: ImagesForPassport, indexImage : Int,


mainBatchObjForDoc : ImageBatchDetailForPassport, arrImageForDoc :
[ImagesForPassport], indexMainBatch : Int){
if self.model.isConnectedToNetwork() == false {
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.previousDocImages.isHidden = false
self.progressLbl.isHidden = true
self.progressViewDoc.isHidden = true
self.updateProgressViewDocOnHistoryPage(isHide: true, isState:
"Finish")
}
self.deleteMainBatchForDoc()
self.appDelegate.isUploadingBatchesDoubt = false
self.showAlertViewForErrorCheck(message: "Network error.")
return
}
if imageObj.isUploaded == "True"{
DatabaseHelper.sharedInstance.editImagesPassportData(objImagePassport:
imageObj)
self.uploadedDocImages = self.uploadedDocImages + 1
self.updateProgessViewForDoc()

var indexImage = indexImage


indexImage = indexImage + 1
if indexImage < arrImageForDoc.count{
self.uploadDocumentDataOneByOne(imageObj:
arrImageForDoc[indexImage], indexImage: indexImage, mainBatchObjForDoc:
mainBatchObjForDoc, arrImageForDoc: arrImageForDoc, indexMainBatch: indexMainBatch)
}else{
print("Specific Batch Images Complete")
DatabaseHelper.sharedInstance.editMainBatchDocData(objMainBatch:
mainBatchObjForDoc)
var indexMainBatch = indexMainBatch
indexMainBatch = indexMainBatch + 1
if indexMainBatch < self.arMainBatchForDoc.count{
self.uploadMainDocument(mainBatchObjForDoc:
self.arMainBatchForDoc[indexMainBatch], indexMainBatch: indexMainBatch)
}else{
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.previousDocImages.isHidden = true
self.progressLbl.isHidden = true
self.progressViewDoc.isHidden = true
self.updateProgressViewDocOnHistoryPage(isHide: true,
isState: "Finish")
}
print("All Batches complete")
print("Try to delete all specific and main batch document
data1")
self.deleteMainBatchForDoc()
self.appDelegate.isUploadingBatchesDoubt = false
}
}
return
}
var localUserId = ""
if let userIdStr = imageObj.userId{
localUserId = userIdStr
}
var DocType = "Passport"
if !imageObj.isPassport{ DocType = "Declaration" }
var isLast = "false"
if indexImage == (arrImageForDoc.count - 1){ isLast = "true" }
let parameters = ["AppBatchId" : imageObj.appBatchId!,
"DateId" : imageObj.dateID,
"CityId" : imageObj.cityID,
"VenueId" : imageObj.venueID,
"PassportNo" : imageObj.passport_no!,
"NoOfFiles" : arrImageForDoc.count,
"FileNameGuid" : imageObj.fileNameGuid!,
"FileName" : imageObj.fileName!,
"AppUploadDate" : imageObj.uploadedDate!,
"AppUploadTime" : imageObj.uploadedTime!,
"DocType" : DocType,
"IsLast" : isLast,
"Userid" : localUserId,
"UserFileBase64" : imageObj.image ?? ""
] as [String : Any]
let manager = Alamofire.SessionManager.default
manager.session.configuration.timeoutIntervalForRequest = 500
AppEngine().UploadedFileForPassport(parameter: parameters as NSDictionary,
completionHandler: { (response: NSDictionary?) in
if response == nil{
self.appDelegate.isUploadingBatchesDoubt = false
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.previousDocImages.isHidden = false
self.progressLbl.isHidden = true
self.progressViewDoc.isHidden = true
self.updateProgressViewDocOnHistoryPage(isHide: true, isState:
"Finish")
}
return
}
if response?.object(forKey: "success") as! Bool == true{
self.previousDocImages.isHidden = true
self.uploadedDocImages = self.uploadedDocImages + 1
self.updateProgessViewForDoc()
if response?.object(forKey: "isMailSend") as! Bool == true{
DispatchQueue.main.async {
var messStr = String(describing: (response?.object(forKey:
"fileCount"))!) + " File(s) Uploaded Successfully !!"
if self.isPreviousButtonImagesClicked == true{
messStr = String(describing: (response?.object(forKey:
"fileCount"))!) + " Previous File(s) Uploaded Successfully !!"
}
SecureUploadModel().localNotification(msg: messStr)
}
}
print("Anand: ", response!)
print("Again: ", imageObj.fileName)
DatabaseHelper.sharedInstance.editImagesPassportData(objImagePassport: imageObj)
var indexImage = indexImage
indexImage = indexImage + 1
if indexImage < arrImageForDoc.count{
self.uploadDocumentDataOneByOne(imageObj:
arrImageForDoc[indexImage], indexImage: indexImage, mainBatchObjForDoc:
mainBatchObjForDoc, arrImageForDoc: arrImageForDoc, indexMainBatch: indexMainBatch)
}else{
print("Specific Batch Images Complete")

DatabaseHelper.sharedInstance.editMainBatchDocData(objMainBatch:
mainBatchObjForDoc)
var indexMainBatch = indexMainBatch
indexMainBatch = indexMainBatch + 1
if indexMainBatch < self.arMainBatchForDoc.count{
self.uploadMainDocument(mainBatchObjForDoc:
self.arMainBatchForDoc[indexMainBatch], indexMainBatch: indexMainBatch)
}else{
print("All Batches complete")
print("Try to delete all specific and main batch document
data2")
self.deleteMainBatchForDoc()
print("Try to SecureUpload data")
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
self.previousDocImages.isHidden = true
self.progressLbl.isHidden = true
self.progressViewDoc.isHidden = true
self.updateProgressViewDocOnHistoryPage(isHide: true,
isState: "Finish")
}
self.appDelegate.isUploadingBatchesDoubt = false
}
}
}else {
self.appDelegate.isUploadingBatchesDoubt = false
if response?.object(forKey: "isLogout") != nil && !
(response?.object(forKey: "isLogout") is NSNull){
if response?.object(forKey: "isLogout") as! Bool{
self.showLogOutAlertView(message: response?.object(forKey:
"message") as! String)
}
}else{
self.view.makeToast(message: response?.object(forKey:
"message") as! String)
}
}
})
}

func deleteMainBatchForDoc(){
let arDeleteMainDoc =
DatabaseHelper.sharedInstance.getMainBatchDocDataForUploading(isUploaded: "True")
for objDeleteMainDoc in arDeleteMainDoc{
let arAllImagesForObj = objDeleteMainDoc.imagesBatchArray?.allObjects
as! [ImagesForPassport]
for objImage in arAllImagesForObj{

DatabaseHelper.sharedInstance.deleteImagesPassportData(objImagePassport: objImage)
}
DatabaseHelper.sharedInstance.deleteMainBatchDocData(objMainBatch:
objDeleteMainDoc)
}

//MARK:- API
func getDocumentsData(){
if self.model.isConnectedToNetwork() == false{
return
}
let parameters = ["":""]
AppEngine().getDoubtsData(parameter: parameters as NSDictionary,
completionHandler: { (response: NSDictionary?) in
if response == nil{ return }
if response?.object(forKey: "success") as! Bool == true{
if response?.object(forKey: "data") != nil && !
(response?.object(forKey: "data") is NSNull){
let dicArray : NSArray = response?.object(forKey: "data") as!
NSArray

DoubtDatabaseHelper.sharedInstance.deleteDoubtDateCityEntities()
for dateObj in dicArray{
let dateID = (dateObj as! NSDictionary).object(forKey:
"dateID") as! Int64
let examDate = (dateObj as! NSDictionary).object(forKey:
"examDate") as! String
print(examDate)
var dateList = [String : Any]()
dateList["dateID"] = dateID
dateList["examDate"] = examDate
DoubtDatabaseHelper.sharedInstance.saveDateDoubt(dateDict:
dateList)
let cityArray = (dateObj as! NSDictionary).object(forKey:
"cityList") as! NSArray
for cityObj in cityArray{
let cityID = (cityObj as! NSDictionary).object(forKey:
"cityID") as! Int64
let cityName = (cityObj as!
NSDictionary).object(forKey: "cityName") as! String
var cityList = [String : Any]()
cityList["cityID"] = cityID
cityList["cityName"] = cityName
cityList["dateID"] = dateID
print(cityName)

DoubtDatabaseHelper.sharedInstance.saveCityDoubt(cityDict: cityList)
}
}
}
if response?.object(forKey: "bucketname") != nil && !
(response?.object(forKey: "bucketname") is NSNull){
let doubtBucketName : String = response?.object(forKey:
"bucketname") as! String
self.prefs.set(doubtBucketName, forKey: "DoubtBucketName")
}
if response?.object(forKey: "accesskey") != nil && !
(response?.object(forKey: "accesskey") is NSNull){
let doubtAccessKey : String = response?.object(forKey:
"accesskey") as! String
self.prefs.set(doubtAccessKey, forKey: "DoubtAccessKey")

}
if response?.object(forKey: "secretkey") != nil && !
(response?.object(forKey: "secretkey") is NSNull){
let doubtSecretKey : String = response?.object(forKey:
"secretkey") as! String
self.prefs.set(doubtSecretKey, forKey: "DoubtSecretKey")
}
if response?.object(forKey: "foldername") != nil && !
(response?.object(forKey: "foldername") is NSNull){
let doubtFolderName : String = response?.object(forKey:
"foldername") as! String
self.prefs.set(doubtFolderName, forKey: "DoubtFolderName")

}
self.prefs.synchronize()
}else{
if response?.object(forKey: "isLogout") != nil && !
(response?.object(forKey: "isLogout") is NSNull){
if response?.object(forKey: "isLogout") as! Bool{
self.showLogOutAlertView(message: response?.object(forKey:
"message") as! String)
}
}else{
self.view.makeToast(message: response?.object(forKey:
"message") as! String)
}
}

})
}

//MARK:- Reuse Utilities


func showHistoryVC(){
let mainStoryboard: UIStoryboard = UIStoryboard(name: "SecondStoryboard",
bundle: nil)
let VC_Obj = mainStoryboard.instantiateViewController(withIdentifier:
"DoubtHistoryVC") as! DoubtHistoryVC
self.addChild(VC_Obj)
VC_Obj.view.frame = self.viewHistory.bounds
self.viewHistory.addSubview(VC_Obj.view)
VC_Obj.didMove(toParent: self)
}

func showAlertViewForErrorCheck(message : String){


let controller:AlertViewController = AlertViewController(nibName:
"AlertViewController", bundle: nil)
controller.message = message
self.addChild(controller)
controller.view.frame = (self.appDelegate.window?.frame)!
self.view.addSubview(controller.view)
controller.didMove(toParent: self)
}

func showLogOutAlertView(message : String){


DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
let controller:AlertViewController = AlertViewController(nibName:
"AlertViewController", bundle: nil)
controller.message = message
controller.comeFromForgotMpin = true
self.addChild(controller)
controller.view.frame = (self.appDelegate.window?.frame)!
self.view.addSubview(controller.view)
controller.didMove(toParent: self)
}
}

func fireUploadPendingNotification(){
let localNotification = UILocalNotification()
localNotification.soundName = UILocalNotificationDefaultSoundName
localNotification.alertBody = "Some uploads are still pending. Tap the
refresh button to upload."
localNotification.alertTitle = "ExM"
localNotification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(localNotification)
}

func getCaptureTimeAndCaptureDate() -> (String, String){


//--------------- get current date ---------
let date = Date()
let calendar = Calendar.current
let components = (calendar as
NSCalendar).components([.day , .month , .year], from: date)
let year = String(describing: components.year!)
let month = components.month
let day = components.day
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm:ss"
let defaultTimeZoneStr = formatter.string(from: date)
let CapturedTime = defaultTimeZoneStr as String
var myStringMonth = String(describing: month!)
var myStringDay = String(describing: day!)
if(myStringMonth.count == 1 ){
myStringMonth = "\(String(describing: myStringMonth))"
}
if(myStringDay.count == 1 ){
myStringDay = "\(String(describing: myStringDay))"
}
let CapturedDate = "\(String(describing: year))-\(String(describing:
myStringMonth))-\(String(describing: myStringDay))"
return (CapturedTime, CapturedDate)
}

func randomString(length: Int) -> String {


let letters : NSString =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
}

You might also like