一网通办ios
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.

преди 2 години
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. //
  2. // WebView.swift
  3. // im-client-ios
  4. //
  5. // Created by 北京居家科技有限公司 on 2021/12/30.
  6. //
  7. import WebKit
  8. import Alamofire
  9. import SwiftUI
  10. import UserNotifications
  11. var token: String?;
  12. var uploadUrl: String?;
  13. class WebViewUI: UIViewController, WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler,UNUserNotificationCenterDelegate,
  14. UIImagePickerControllerDelegate & UINavigationControllerDelegate {
  15. func getDictionaryFromJSONString(jsonString:String) ->NSDictionary{
  16. let jsonData:Data = jsonString.data(using: .utf8)!
  17. let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .mutableContainers)
  18. if dict != nil {
  19. return dict as! NSDictionary
  20. }
  21. return NSDictionary()
  22. }
  23. func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
  24. //判断消息通道
  25. if(message.name == "photoAlbum"){
  26. print(message.body);
  27. var NSDictionary = getDictionaryFromJSONString(jsonString: message.body as! String);
  28. token = NSDictionary.value(forKey: "token") as! String;
  29. uploadUrl = NSDictionary.value(forKey: "uploadUrl") as! String;
  30. // 相册
  31. openAlbum();
  32. }
  33. if(message.name == "takePhoto"){
  34. // 相机
  35. openCamera();
  36. print(message.body);
  37. }
  38. if(message.name == "scan"){
  39. // 扫一扫
  40. SwiftQRCodeVC();
  41. print(message.body);
  42. }
  43. if(message.name == "fileChoose"){
  44. // UserNotificationManager.instance.sendNotification(title: "何涛", body: "我什么也不知道呀")
  45. // UIApplication.shared.applicationIconBadgeNumber = 1
  46. // openFileSelect();
  47. print("message.body");
  48. print(message.body);
  49. }
  50. if(message.name == "getSysInfo"){
  51. getSysInfo();
  52. }
  53. if(message.name == "sendMessage"){
  54. let NSDictionary = getDictionaryFromJSONString(jsonString: message.body as! String);
  55. let title = NSDictionary.value(forKey: "title") as! String;
  56. let body = NSDictionary.value(forKey: "body") as! String;
  57. UserNotificationManager.instance.sendNotification(title: title, body: body)
  58. UIApplication.shared.applicationIconBadgeNumber = 1
  59. print(message.body);
  60. }
  61. }
  62. // 将进入前台通知
  63. @objc func appWillEnterForeground(){
  64. UIApplication.shared.applicationIconBadgeNumber = 0
  65. print("周期 ---将进入前台通知")
  66. }
  67. //应用程序确实进入了后台
  68. @objc func appDidEnterBackground(){
  69. print("周期 ---应用程序确实进入了后台")
  70. }
  71. var webView:WKWebView!
  72. override func loadView() {
  73. let webConfiguration = WKWebViewConfiguration();
  74. // 创建UserContentController(提供JavaScript向webView发送消息的方法)
  75. let userContent = WKUserContentController()
  76. // 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
  77. userContent.add(self, name: "photoAlbum");
  78. userContent.add(self, name: "takePhoto");
  79. userContent.add(self, name: "fileChoose");
  80. userContent.add(self, name: "sendMessage");
  81. userContent.add(self, name: "getSysInfo");
  82. userContent.add(self, name: "scan");
  83. // userContent.add(Dsbridge());
  84. // 将UserConttentController设置到配置文件
  85. webConfiguration.userContentController = userContent
  86. webView = WKWebView(frame: .zero, configuration: webConfiguration);
  87. // UI代理
  88. webView.uiDelegate = self;
  89. // 是否允许手势左滑返回上一级, 类似导航控制的左滑返回
  90. webView.allowsBackForwardNavigationGestures = true;
  91. view = webView;
  92. UserNotificationManager.instance.requestAuthorization()
  93. }
  94. override func viewDidLoad() {
  95. super.viewDidLoad()
  96. let timestamp = Date().timeIntervalSince1970
  97. let timeStamp3 = CLongLong(round(timestamp*1000))
  98. let myURL = URL(string:"http://www.jujiaservice.com/jjkj/app/?t=" + "\(timeStamp3)")
  99. let myRequest = URLRequest(url: myURL!)
  100. NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
  101. NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
  102. webView.load(myRequest)
  103. }
  104. override func viewWillDisappear(_ animated: Bool) {
  105. super.viewWillDisappear(animated)
  106. //当前ViewController销毁前将其移除,否则会造成内存泄漏
  107. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "photoAlbum") //移除方法
  108. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "takePhoto")
  109. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "fileChoose")
  110. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "sendMessage")
  111. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "scan")
  112. self.webView?.configuration.userContentController.removeScriptMessageHandler(forName: "getSysInfo")
  113. }
  114. override func didReceiveMemoryWarning() {
  115. super.didReceiveMemoryWarning()
  116. }
  117. //选择图片成功后代理
  118. @objc func imagePickerController(_ picker: UIImagePickerController,
  119. didFinishPickingMediaWithInfo info: [String :Any]) {
  120. //获取选择的原图
  121. let image = info[UIImagePickerController.InfoKey.originalImage.rawValue]as! UIImage;
  122. if image != nil {
  123. // // 将图片转化成Data
  124. // let imageData = image.jpegData (compressionQuality: 1.0)
  125. // // 将Data转化成 base64的字符串
  126. // let imageBase64String = imageData?.base64EncodedString()
  127. // print(image)
  128. // let s: String = "json.rawString()!";
  129. // self.webView.evaluateJavaScript("taskPathCallBack('" + imageBase64String! + "')") {(data, error) in
  130. //
  131. // }
  132. uploadFile(pickedImage: image);
  133. }
  134. // imageView.image = image
  135. //图片控制器退出
  136. picker.dismiss(animated: true, completion: {
  137. () -> Void in
  138. })
  139. }
  140. func toolsChangeToJson(info: Any) -> String{
  141. //首先判断能不能转换
  142. guard JSONSerialization.isValidJSONObject(info) else {
  143. return ""
  144. }
  145. //如果设置options为JSONSerialization.WritingOptions.prettyPrinted,则打印格式更好阅读
  146. let jsonData = try? JSONSerialization.data(withJSONObject: info, options: [])
  147. if let jsonData = jsonData {
  148. let str = String(data: jsonData, encoding: String.Encoding.utf8)
  149. return str ?? ""
  150. }else {
  151. return ""
  152. }
  153. }
  154. func uploadFile(pickedImage: UIImage) {
  155. var httpHeaders = HTTPHeaders.init();
  156. httpHeaders.add(name: "Auth-Token", value: token ?? "");
  157. let AF = Session.init();
  158. AF.upload(multipartFormData: { (data) in
  159. data.append(pickedImage.jpegData(compressionQuality: 0.6)!, withName: "file",fileName: "\(Date().timeIntervalSince1970).jpg",mimeType: "image/jpeg")
  160. }, to: "http://39.98.219.177:8787"+(uploadUrl ?? ""), headers: httpHeaders)
  161. .responseJSON { response in
  162. // debugPrint(response)
  163. switch response.result {
  164. case let .success(json) :
  165. print(json)
  166. self.webView.evaluateJavaScript("taskPathCallBack('" + self.toolsChangeToJson(info: json) + "')") {(data, error) in
  167. }
  168. fallthrough
  169. default :
  170. print("失败");
  171. }
  172. // print(response.result);
  173. // getJSONStringFromDictionary(dictionary: response.data);
  174. }
  175. }
  176. // 相册相机都要移除到一个新的类里面去-暂时全部写到这里
  177. //打开相册
  178. func openAlbum(){
  179. //判断设置是否支持图片库
  180. if (UIImagePickerController.isSourceTypeAvailable(.photoLibrary)){
  181. //初始化图片控制器
  182. let picker = UIImagePickerController()
  183. //设置代理
  184. picker.delegate = self
  185. //指定图片控制器类型
  186. picker.sourceType = UIImagePickerController.SourceType .photoLibrary
  187. //设置是否允许编辑
  188. // picker.allowsEditing = editSwitch.on
  189. //弹出控制器,显示界面
  190. self.present(picker, animated:true, completion: {
  191. () -> Void in
  192. })
  193. } else {
  194. print("读取相册错误")
  195. }
  196. }
  197. // 打开相机
  198. func openCamera(){
  199. if(UIImagePickerController.isSourceTypeAvailable(.camera)){
  200. //创建图片控制器
  201. let picker = UIImagePickerController()
  202. //设置代理
  203. picker.delegate = self
  204. //设置来源
  205. picker.sourceType = UIImagePickerController.SourceType.camera
  206. //允许编辑
  207. picker.allowsEditing = true
  208. //打开相机
  209. self.present(picker, animated:true, completion: { () -> Void in
  210. })
  211. } else {
  212. debugPrint("找不到相机")
  213. }
  214. }
  215. // 打开文件选择器
  216. func openFileSelect() {
  217. // let importMenu = UIDocumentMenuViewController(documentTypes: [String(kUTTypePDF)], in: .import)
  218. // importMenu.delegate = self
  219. // importMenu.modalPresentationStyle = .formSheet
  220. // self.present(importMenu, animated: true, completion: nil)
  221. }
  222. func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
  223. let options:UNAuthorizationOptions = [.alert, .sound]
  224. UNUserNotificationCenter.current().requestAuthorization(options: options) { (success, error) in
  225. if let info = error?.localizedDescription {
  226. print(info)
  227. }
  228. }
  229. return true;
  230. }
  231. ///请求完成后会调用把获取的deviceToken返回给我们
  232. func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
  233. //deviceToken = 32 bytes
  234. print("deviceToken = \(deviceToken)")
  235. let deviceToken = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined();
  236. self.webView.evaluateJavaScript("iosDeviceToken('" + deviceToken + "')") {(data, error) in
  237. }
  238. //FIXME:打印推送64位token
  239. print( deviceToken, "推送 deviceToken" )
  240. }
  241. func getSysInfo() {
  242. let infoDictionary = Bundle .main.infoDictionary!
  243. let appVersion = infoDictionary["CFBundleShortVersionString"] as? String
  244. let appDisplayName = infoDictionary[ "CFBundleDisplayName" ] //程序名称
  245. let iosVersion = UIDevice.current.systemVersion //iOS版本
  246. let identifierNumber = UIDevice.current.identifierForVendor //设备udid
  247. let systemName = UIDevice.current.systemName //设备名称
  248. let model = UIDevice.current.model //设备型号
  249. let localizedModel = UIDevice .current.localizedModel //设备区域化型号如A1533
  250. let screenh = UIScreen.main.applicationFrame.size.height
  251. let screenw = UIScreen.main.applicationFrame.size.width
  252. let m = (versionName: appDisplayName, versionCode: appVersion,is_dev: false, device_key: identifierNumber
  253. ,device_type: "ios", device_model: model, device_sys_version: model
  254. ,device_screen_width: screenw, device_screen_height: screenh);
  255. 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);
  256. let jsonData = try! JSONEncoder().encode(sysInfo)
  257. let jsonString = String(data: jsonData, encoding: .utf8)
  258. // let data = try? JSONSerialization.data(withJSONObject: sysInfo, options: JSONSerialization.WritingOptions.init(rawValue: 0))
  259. // let jsonStr = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
  260. print(jsonString);
  261. self.webView.evaluateJavaScript("getSysInfoCallBack('" + (jsonString ?? "") + "')") {(data, error) in
  262. }
  263. }
  264. }