// // FirmwareUpdateVC.swift // Twear // // Created by yangbin on 2021/12/25. // import UIKit import Alamofire import HandyJSON import SSZipArchive import MBProgressHUD class FirmwareUpdateVC: UIViewController, XMLParserDelegate { @IBOutlet weak var updateBtn: UIButton! @IBOutlet weak var updateImageView: UIImageView! @IBOutlet weak var deviceImageView: UIImageView! @IBOutlet weak var updateLabel: UILabel! @IBOutlet weak var progressLabel: UILabel! @IBOutlet weak var versionLabel: UILabel! var latestVersion: String = "" var downLoadUrlPath: String = "" var id: String = "" var device = CurDevice var downloadRequest: DownloadRequest? //下载请求对象 override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) UIApplication.shared.isIdleTimerDisabled = false } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) let navController = navigationController as? ZCNavigationController navController?.enableScreenEdgePanGestureRecognizer(true) } override func navigationShouldPop() -> Bool { if !IsDailSyncing { return true } else { MBProgressHUD.showh(LocString("正在升级中,请稍后...")) return false } } override func viewDidLoad() { super.viewDidLoad() title = LocString("固件升级") UIApplication.shared.isIdleTimerDisabled = true Alamofire.SessionManager.default.session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData BluetoothManager.shared.getFirmwareVersion {[weak self] version, type, error in self?.device = CurDevice self?.queryLatestVersion() } } func updateUserInteraction(_ isSyncing: Bool) { // collectionView.isUserInteractionEnabled = !isSyncing IsDailSyncing = isSyncing let navController = navigationController as? ZCNavigationController navController?.enableScreenEdgePanGestureRecognizer(!isSyncing) } func queryLatestVersion() { Alamofire.request("http://hodafone.com.cn/qwear/update/\(device.type)/version.xml").responseData { responseData in if let data = responseData.data { self.parseXML(data) } } } private func checkUpdate() { if device.version.checkVersion(latestVersion) { updateBtn.isUserInteractionEnabled = true updateBtn.backgroundColor = UIColor.rgbColorFromHex(0x00993E) let string = NSMutableAttributedString(string: "\(LocString("发现新版本")):v \(latestVersion)") string.addAttributes([.foregroundColor: UIColor.rgbColorFromHex(0x00993E)], range: NSMakeRange("\(LocString("发现新版本")):".count, string.string.length-"\(LocString("发现新版本")):".count)) versionLabel.attributedText = string } else { updateBtn.isUserInteractionEnabled = false updateBtn.backgroundColor = UIColor.rgbColorFromHex(0xCBCBCB) let str1 = LocString("当前已是最新版本") let string = NSMutableAttributedString(string: "\(str1)\nv \(device.version)") string.addAttributes([.foregroundColor: UIColor.rgbColorFromHex(0x00993E)], range: NSMakeRange(str1.count, string.string.count-str1.count)) versionLabel.attributedText = string } } @IBAction func update(_ sender: UIButton) { print("开始更新") updateBtn.isUserInteractionEnabled = false updateBtn.backgroundColor = UIColor.rgbColorFromHex(0xCBCBCB) deviceImageView.isHidden = true updateLabel.isHidden = false progressLabel.isHidden = false downloadUpdateFile() } func downloadUpdateFile() { // let url = URL(string: "http://hodafone.com.cn/qwear/update/\(id)/\(downLoadUrlPath)") let version = latestVersion var filePath = "" var unzipPath = "" // let dest: DownloadRequest.DownloadFileDestination = { _, _ in // let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] // let fileURL = documentsURL.appendingPathComponent("update/firmware1.bin") //// unzipPath = documentsURL.path//.appendingPathComponent("update").path // return (fileURL, [.removePreviousFile, .createIntermediateDirectories]) // } let destination = DownloadRequest.suggestedDownloadDestination(for: .documentDirectory) let manager = FileManager.default let documentsURL = manager.urls(for: .documentDirectory, in: .userDomainMask)[0] let contentsOfPath = try? manager.contentsOfDirectory(atPath: documentsURL.path) print(contentsOfPath) let dPath = documentsURL.appendingPathComponent(downLoadUrlPath).path if manager.fileExists(atPath: dPath) { try? manager.removeItem(atPath: dPath) // self.showAlert(title: LocString("提示"), message: LocString("升级失败,请重试"), cancelText: nil) // return } // MTB033B_0.1.7.bin Alamofire.download("http://hodafone.com.cn/qwear/update/\(id)/\(downLoadUrlPath)", to: destination).downloadProgress { progress in print("下载进度--\(progress.fractionCompleted)") }.responseData { response in if let data = response.value { print("下载成功") self.syncFile(response.destinationURL!.path, unzipPath: unzipPath) // response.destinationURL } else { self.showAlert(title: LocString("提示"), message: LocString("升级失败,请重试"), cancelText: nil) } } //开始下载 // AF.download(url, interceptor: nil, to: dest).downloadProgress(closure: { (progress) in // // debugPrint("-------下载进度: \(progress.fractionCompleted)") // }).responseData { (res) in // if let data = res.value { // //显示图片 // let image = UIImage(data: data) // self.imgGif.image = image // } // } } func syncFile(_ path: String, unzipPath: String) { let manager = FileManager.default let contentsOfPath = try? manager.contentsOfDirectory(atPath: path) print(contentsOfPath) // path String "/var/mobile/Containers/Data/Application/38F71EF2-43E6-415C-85BF-D7F29FFBC772/Documents/update/firmware.bin" // print(unzipPath) // let attributes = try? manager.attributesOfItem(atPath: path) //结果为Dictionary类型 // print("文件大小:\(attributes![FileAttributeKey.size]!)") // print(NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]) // let success: Bool = SSZipArchive.unzipFile(atPath: path, toDestination: unzipPath) // if !success { // self.showAlert(title: "", message: "升级失败,请重试") // return // } if !manager.fileExists(atPath: path) { self.showAlert(title: LocString("提示"), message: LocString("升级失败,请重试"), cancelText: nil) return } // return updateUserInteraction(true) BluetoothManager.shared.syncFileWith(path: path, isFirmware: true) {[weak self] progress in let n = progress/2 * 2 self?.updateImageView.image = UIImage(named: "update_\(n)") self?.progressLabel.text = "\(progress)%" } completion: {[weak self] error in self?.updateUserInteraction(false) if error == nil { self?.updateLabel.text = LocString("升级完成") self?.updateBtn.setTitle(LocString("升级完成"), for: .normal) self?.updateImageView.image = UIImage(named: "update_100") } else { self?.showAlert(title: LocString("提示"), message: LocString("升级失败,请重试"), cancelText: nil) } } } func parseXML(_ data: Data) { let parser = XMLParser(data: data) parser.delegate = self parser.parse() } func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) { if elementName == "product"{ print(attributeDict) if let least = attributeDict["least"] { latestVersion = least checkUpdate() } if let file = attributeDict["file"] { downLoadUrlPath = file } if let id = attributeDict["id"] { self.id = id } } } deinit { print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!") } } // func compareVersion(nowVersion:String,newVersion:String) -> Bool { // // let nowArray = nowVersion.split(separator: ".") // // let newArray = newVersion.split(separator: ".") // // let big = nowArray.count > newArray.count ? newArray.count : nowArray.count // // for index in 0...big - 1 { // // let first = nowArray[index] // let second = newArray[index] // if Int(first)! < Int(second)! { // return true // } // } // return false // }