// // WebView.swift // im-client-ios // // Created by 北京居家科技有限公司 on 2021/12/30. // import WebKit import Alamofire import SwiftUI import UserNotifications var token: String?; var uploadUrl: String?; class WebViewUI: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler,UNUserNotificationCenterDelegate, UIImagePickerControllerDelegate & UINavigationControllerDelegate { func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{ let jsonData:Data = jsonString.data(using: .utf8)! let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers) if dict != nil { return dict as! NSDictionary } return NSDictionary() } func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { //判断消息通道 if(message.name == "photoAlbum"){ print(message.body); var NSDictionary = getDictionaryFromJSONString(jsonString: message.body as! String); token = NSDictionary.value(forKey: "token") as! String; uploadUrl = NSDictionary.value(forKey: "uploadUrl") as! String; // 相册 openAlbum(); } if(message.name == "takePhoto"){ // 相机 openCamera(); print(message.body); } if(message.name == "scan"){ // 扫一扫 SwiftQRCodeVC(); print(message.body); } if(message.name == "fileChoose"){ // UserNotificationManager.instance.sendNotification(title: "何涛", body: "我什么也不知道呀") // UIApplication.shared.applicationIconBadgeNumber = 1 // openFileSelect(); print("message.body"); print(message.body); } if(message.name == "getSysInfo"){ getSysInfo(); } if(message.name == "sendMessage"){ let NSDictionary = getDictionaryFromJSONString(jsonString: message.body as! String); let title = NSDictionary.value(forKey: "title") as! String; let body = NSDictionary.value(forKey: "body") as! String; UserNotificationManager.instance.sendNotification(title: title, body: body) UIApplication.shared.applicationIconBadgeNumber = 1 print(message.body); } } // 将进入前台通知 @objc func appWillEnterForeground(){ UIApplication.shared.applicationIconBadgeNumber = 0 print("周期 ---将进入前台通知") } //应用程序确实进入了后台 @objc func appDidEnterBackground(){ print("周期 ---应用程序确实进入了后台") } var webView:WKWebView! override func loadView() { let webConfiguration = WKWebViewConfiguration(); // 创建UserContentController(提供JavaScript向webView发送消息的方法) let userContent = WKUserContentController() // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除 userContent.add(self, name: "photoAlbum"); userContent.add(self, name: "takePhoto"); userContent.add(self, name: "fileChoose"); userContent.add(self, name: "sendMessage"); userContent.add(self, name: "getSysInfo"); userContent.add(self, name: "scan"); // userContent.add(Dsbridge()); // 将UserConttentController设置到配置文件 webConfiguration.userContentController = userContent webView = WKWebView(frame: .zero, configuration: webConfiguration); // UI代理 webView.uiDelegate = self; // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回 webView.allowsBackForwardNavigationGestures = true; view = webView; UserNotificationManager.instance.requestAuthorization() } override func viewDidLoad() { super.viewDidLoad() let timestamp = Date().timeIntervalSince1970 let timeStamp3 = CLongLong(round(timestamp*1000)) let myURL = URL(string:"http://www.jujiaservice.com/jjkj/app/?t=" + "\(timeStamp3)") let myRequest = URLRequest(url: myURL!) NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil) webView.load(myRequest) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) //当前ViewController销毁前将其移除,否则会造成内存泄漏 self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "photoAlbum") //移除方法 self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "takePhoto") self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "fileChoose") self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "sendMessage") self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "scan") self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "getSysInfo") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } //选择图片成功后代理 @objc func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String :Any]) { //获取选择的原图 let image = info[UIImagePickerController.InfoKey.originalImage.rawValue]as! UIImage; if image != nil { // // 将图片转化成Data // let imageData = image.jpegData (compressionQuality: 1.0) // // 将Data转化成 base64的字符串 // let imageBase64String = imageData?.base64EncodedString() // print(image) // let s: String = "json.rawString()!"; // self.webView.evaluateJavaScript("taskPathCallBack('" + imageBase64String! + "')") {(data, error) in // // } uploadFile(pickedImage: image); } // imageView.image = image //图片控制器退出 picker.dismiss(animated: true, completion: { () -> Void in }) } func toolsChangeToJson(info: Any) -> String{ //首先判断能不能转换 guard JSONSerialization.isValidJSONObject(info) else { return "" } //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读 let jsonData = try? JSONSerialization.data(withJSONObject: info, options: []) if let jsonData = jsonData { let str = String(data: jsonData, encoding: String.Encoding.utf8) return str ?? "" }else { return "" } } func uploadFile(pickedImage: UIImage) { var httpHeaders = HTTPHeaders.init(); httpHeaders.add(name: "Auth-Token", value: token ?? ""); let AF = Session.init(); AF.upload(multipartFormData: { (data) in data.append(pickedImage.jpegData(compressionQuality: 0.6)!, withName: "file",fileName: "\(Date().timeIntervalSince1970).jpg",mimeType: "image/jpeg") }, to: "http://39.98.219.177:8787"+(uploadUrl ?? ""), headers: httpHeaders) .responseJSON { response in // debugPrint(response) switch response.result { case let .success(json) : print(json) self.webView.evaluateJavaScript("taskPathCallBack('" + self.toolsChangeToJson(info: json) + "')") {(data, error) in } fallthrough default : print("失败"); } // print(response.result); // getJSONStringFromDictionary(dictionary: response.data); } } // 相册相机都要移除到一个新的类里面去-暂时全部写到这里 //打开相册 func openAlbum(){ //判断设置是否支持图片库 if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)){ //初始化图片控制器 let picker = UIImagePickerController() //设置代理 picker.delegate = self //指定图片控制器类型 picker.sourceType = UIImagePickerController.SourceType .photoLibrary //设置是否允许编辑 // picker.allowsEditing = editSwitch.on //弹出控制器,显示界面 self.present(picker, animated:true, completion: { () -> Void in }) } else { print("读取相册错误") } } // 打开相机 func openCamera(){ if(UIImagePickerController.isSourceTypeAvailable(.camera)){ //创建图片控制器 let picker = UIImagePickerController() //设置代理 picker.delegate = self //设置来源 picker.sourceType = UIImagePickerController.SourceType.camera //允许编辑 picker.allowsEditing = true //打开相机 self.present(picker, animated:true, completion: { () -> Void in }) } else { debugPrint("找不到相机") } } // 打开文件选择器 func openFileSelect() { // let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import) // importMenu.delegate = self // importMenu.modalPresentationStyle = .formSheet // self.present(importMenu, animated: true, completion: nil) } func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { let options:UNAuthorizationOptions = [.alert, .sound] UNUserNotificationCenter.current().requestAuthorization(options: options) { (success, error) in if let info = error?.localizedDescription { print(info) } } return true; } ///请求完成后会调用把获取的deviceToken返回给我们 func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { //deviceToken = 32 bytes print("deviceToken = \(deviceToken)") let deviceToken = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined(); self.webView.evaluateJavaScript("iosDeviceToken('" + deviceToken + "')") {(data, error) in } //FIXME:打印推送64位token print( deviceToken, "推送 deviceToken" ) } func getSysInfo() { let infoDictionary = Bundle .main.infoDictionary! let appVersion = infoDictionary["CFBundleShortVersionString"] as? String let appDisplayName = infoDictionary[ "CFBundleDisplayName" ] //程序名称 let iosVersion = UIDevice.current.systemVersion //iOS版本 let identifierNumber = UIDevice.current.identifierForVendor //设备udid let systemName = UIDevice.current.systemName //设备名称 let model = UIDevice.current.model //设备型号 let localizedModel = UIDevice .current.localizedModel //设备区域化型号如A1533 let screenh = UIScreen.main.applicationFrame.size.height let screenw = UIScreen.main.applicationFrame.size.width let m = (versionName: appDisplayName, versionCode: appVersion,is_dev: false, device_key: identifierNumber ,device_type: "ios", device_model: model, device_sys_version: model ,device_screen_width: screenw, device_screen_height: screenh); var sysInfo = SysInfo.init(versionName: appDisplayName as! String, versionCode: appVersion ?? "", is_dev: false, device_key: identifierNumber ?? UUID.init(), device_type: "ios", device_model: model, device_sys_version: model, device_screen_width: screenw, device_screen_height: screenh); let jsonData = try! JSONEncoder().encode(sysInfo) let jsonString = String(data: jsonData, encoding: .utf8) // let data = try? JSONSerialization.data(withJSONObject: sysInfo, options: JSONSerialization.WritingOptions.init(rawValue: 0)) // let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) print(jsonString); self.webView.evaluateJavaScript("getSysInfoCallBack('" + (jsonString ?? "") + "')") {(data, error) in } } }