Skip to content

Instantly share code, notes, and snippets.

@idmcalculus
Created February 1, 2023 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save idmcalculus/0d50ddda7ec3e5fa4098d439b3340f62 to your computer and use it in GitHub Desktop.
Save idmcalculus/0d50ddda7ec3e5fa4098d439b3340f62 to your computer and use it in GitHub Desktop.
Swift code containing table views for carrying out iCloud operations
//
// ICloudSubMenuVC.swift
// DressMeasurement
//
// Created by Suleiman Abubakar on 10/05/2022.
// Copyright © 2022 Aeeiee. All rights reserved.
//
import UIKit
import CloudKit
class ICloudSubMenuVC: UIViewController {
@IBOutlet weak var icloudMenuTableView: UITableView!
@IBOutlet weak var icloudMenuTableLeadingConstraint: NSLayoutConstraint?
@IBOutlet weak var icloudMenuTableTrailingConstraint: NSLayoutConstraint?
@IBOutlet weak var tableHeight: NSLayoutConstraint!
var heightOfTableViewConstraint: NSLayoutConstraint!
var cloudKitSwitch: UISwitch!
var reachability: Reachability!
var profileSyncErrorOccured = false
var measValueSyncErrorOccured = false
var measTempSyncErrorOccured = false
var refMeasSyncErrorOccured = false
var pageSyncErrorOccured = false
var noteSyncErrorOccured = false
var photoSyncErrorOccured = false
let downArrow = UIImage(named: "down_arrow")
let upArrow = UIImage(named: "up_arrow")
var isexpanded = false
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
setupHelpBtn()
self.icloudMenuTableView.dataSource = self
self.icloudMenuTableView.delegate = self
customizeTableView()
self.title = NSLocalizedString("iCloud Settings", comment: "title for the Settings Page")
icloudMenuTableView.layer.borderWidth = 1
icloudMenuTableView.layer.borderColor = UIColor.appColor(.pryForegroundStrokeColor).cgColor
if UIDevice.current.userInterfaceIdiom == .pad {
icloudMenuTableView.layer.cornerRadius = 8
}
setupIpadConstraint()
reachability = Reachability()
}
func setupHelpBtn() {
let device = UIDevice.current.userInterfaceIdiom
var customHelpBtn = UIBarButtonItem()
let helpIcon = UIImage(named: "help_icon")
let helpImageView = UIImageView(image: helpIcon)
customHelpBtn = UIBarButtonItem(customView: helpImageView)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.helpBtnTapped))
let helpImageViewContainer = UIView(frame: CGRect(x: 0, y: 0, width: device == .pad ? 40 : 36, height: device == .pad ? 40 : 36))
helpImageView.contentMode = .scaleAspectFit
helpImageView.isUserInteractionEnabled = true
helpImageView.addGestureRecognizer(tapGestureRecognizer)
helpImageViewContainer.addSubview(helpImageView)
customHelpBtn = UIBarButtonItem(customView: helpImageView)
self.navigationItem.rightBarButtonItems = [customHelpBtn]
}
@objc
func helpBtnTapped() {
navigationController?.pushViewController(ICloudHelpViewController(), animated: true)
}
override func viewWillLayoutSubviews() {
super.updateViewConstraints()
UIView.animate(withDuration: 0) {
self.icloudMenuTableView.layoutIfNeeded()
} completion: { [self] (complete) in
var heightOfTableView: CGFloat = 0.0
// Get visible cells and sum up their heights
let cells = self.icloudMenuTableView.visibleCells
for cell in cells {
heightOfTableView += cell.frame.height
}
// Edit heightOfTableViewConstraint's constant to update height of table view
tableHeight.constant = heightOfTableView
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
closeExpandedView()
self.icloudMenuTableView.reloadData()
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
icloudMenuTableView.layer.borderColor = UIColor.appColor(.pryForegroundStrokeColor).cgColor
self.view.setNeedsDisplay()
}
func setupIpadConstraint() {
if UIDevice.current.userInterfaceIdiom == .pad {
if Orientation.isPortrait {
icloudMenuTableLeadingConstraint?.constant = 8
icloudMenuTableTrailingConstraint?.constant = 8
} else {
icloudMenuTableLeadingConstraint?.constant = 70
icloudMenuTableTrailingConstraint?.constant = 70
}
}
}
func customizeTableView() {
heightOfTableViewConstraint = NSLayoutConstraint(item: icloudMenuTableView ?? UITableView(), attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: 0.0, constant: 1000)
view.addConstraint(heightOfTableViewConstraint)
self.icloudMenuTableView.layer.borderColor = UIColor.appColor(.pryForegroundStrokeColor).cgColor
icloudMenuTableView.backgroundColor = UIColor.appColor(.appBg)
icloudMenuTableView.contentInset = UIEdgeInsets(top: 0, left: 0, bottom: -29, right: 0)
}
func closeExpandedView() {
DispatchQueue.main.async {
if self.isexpanded == true {
self.isexpanded = false
if let cell = self.icloudMenuTableView.visibleCells[1] as? iCloudStorage {
cell.icloudStorageDetails.isHidden = true
}
}
}
}
@objc
func cloudKitSwitchPressed(_ sender: UISwitch) {
let switchOn = sender.isOn
if self.reachability.connection != .none {
print("create cloudkit network \(CheckUpdate.netwkrOn)")
CheckUpdate.shared.showUpdate(withConfirmation: true) { ntwOn in
switch ntwOn {
case true:
if switchOn {
// close up storage details if it is open.
self.closeExpandedView()
self.checkForOngoingOperation()
DispatchQueue.main.async(execute: {
self.defaults.set(self.cloudKitSwitch.isOn, forKey: "cloudkitSwitchKey")
// self.icloudMenuTableView.reloadData()
})
CKContainer(identifier: "iCloud.aeeiee.dressmeasurement").accountStatus(completionHandler: { (accountStatus, _) in
if accountStatus == .noAccount {
DispatchQueue.main.async(execute: {
self.cloudKitSwitch.setOn(false, animated: false)
let alert = UIAlertController(title: DressMeasurementCloudKit.cloudKitMessages.failTitle, message: DressMeasurementCloudKit.cloudKitMessages.failMessage, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: DressMeasurementCloudKit.cloudKitMessages.ok, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
})
} else {
DispatchQueue.main.async(execute: {
self.defaults.set(self.cloudKitSwitch.isOn, forKey: "cloudkitSwitchKey")
self.icloudMenuTableView.reloadData()
})
if !CloudIcon.shared.pulseActive {
DressMeasurementCloudKit.shared.synced = false
DispatchQueue.main.async(execute: {
self.icloudMenuTableView.reloadData()
})
DressMeasurementCloudKit.shared.createZone()
let insert = CKInsert(complexInstruction: CKInsert.CloudInstruction.complex(.cloudSync), creationDate: Date()) {
DispatchQueue.main.async(execute: {
globalProgressorView.removeFromSuperview()
DressMeasurementCloudKit.shared.synced = true
syncInProgress = false
UserDefaults.standard.set("none", forKey: "ongoingOperation")
self.icloudMenuTableView.reloadData()
self.navigationController?.popViewController(animated: true)
self.showOperationCompletionAlert(title: nil, message: NSLocalizedString("iCloud Sync is complete!", comment: ""))
})
}
DressMeasurementCloudKit.shared.cloudQueue.enqueue(insert)
}
}
})
} else {
//turned off
DispatchQueue.main.async(execute: {
if CloudIcon.shared.pulseActive {
self.cloudKitSwitch.setOn(true, animated: false)
let alert = UIAlertController(title: nil, message: DressMeasurementCloudKit.cloudKitMessages.patience, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else {
self.defaults.set(self.cloudKitSwitch.isOn, forKey: "cloudkitSwitchKey")
globalProgressorView.removeFromSuperview()
self.icloudMenuTableView.reloadData()
}
})
}
case false:
DispatchQueue.main.async(execute: {
sender.setOn(false, animated: false)
})
}
}
} else {
DispatchQueue.main.async(execute: {
sender.setOn(!self.cloudKitSwitch.isOn, animated: false)
let alert = UIAlertController(title: nil, message: DressMeasurementCloudKit.cloudKitMessages.noInternet, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: DressMeasurementCloudKit.cloudKitMessages.ok, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
})
}
}
}
extension ICloudSubMenuVC: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return .leastNormalMagnitude
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 6
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.row == 0 {
if self.cloudKitSwitch.isOn && !DressMeasurementCloudKit.shared.synced {
return 206
} else {
return 56
}
} else if indexPath.row == 1 {
if self.isexpanded == true {
return 338
} else {
return 56
}
} else {
return 56
}
}
func numberOfSections(in tableView: UITableView) -> Int {
1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.row == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "iCloudCell") as? iCloudCell ?? iCloudCell()
//set the data here
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
self.cloudKitSwitch = cell.cloudKitSwitch
self.cloudKitSwitch.addTarget(self, action: #selector(cloudKitSwitchPressed(_:)), for: .valueChanged)
if defaults.bool(forKey: "cloudkitSwitchKey") {
cell.cloudKitSwitch.isOn = true
} else {
cell.cloudKitSwitch.isOn = false
}
cell.setProgressView()
return cell
} else if indexPath.row == 1 {
let cell = tableView.dequeueReusableCell(withIdentifier: "iCloudStorage")as? iCloudStorage ?? iCloudStorage()
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
cell.callback = {[weak self] in
guard let `self` = self else {
return
}
DressMeasurementCloudKit.shared.resetCloudAndLocalDataCount()
self.checkForOngoingOperation()
guard self.checkCurrentOperationValue() == "none" else { return }
if self.isexpanded {
cell.toggleimage.isHidden = false
cell.toggleimage.image = self.downArrow
cell.icloudStorageDetails.isHidden = true
self.isexpanded = !(self.isexpanded)
tableView.beginUpdates()
tableView.endUpdates()
} else {
self.checkAppleIdSignin()
DispatchQueue.main.async {
cell.toggleimage.isHidden = true
cell.activityIndicator.startAnimating()
}
DispatchQueue.global(qos: .userInitiated).async { [self] in
let semaphore: DispatchSemaphore = DispatchSemaphore(value: 0)
self.getDataCount {
print("Fetch user information completed.")
semaphore.signal()
}
semaphore.wait()
DispatchQueue.main.asyncAfter(deadline: .now()) { [self] in
cell.activityIndicator.stopAnimating()
cell.toggleimage.isHidden = false
self.updateDataCount(cell: cell)
self.updateAutosyncLabel(cell: cell)
self.indicateErrorLabels(cell: cell)
cell.getLastSyncDate()
cell.toggleimage.image = self.upArrow
cell.icloudStorageDetails.isHidden = false
self.isexpanded = true
tableView.beginUpdates()
tableView.endUpdates()
}
}
}
}
//set the data here
return cell
} else if indexPath.row == 2 {
let cell = tableView.dequeueReusableCell(withIdentifier: "iCloudPullCell") as? iCloudPullCell ?? iCloudPullCell()
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
return cell
} else if indexPath.row == 3 {
let cell: iCloudPushCell = tableView.dequeueReusableCell(withIdentifier: "iCloudPushCell", for: indexPath) as? iCloudPushCell ?? iCloudPushCell()
//set the data here
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
return cell
} else if indexPath.row == 4 {
let cell = tableView.dequeueReusableCell(withIdentifier: "iCloudSave", for: indexPath) as? iCloudSave ?? iCloudSave()
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: "iCloudRestore", for: indexPath) as? iCloudRestore ?? iCloudRestore()
cell.backgroundColor = UIColor.appColor(.pryForegroundColor)
return cell
}
}
func checkCurrentOperationValue() -> String {
return UserDefaults.standard.value(forKey: "ongoingOperation") as? String ?? "none"
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let backupExist = Database.shared.isBackupExist()
switch indexPath.row {
case 2:
print("cell at indexPath \(indexPath.row) is selected")
// pull from iCloud
pullFromIcloud()
case 3:
print("cell at indexPath \(indexPath.row) is selected")
// push to iCloud
pushToIcloud()
case 4:
// local snapshot save
checkForOngoingOperation()
guard checkCurrentOperationValue() == "none" else { return }
let viewController = LocalSnapshotViewController()
viewController.snapShot = Snapshot(dataAvailable: Database.shared.isProfileExist(), lastSnapshotDate: backupExist ? (UserDefaults.standard.string(forKey: "backupDate") ?? "") : "", fileSize: backupExist ? (Database.shared.fileSize() ?? "") : "0")
viewController.snapshotTask = .save
viewController.detailViewOperation = .snapshotOperation
viewController.icloudTask = .saveLocalSnapshot
let snapShotDetailMessage = viewController.snapShot.dataAvailable == false ? CloudUpdateStrings.noBackupData : CloudUpdateStrings.newDataForBackup
viewController.localSnapshotActionDetail = TaskDetail(image: "disk_save", message: snapShotDetailMessage)
viewController.backupOperationProgressDetail = TaskDetail(image: "disk_save", message: CloudUpdateStrings.viewStats)
navigationController?.pushViewController(viewController, animated: true)
case 5:
// Restore local snapshot
checkForOngoingOperation()
guard checkCurrentOperationValue() == "none" else { return }
let viewController = LocalSnapshotViewController()
viewController.snapShot = Snapshot(dataAvailable: Database.shared.isBackupExist(), lastSnapshotDate: backupExist ? (UserDefaults.standard.string(forKey: "backupDate") ?? "") : "", fileSize: backupExist ? (Database.shared.fileSize() ?? "") : "0")
viewController.snapshotTask = .restore
viewController.detailViewOperation = .snapshotOperation
viewController.icloudTask = .restoreLocalSnapshot
let snapShotDetailMessage = viewController.snapShot.dataAvailable == false ? CloudUpdateStrings.noRestoreData : CloudUpdateStrings.restoreDataAvailable
viewController.localSnapshotActionDetail = TaskDetail(image: "restore", message: snapShotDetailMessage)
viewController.backupOperationProgressDetail = TaskDetail(image: "restore", message: CloudUpdateStrings.viewStats)
navigationController?.pushViewController(viewController, animated: true)
default:
print("cell at indexPath \(indexPath.row) is selected")
self.icloudMenuTableView.reloadData()
}
self.icloudMenuTableView.reloadData()
}
private func pullFromIcloud() {
checkForOngoingOperation()
checkNetworkBeforeOperation(operation: "pullFromIcloud")
guard checkCurrentOperationValue() == "none" else { return }
showAlert(alertType: .pullFromCloud) { [self] ok in
guard ok else { return }
let viewController = CloudActionViewController()
progressorTask = .pullFromCloud
viewController.icloudTask = .pullFromCloud
viewController.detailViewOperation = .cloudOperation
viewController.cloudActionDetail = TaskDetail(image: "icloud_pull", message: CloudUpdateStrings.replaceDataWithCloud)
navigationController?.pushViewController(viewController, animated: true)
}
}
private func pushToIcloud() {
checkForOngoingOperation()
checkNetworkBeforeOperation(operation: "pushToIcloud")
guard checkCurrentOperationValue() == "none" else { return }
showAlert(alertType: .pushToCloud) { [self] ok in
guard ok else { return }
let viewController = CloudActionViewController()
viewController.icloudTask = .pushToCloud
viewController.detailViewOperation = .cloudOperation
viewController.cloudActionDetail = TaskDetail(image: "icloud_push", message: CloudUpdateStrings.replaceDataWithLocal)
navigationController?.pushViewController(viewController, animated: true)
}
}
private func showAlert(alertType: SensitiveAction, callback: @escaping (Bool) -> Void) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let rootvC = appDelegate.window?.rootViewController {
AlertSensitiveActionViewController.show(sender: rootvC, sensitiveActionType: alertType, okAction: callback)
}
}
}
}
extension ICloudSubMenuVC {
func getDataCount(completion: @escaping () -> Void) {
let operations = OperationQueue()
let operation1 = BlockOperation {
Database.shared.getAllDatabaseDataCount()
}
let operation2 = BlockOperation {
DressMeasurementCloudKit.shared.getAllCloudDataCount {
self.compareCloudAndDatabaseDataCount {
completion()
}
}
}
operation2.addDependency(operation1)
operations.addOperation(operation1)
operations.addOperation(operation2)
}
func compareCloudAndDatabaseDataCount(completion: @escaping () -> Void) {
profileSyncErrorOccured = DressMeasurementCloudKit.shared.profileCountFromCloud != Database.shared.profileCountFromDB
measValueSyncErrorOccured = DressMeasurementCloudKit.shared.measurementValueCountFromCloud != Database.shared.measurementValueCountFromDB
measTempSyncErrorOccured = DressMeasurementCloudKit.shared.measTempCountFromCloud != Database.shared.measTempCountFromDB
refMeasSyncErrorOccured = DressMeasurementCloudKit.shared.refMeasCountFromCloud != Database.shared.refMeasCountFromDB
noteSyncErrorOccured = DressMeasurementCloudKit.shared.notesCountFromCloud != Database.shared.notesCountFromDB
photoSyncErrorOccured = DressMeasurementCloudKit.shared.photoCountFromCloud != Database.shared.photoCountFromDB
pageSyncErrorOccured = DressMeasurementCloudKit.shared.pageCountFromCloud != Database.shared.pageCountFromDB
let errorArray = [
profileSyncErrorOccured,
measValueSyncErrorOccured,
measTempSyncErrorOccured,
refMeasSyncErrorOccured,
noteSyncErrorOccured,
photoSyncErrorOccured,
pageSyncErrorOccured
]
if errorArray.contains(true) {
UserDefaults.standard.set(true, forKey: "syncErrorOccured")
completion()
} else {
UserDefaults.standard.set(false, forKey: "syncErrorOccured")
completion()
}
}
private func updateDataCount(cell: iCloudStorage) {
cell.iCloudStorageLabel.text = StringConstants.iCloudStorage
cell.profiles.text = "\(DressMeasurementCloudKit.shared.profileCountFromCloud)"
cell.measurements.text = "\(DressMeasurementCloudKit.shared.measurementValueCountFromCloud)"
cell.notes.text = "\(DressMeasurementCloudKit.shared.notesCountFromCloud)"
cell.pictures.text = "\(DressMeasurementCloudKit.shared.photoCountFromCloud)"
cell.customPages.text = "\(DressMeasurementCloudKit.shared.pageCountFromCloud)"
cell.customMeasurements.text = "\(DressMeasurementCloudKit.shared.measTempCountFromCloud)"
cell.customReference.text = "\(DressMeasurementCloudKit.shared.refMeasCountFromCloud)"
// local
cell.localProfilesLabel.text = "\(Database.shared.profileCountFromDB)"
cell.localMeasurementsLabel.text = "\(Database.shared.measurementValueCountFromDB)"
cell.localNotesLabel.text = "\(Database.shared.notesCountFromDB)"
cell.localPicturesLabel.text = "\(Database.shared.photoCountFromDB)"
cell.localCustomPagesLabel.text = "\(Database.shared.pageCountFromDB)"
cell.localCustomMeasurementsLabel.text = "\(Database.shared.measTempCountFromDB)"
cell.localCustomReferenceLabel.text = "\(Database.shared.refMeasCountFromDB)"
}
private func updateAutosyncLabel(cell: iCloudStorage) {
if UserDefaults.standard.bool(forKey: "syncErrorOccured") == true {
cell.autoSync.text = StringConstants.error
cell.autoSync.textColor = .red
self.indicateErrorLabels(cell: cell)
showOperationErrorAlert(title: NSLocalizedString("Oops!", comment: ""), message: NSLocalizedString("There is a conflict between your data on iCloud and the data on your device. They don't seem to match.", comment: ""), actionTitle: NSLocalizedString("Learn More", comment: "")) { _ in
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let topViewController = appDelegate.window?.topViewController() {
if topViewController is ICloudHelpViewController {
// do nothing because we are on help screen already.
} else {
// navigate to help screen
topViewController.navigationController?.pushViewController(ICloudHelpViewController(), animated: true)
}
}
}
}
} else if defaults.bool(forKey: "cloudkitSwitchKey") {
cell.autoSync.text = StringConstants.on
cell.autoSync.textColor = .green
} else {
cell.autoSync.text = StringConstants.off
cell.autoSync.textColor = .gray
}
}
private func indicateErrorLabels(cell: iCloudStorage) {
if profileSyncErrorOccured {
cell.profiles.textColor = .red
cell.localProfilesLabel.textColor = .red
} else {
cell.profiles.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localProfilesLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if measValueSyncErrorOccured {
cell.measurements.textColor = .red
cell.localMeasurementsLabel.textColor = .red
} else {
cell.measurements.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localMeasurementsLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if pageSyncErrorOccured {
cell.customPages.textColor = .red
cell.localCustomPagesLabel.textColor = .red
} else {
cell.customPages.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localCustomPagesLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if measTempSyncErrorOccured {
cell.customMeasurements.textColor = .red
cell.localCustomMeasurementsLabel.textColor = .red
} else {
cell.customMeasurements.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localCustomMeasurementsLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if refMeasSyncErrorOccured {
cell.customReference.textColor = .red
cell.localCustomReferenceLabel.textColor = .red
} else {
cell.customReference.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localCustomReferenceLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if noteSyncErrorOccured {
cell.notes.textColor = .red
cell.localNotesLabel.textColor = .red
} else {
cell.notes.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localNotesLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
if photoSyncErrorOccured {
cell.pictures.textColor = .red
cell.localPicturesLabel.textColor = .red
} else {
cell.pictures.textColor = UIColor.measLineColor(.creamModelMeasurementColor)
cell.localPicturesLabel.textColor = UIColor.textColor(.descriptionTextColor)
}
}
}
extension ICloudSubMenuVC {
func checkForOngoingOperation() {
let currentOperation = UserDefaults.standard.value(forKey: "ongoingOperation") as? String
guard currentOperation != "none" else { return }
var messageToShow = ""
switch currentOperation {
case "syncing":
messageToShow = "\(CloudUpdateStrings.syncingInProgress) \(CloudUpdateStrings.waitForProcess)"
case "pushToCloud":
messageToShow = "\(CloudUpdateStrings.pushingInProgress) \(CloudUpdateStrings.waitForProcess)"
case "pullFromCloud":
messageToShow = "\(CloudUpdateStrings.pullingInProgress) \(CloudUpdateStrings.waitForProcess)"
case "saveLocalSnashot":
messageToShow = "\(CloudUpdateStrings.savingInProgress) \(CloudUpdateStrings.waitForProcess)"
case "restoreLocalSnapshot":
messageToShow = "\(CloudUpdateStrings.restoringInProgress) \(CloudUpdateStrings.waitForProcess)"
default:
messageToShow = ""
}
self.showAlert(message: messageToShow, buttonText: EditCustomMeasurementStrings.okay, callback: { (ok) in
guard ok else { return }
return
})
}
func showAlert(message: String, buttonText: String, callback: @escaping (Bool) -> Void) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let rootvC = appDelegate.window?.rootViewController {
SingleButtonAlertVC.show(sender: rootvC, message: message, buttonText: buttonText, okAction: callback)
}
}
}
func showOperationCompletionAlert(title: String?, message: String?) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let rootVC = appDelegate.window?.rootViewController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
rootVC.present(alert, animated: true, completion: nil)
}
}
}
func showOperationErrorAlert(title: String?, message: String?, actionTitle: String?, handler: ((UIAlertAction) -> Void)?) {
if let appDelegate = UIApplication.shared.delegate as? AppDelegate {
if let rootvC = appDelegate.window?.rootViewController {
let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: StringConstants.cancel, style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: actionTitle, style: .default, handler: handler))
rootvC.present(alert, animated: true, completion: nil)
}
}
}
func checkNetworkBeforeOperation(operation: String) {
if self.reachability.connection == .none {
switch operation {
case "pullFromIcloud":
showOperationErrorAlert(title: NSLocalizedString("Something’s wrong", comment: ""), message: NSLocalizedString("Pull from iCloud was not successful. Check your internet and try again. ", comment: ""), actionTitle: NSLocalizedString("Try Again", comment: "")) { [weak self] _ in
self?.pullFromIcloud()
}
case "pushToIcloud":
showOperationErrorAlert(title: NSLocalizedString("Something’s wrong", comment: ""), message: NSLocalizedString("Push to iCloud was not successful. Check your internet and try again.", comment: ""), actionTitle: NSLocalizedString("Try Again", comment: "")) { [weak self] _ in
self?.pushToIcloud()
}
default:
print("nothing to do")
}
return
} else {
checkAppleIdSignin()
return
}
}
func checkAppleIdSignin() {
// CKContainer(identifier: "iCloud.aeeiee.dressmeasurement").accountStatus { [weak self] (accountStatus, _) in
// if accountStatus == .noAccount {
// DispatchQueue.main.async {
// self?.showOperationCompletionAlert(title: NSLocalizedString("Not Signed In", comment: ""), message: NSLocalizedString("Please sign in with your Apple ID to perfom this action.", comment: ""))
// return
// }
// }
// }
}
}
struct icloudTableArrowData {
var isexpanded: Bool
var index: Int
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment