QSLHomeController.swift 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  1. //
  2. // QSLHomeController.swift
  3. // QuickSearchLocation
  4. //
  5. // Created by mac on 2024/4/10.
  6. //
  7. import UIKit
  8. import SwiftyJSON
  9. import MAMapKit
  10. import AMapFoundationKit
  11. import AMapLocationKit
  12. import YYText
  13. class QSLHomeController: QSLBaseController {
  14. lazy var viewModel: QSLHomeViewModel = {
  15. return QSLHomeViewModel()
  16. }()
  17. var personalModel: QSLUserModel = QSLUserModel()
  18. ///判断是不是第一次定位成功
  19. var isFirstLocatScuess : Bool = true
  20. var isFirstRequestLoc : Bool = false
  21. var isEnterSearchFriend : Bool = false
  22. // var friendList: [QSLUserModel] = [QSLUserModel]()
  23. override func viewDidLoad() {
  24. super.viewDidLoad()
  25. checkDialog()
  26. QSLTools.shared.requestShortcutItem()
  27. }
  28. func checkDialog(){
  29. if UserDefaults.standard.string(forKey: "FIRST_ENTER_LOCATION_HOMEPAGE") == nil{
  30. isFirstRequestLoc = true
  31. }
  32. dealWithMap();
  33. QSLTools.shared.isOpen = true
  34. if(QSLTools.shared.urlScheme.count > 0){
  35. if(isFirstRequestLoc){
  36. isEnterSearchFriend = true
  37. }
  38. QSLTools.shared.dealwithScheme(QSLTools.shared.urlScheme)
  39. return
  40. }
  41. //会员而且没有好友才弹出来
  42. if QSLBaseManager.shared.isVip() {
  43. QSLNetwork().request(.friendList(dict: [:])) { response in
  44. let list = response.mapArray(QSLUserModel.self, modelKey: "data>list")
  45. if(list.count == 0){
  46. self.showAddFriendView()
  47. }
  48. } fail: { code, error in
  49. }
  50. }else{
  51. let vc = QSLActivityVipVC()
  52. vc.modalPresentationStyle = .fullScreen
  53. self.navigationController?.pushViewController(vc, animated: false)
  54. vc.dismissHandler = {[weak self] isCancel in
  55. QSLGuideusersToCommentManager.commentShare.manageWhetherTriggerPopUpWindow(.nonMember){[weak self] in
  56. self?.showAddFriendView(hideBtnClosure: {[weak self] in
  57. DispatchQueue.main.async {
  58. self?.checkLocAgain();
  59. }
  60. })
  61. }
  62. }
  63. }
  64. }
  65. func checkLocAgain(){
  66. homeMapLocationM.startUpdatingLocation()
  67. homeMapView.showsUserLocation = true
  68. homeMapView.userTrackingMode = .follow
  69. self.onceLocation()
  70. firstEnterLocationHomepage()
  71. if(QSLBaseManager.shared.isLogin()){
  72. let memberModel = QSLBaseManager.shared.userModel.memberModel
  73. let duration = (memberModel.serverTimestamp - memberModel.endTimestamp)
  74. if(duration > 0 && memberModel.trialed) {
  75. showTrialDialog()
  76. }
  77. }
  78. }
  79. func showTrialDialog(){
  80. if let currentWindow = UIApplication.keyWindow {
  81. QSLTrialTipsAlertView.alert(view: currentWindow, clickBtnClosure: {[weak self] in
  82. QSLJumpManager.shared.pushToVip(type: .shortcut)
  83. },hideBtnClosure: {
  84. })
  85. }
  86. }
  87. override func viewWillAppear(_ animated: Bool) {
  88. super.viewWillAppear(animated)
  89. if(self.isFirstRequestLoc && self.isEnterSearchFriend){
  90. self.isEnterSearchFriend = false
  91. self.checkLocAgain();
  92. }
  93. }
  94. func showAddFriendView(hideBtnClosure: @escaping () -> () = {}){
  95. if let currentWindow = UIApplication.keyWindow {
  96. QSLHomeAddFriendView.alert(view: currentWindow, clickBtnClosure: {[weak self] in
  97. QSLJumpManager.shared.pushToAdd(type: .homealert)
  98. self?.isEnterSearchFriend = true
  99. },hideBtnClosure: {
  100. hideBtnClosure()
  101. })
  102. }
  103. }
  104. func dealWithMap(){
  105. viewModel.initUIData()
  106. setUpMap()
  107. setUpUI()
  108. loadData()
  109. NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: QSLNotification.QSLLogin, object: nil)
  110. NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: QSLNotification.QSLLogout, object: nil)
  111. NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: QSLNotification.QSLRefreshFriend, object: nil)
  112. NotificationCenter.default.addObserver(self, selector: #selector(loadData), name: QSLNotification.QSLRefreshRequest, object: nil)
  113. NotificationCenter.default.addObserver(self, selector: #selector(requestVip), name: QSLNotification.QSLRefreshMember, object: nil)
  114. //处理第一次进入首页定位
  115. if(isFirstRequestLoc){
  116. return
  117. }
  118. firstEnterLocationHomepage()
  119. }
  120. //处理第一次进入首页定位
  121. func firstEnterLocationHomepage() {
  122. guard UserDefaults.standard.string(forKey: "FIRST_ENTER_LOCATION_HOMEPAGE") != nil else {
  123. UserDefaults.standard.set("YES", forKey: "FIRST_ENTER_LOCATION_HOMEPAGE")
  124. UserDefaults.standard.synchronize()
  125. ///第一次进入埋点
  126. QSEventHandle.gravityPush(eventName: QSLGravityConst.location_enter_first_homepage, eventProps: ["id": 03005])
  127. return
  128. }
  129. }
  130. /// 高德地图
  131. lazy var homeMapView = {
  132. let _mapView = MAMapView()
  133. _mapView.delegate = self
  134. _mapView.minZoomLevel = 7;
  135. _mapView.maxZoomLevel = 19;
  136. _mapView.zoomLevel = 17;
  137. _mapView.showsCompass = false
  138. _mapView.showsScale = false
  139. _mapView.isRotateCameraEnabled = false
  140. if(!isFirstRequestLoc){
  141. _mapView.showsUserLocation = true
  142. _mapView.userTrackingMode = .follow
  143. }
  144. // 关闭显示精度圈
  145. let represent = MAUserLocationRepresentation()
  146. represent.showsAccuracyRing = false
  147. _mapView.update(represent)
  148. let tap = UITapGestureRecognizer(target: self, action: #selector(mapTapAction))
  149. _mapView.addGestureRecognizer(tap)
  150. return _mapView
  151. }()
  152. /// 高德地图定位
  153. lazy var homeMapLocationM = {
  154. let _homeMapLocationM = AMapLocationManager()
  155. _homeMapLocationM.delegate = self
  156. _homeMapLocationM.distanceFilter = 100
  157. _homeMapLocationM.locatingWithReGeocode = true
  158. _homeMapLocationM.desiredAccuracy = kCLLocationAccuracyHundredMeters
  159. _homeMapLocationM.locationTimeout = 2
  160. _homeMapLocationM.reGeocodeTimeout = 2
  161. _homeMapLocationM.pausesLocationUpdatesAutomatically = false
  162. _homeMapLocationM.allowsBackgroundLocationUpdates = true
  163. return _homeMapLocationM
  164. }()
  165. /// 头部定位权限弹窗
  166. lazy var homeAuthHeaderView = {
  167. let _homeAuthHeaderView = QSLHomeAuthHeaderView()
  168. _homeAuthHeaderView.addRadius(radius: 6)
  169. return _homeAuthHeaderView
  170. }()
  171. @objc func homeFriendBtnAction(){
  172. QSLJumpManager.shared.pushToAdd(type: .homesmall)
  173. }
  174. lazy var homeFriendBtn: UIButton = {
  175. let _homeResortBtn = UIButton(frame: CGRect(x: 0, y: 0, width: 56.rpx, height: 56.rpx))
  176. _homeResortBtn.image(UIImage(named: "home_find_friend"))
  177. _homeResortBtn.addTarget(self, action: #selector(homeFriendBtnAction), for: .touchUpInside)
  178. return _homeResortBtn
  179. }()
  180. /// 定位按钮
  181. lazy var homeLocateBtnView = {
  182. let _homeLocateBtnView = UIView()
  183. _homeLocateBtnView.addRadius(radius: 6)
  184. _homeLocateBtnView.effectViewWithAlpha(alpha: 1, size: CGSize(width: 40, height: 40), style: .light)
  185. return _homeLocateBtnView
  186. }()
  187. lazy var homeLocateBtn = {
  188. let _homeLocateBtn = UIButton(type: .custom)
  189. _homeLocateBtn.image(UIImage(named: "home_btn_locate"))
  190. return _homeLocateBtn
  191. }()
  192. /// 无好友和未登录时的状态
  193. lazy var homeEmptyView: QSLHomeEmptyView = {
  194. let _homeEmptyView = QSLHomeEmptyView()
  195. _homeEmptyView.delegate = self
  196. _homeEmptyView.isHidden = true
  197. return _homeEmptyView
  198. }()
  199. lazy var homeFriendView: QSLHomeFriendView = {
  200. let topHeight = QSLConst.qsl_kStatusBarFrameH
  201. let view = QSLHomeFriendView(frame: CGRect(x: 0, y: QSLConst.qsl_kScreenH - viewModel.friendViewHeight - QSLConst.qsl_kTabbarFrameH, width: QSLConst.qsl_kScreenW, height: QSLConst.qsl_kScreenH - topHeight))
  202. view.scrollTopHeight = topHeight - 40
  203. view.delegate = self
  204. return view
  205. }()
  206. }
  207. // MARK: - 网络请求等
  208. extension QSLHomeController {
  209. @objc func loadData() {
  210. // viewModel.refreshDataSoure(complete: { [unowned self] in
  211. // self.homeFriendView.viewModel = self.viewModel
  212. // let friViewTopY = QSLConst.qsl_kScreenH - viewModel.friendViewHeight - QSLConst.qsl_kTabbarFrameH
  213. // homeFriendView.scrollCenterHeight = friViewTopY
  214. // homeFriendView.snp.updateConstraints { make in
  215. // make.top.equalTo(friViewTopY)
  216. // }
  217. // })
  218. if(!isFirstRequestLoc){
  219. self.onceLocation()
  220. }
  221. if QSLBaseManager.shared.isLogin() {
  222. self.initSocket()
  223. } else {
  224. self.deposeSocket()
  225. }
  226. requestFriendList()
  227. requestVip()
  228. }
  229. // 请求好友列表
  230. @objc func requestFriendList() {
  231. self.homeMapView.removeAnnotations(self.homeMapView.annotations)
  232. viewModel.friendList.removeAll()
  233. viewModel.friendLocationList.removeAll()
  234. viewModel.friendList.append(QSLBaseManager.shared.userModel)
  235. QSLNetwork().request(.friendList(dict: [:])) { response in
  236. let list = response.mapArray(QSLUserModel.self, modelKey: "data>list")
  237. self.viewModel.friendList.append(contentsOf: list)
  238. self.homeFriendView.viewModel = self.viewModel
  239. for model in list {
  240. let pointAnnotation = MAPointAnnotation()
  241. let loc = CLLocationCoordinate2D(latitude: model.location.lat, longitude: model.location.lng)
  242. pointAnnotation.coordinate = loc
  243. if model.remark.count > 0 {
  244. pointAnnotation.title = model.remark
  245. } else {
  246. pointAnnotation.title = model.phone
  247. }
  248. pointAnnotation.subtitle = "300"
  249. let pointModel = QSLMapPointModel()
  250. pointModel.userId = model.userId
  251. pointModel.pointAnnotation = pointAnnotation
  252. self.viewModel.friendLocationList.append(pointModel)
  253. if QSLBaseManager.shared.isVip() && !model.blockedMe {
  254. self.homeMapView.addAnnotation(pointAnnotation)
  255. }
  256. }
  257. } fail: { code, error in
  258. self.homeFriendView.viewModel = self.viewModel
  259. }
  260. }
  261. // 请求vip信息
  262. @objc func requestVip() {
  263. QSLNetwork().request(.userMember(dict: [:])) { response in
  264. let memberModel = response.mapObject(QSLMemberModel.self, modelKey: "data")
  265. QSLBaseManager.shared.userModel.memberModel = memberModel
  266. if memberModel.expired {
  267. QSLBaseManager.shared.saveVipExpiredTime(time: 0)
  268. } else {
  269. QSLBaseManager.shared.saveVipExpiredTime(time: memberModel.endTimestamp)
  270. }
  271. QSLBaseManager.shared.saveUserId(id: memberModel.userId)
  272. QSLTools.shared.requestShortcutItem()
  273. // NotificationCenter.default.post(name: QSLNotification.QSLRefreshMember, object: nil)
  274. } fail: { code, error in
  275. }
  276. }
  277. }
  278. // MARK: - 设置地图相关方法
  279. extension QSLHomeController: MAMapViewDelegate, AMapLocationManagerDelegate {
  280. // 初始化高德地图设置
  281. func setUpMap() {
  282. AMapServices.shared().enableHTTPS = true
  283. AMapLocationManager.updatePrivacyShow(.didShow, privacyInfo: .didContain)
  284. AMapLocationManager.updatePrivacyAgree(.didAgree)
  285. homeMapLocationM.locatingWithReGeocode = true
  286. if(!isFirstRequestLoc){
  287. homeMapLocationM.startUpdatingLocation()
  288. }
  289. }
  290. // 申请地图定位权限
  291. func mapViewRequireLocationAuth(_ locationManager: CLLocationManager!) {
  292. locationManager.requestWhenInUseAuthorization()
  293. }
  294. // 地图触摸事件
  295. @objc func mapTapAction() {
  296. if self.homeFriendView.scrollLocation != .ScrollBottom {
  297. self.homeFriendView.scrollToLocation(type: .ScrollBottom)
  298. }
  299. }
  300. // 获取一次性定位
  301. func onceLocation() {
  302. // 先停止持续定位
  303. self.homeMapLocationM.stopUpdatingLocation()
  304. self.homeMapLocationM.requestLocation(withReGeocode: true) { location, regeocode, error in
  305. if error != nil {
  306. self.personalModel = QSLBaseManager.shared.userModel
  307. // 获取电话和名字
  308. // self.personalModel.phone = QSLBaseManager.shared.userModel.phone
  309. var name = "用户\(QSLBaseManager.shared.userModel.phone.suffix(4))"
  310. if !QSLBaseManager.shared.isLogin() {
  311. name = "自己"
  312. }
  313. name = "自己"
  314. self.personalModel.remark = name
  315. // 地址
  316. self.personalModel.location.addr = "请先开启位置权限"
  317. QSLBaseManager.shared.updateUser(model: self.personalModel)
  318. if self.viewModel.friendList.isEmpty {
  319. self.viewModel.friendList.append(self.personalModel)
  320. } else {
  321. self.viewModel.friendList[0] = self.personalModel
  322. }
  323. self.homeFriendView.viewModel = self.viewModel
  324. self.homeMapLocationM.startUpdatingLocation()
  325. return
  326. }
  327. self.personalModel = QSLBaseManager.shared.userModel
  328. var name = "用户\(QSLBaseManager.shared.userModel.phone.suffix(4))"
  329. if !QSLBaseManager.shared.isLogin() {
  330. name = "自己"
  331. }
  332. name = "自己"
  333. self.personalModel.remark = name
  334. self.personalModel.location.addr = regeocode?.formattedAddress ?? "未知"
  335. self.personalModel.location.timestamp = Int(Date.secondStamp) ?? 0
  336. if let location = location {
  337. // 地图居中
  338. self.homeMapView.setCenter(location.coordinate, animated: true)
  339. self.homeFriendView.scrollLocation = .ScrollCenter
  340. self.personalModel.location.lat = location.coordinate.latitude
  341. self.personalModel.location.lng = location.coordinate.longitude
  342. // 速度
  343. self.personalModel.location.speed = location.speed >= 0 ? location.speed : 0
  344. // 朝向
  345. self.personalModel.location.bearing = location.course >= 0 ? location.course : 0
  346. }
  347. QSLBaseManager.shared.updateUser(model: self.personalModel)
  348. if QSLBaseManager.shared.isLogin() {
  349. let locationData = self.personalModel.location
  350. let addr = locationData.addr
  351. if addr != "请先开启位置权限" {
  352. self.sendSocket()
  353. }
  354. }
  355. if self.viewModel.friendList.isEmpty {
  356. self.viewModel.friendList.append(self.personalModel)
  357. } else {
  358. self.viewModel.friendList[0] = self.personalModel
  359. }
  360. print("location: \(String(describing: location))")
  361. if let regeocode = regeocode {
  362. print("reGeocode: \(regeocode)")
  363. }
  364. self.homeFriendView.viewModel = self.viewModel
  365. self.homeMapLocationM.startUpdatingLocation()
  366. }
  367. }
  368. // 持续定位
  369. func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!, reGeocode: AMapLocationReGeocode!) {
  370. if self.isFirstLocatScuess {
  371. self.isFirstLocatScuess = false
  372. //始终允许定位成功
  373. QSEventHandle.gravityPush(eventName: QSLGravityConst.location_success_always, eventProps: ["id": 03003])
  374. }
  375. // 获取电话和名字
  376. self.personalModel = QSLBaseManager.shared.userModel
  377. var name = "用户\(QSLBaseManager.shared.userModel.phone.suffix(4))"
  378. if !QSLBaseManager.shared.isLogin() {
  379. name = "自己"
  380. }
  381. name = "自己"
  382. self.personalModel.remark = name
  383. // 时间戳
  384. self.personalModel.location.timestamp = Int(Date.secondStamp) ?? 0
  385. // 经纬度
  386. self.personalModel.location.lat = location.coordinate.latitude
  387. self.personalModel.location.lng = location.coordinate.longitude
  388. // 速度
  389. if location.speed >= 0 {
  390. self.personalModel.location.speed = location.speed
  391. } else {
  392. self.personalModel.location.speed = 0
  393. }
  394. // 朝向
  395. if location.course >= 0 {
  396. self.personalModel.location.bearing = location.course
  397. } else {
  398. self.personalModel.location.bearing = 0
  399. }
  400. // 打印位置信息
  401. print("location: {lat: \(location.coordinate.latitude); lon: \(location.coordinate.longitude); accuracy: \(location.horizontalAccuracy)}")
  402. // 逆地理编码处理
  403. if let reGeocode = reGeocode {
  404. print("reGeocode: \(reGeocode)")
  405. self.personalModel.location.addr = reGeocode.formattedAddress
  406. } else {
  407. self.personalModel.location.addr = "请先开启位置权限"
  408. }
  409. // 保存到模块
  410. QSLBaseManager.shared.updateUser(model: self.personalModel)
  411. // 更新好友列表
  412. if self.viewModel.friendList.isEmpty {
  413. self.viewModel.friendList.append(self.personalModel)
  414. } else {
  415. self.viewModel.friendList[0] = self.personalModel
  416. }
  417. self.homeFriendView.viewModel = self.viewModel
  418. // 更新UI
  419. // self.updateHomeUI()
  420. // 如果已登录,发送定位信息
  421. if QSLBaseManager.shared.isLogin() {
  422. let locationData = self.personalModel.location
  423. let addr = locationData.addr
  424. if addr != "请先开启位置权限" {
  425. self.sendSocket()
  426. }
  427. }
  428. }
  429. func mapView(_ mapView: MAMapView!, viewFor annotation: (any MAAnnotation)!) -> MAAnnotationView! {
  430. // 处理用户位置的标注
  431. if annotation is MAUserLocation {
  432. let reuseIdentifier = "UserAnotation"
  433. var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? QSLHomeAnnotatinView
  434. if annotationView == nil {
  435. annotationView = QSLHomeAnnotatinView(annotation: annotation, reuseIdentifier: reuseIdentifier)
  436. }
  437. let name = "我"
  438. annotationView?.title = name
  439. annotationView?.isEnabled = false
  440. annotationView?.image = UIImage(named: "home_mine_anno")
  441. annotationView?.canShowCallout = false
  442. annotationView?.centerOffset = CGPoint(x: 0, y: -18)
  443. annotationView?.calloutOffset = CGPoint(x: 0, y: 0)
  444. annotationView?.zIndex = 360
  445. annotationView?.isSelected = true
  446. return annotationView
  447. }
  448. // 处理普通点标注
  449. if annotation is MAPointAnnotation {
  450. let reuseIdentifier = "OtherAnnotation"
  451. var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) as? QSLHomeAnnotatinView
  452. if annotationView == nil {
  453. annotationView = QSLHomeAnnotatinView(annotation: annotation, reuseIdentifier: reuseIdentifier)
  454. annotationView?.title = annotation.title
  455. }
  456. if let subtitle = annotation.subtitle as? Int {
  457. annotationView?.zIndex = subtitle
  458. }
  459. annotationView?.isEnabled = false
  460. annotationView?.image = UIImage(named: "home_mine_anno")
  461. annotationView?.canShowCallout = false
  462. annotationView?.centerOffset = CGPoint(x: 0, y: -18)
  463. annotationView?.calloutOffset = CGPoint(x: 0, y: 0)
  464. annotationView?.isSelected = true
  465. return annotationView
  466. }
  467. return nil
  468. }
  469. //@brief 定位权限状态改变时回调函数。注意:iOS13及之前版本回调
  470. // 高德地图权限变化回调
  471. func amapLocationManager(_ manager: AMapLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
  472. //print("高德地图定位权限变化: \(status.rawValue)")
  473. switch status {
  474. case .authorizedAlways, .authorizedWhenInUse:
  475. //print("定位权限已授权")
  476. //支付成功埋点
  477. QSEventHandle.gravityPush(eventName: QSLGravityConst.location_allow_permission, eventProps: ["id": 03001])
  478. case .denied:
  479. //print("定位权限被拒绝")
  480. //拒绝定位权限
  481. QSEventHandle.gravityPush(eventName: QSLGravityConst.location_allow_permission, eventProps: ["id": 03002])
  482. default:
  483. break
  484. }
  485. }
  486. // 系统定位权限变化回调
  487. func amapLocationManager(_ manager: AMapLocationManager, locationManagerDidChangeAuthorization locationManager: CLLocationManager) {
  488. if #available(iOS 14.0, *) {
  489. let status = locationManager.authorizationStatus
  490. // 统一处理权限变化
  491. amapLocationManager(manager, didChangeAuthorization: status)
  492. // if(status != .notDetermined){
  493. // QSLTools.shared.requestNotificationPermission()
  494. // }
  495. //print("系统定位权限变化: \(status.rawValue)")
  496. } else {
  497. // Fallback on earlier versions
  498. }
  499. }
  500. // 定位结果回调
  501. func amapLocationManager(_ manager: AMapLocationManager, didFailWithError error: Error) {
  502. print("定位失败: \(error.localizedDescription)")
  503. QSEventHandle.gravityPush(eventName: QSLGravityConst.location_fail_always, eventProps: ["id": 03004])
  504. }
  505. }
  506. // MARK: - 设置WebSocket
  507. extension QSLHomeController: QSLSocketManagerDelegate {
  508. // 初始化
  509. func initSocket() {
  510. QSLSocketManager.shared.urlString = "\(QSLApi.prodWSUrl)/websocket/\(QSLBaseManager.shared.userModel.authToken)"
  511. QSLSocketManager.shared.connect()
  512. QSLSocketManager.shared.delegate = self
  513. }
  514. // 关闭socket
  515. func deposeSocket() {
  516. QSLSocketManager.shared.urlString = ""
  517. QSLSocketManager.shared.close()
  518. QSLSocketManager.shared.delegate = nil
  519. }
  520. // 发送socket信息
  521. func sendSocket() {
  522. var message = QSLMapMessageModel()
  523. message.cmd = "u.location"
  524. var location = QSLMapTrackModel()
  525. location.lat = self.personalModel.location.lat
  526. location.lng = self.personalModel.location.lng
  527. location.addr = self.personalModel.location.addr
  528. location.speed = self.personalModel.location.speed
  529. location.bearing = self.personalModel.location.bearing
  530. location.timestamp = Int(Date.milliStamp) ?? 0
  531. message.body = location.toJSONString()
  532. QSLSocketManager.shared.sendMessage(message.toJSONString())
  533. }
  534. // 接收到消息
  535. func socketDidReceiveMessage(with string: String) {
  536. let locationModel = QSLMapMessageModel.mapModel(from: string)
  537. if let data = locationModel.body.data(using: .utf8), let list = try? JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [QSLMapTrackModel] {
  538. if locationModel.cmd == "d.location.batch" {
  539. for model in list {
  540. var isBlockedMe = false
  541. for var user in viewModel.friendList {
  542. if model.userId == user.friendId {
  543. user.location = model
  544. isBlockedMe = user.blockedMe
  545. }
  546. }
  547. if !isBlockedMe && QSLBaseManager.shared.isVip() {
  548. for location in viewModel.friendLocationList {
  549. if model.userId == location.userId {
  550. let annotation = MAPointAnnotation()
  551. let cll2d = CLLocationCoordinate2D(latitude: model.lat, longitude: model.lng)
  552. annotation.coordinate = cll2d
  553. location.pointAnnotation = annotation
  554. self.homeMapView.addAnnotation(location.pointAnnotation)
  555. }
  556. }
  557. }
  558. }
  559. self.homeFriendView.viewModel = self.viewModel
  560. }
  561. }
  562. }
  563. }
  564. // MARK: - 设置界面代理方法
  565. extension QSLHomeController: QSLHomeEmptyViewDelegate, QSLHomeFriendViewDelegate {
  566. func viewDidScroll() {
  567. switch self.homeFriendView.scrollLocation {
  568. case .ScrollTop:
  569. self.homeFriendView.snp.updateConstraints { make in
  570. make.top.equalTo(QSLConst.qsl_kStatusBarFrameH - 40.rpx)
  571. }
  572. break
  573. case .ScrollCenter:
  574. self.homeFriendView.snp.updateConstraints { make in
  575. make.top.equalTo(QSLConst.qsl_kScreenH - viewModel.friendViewHeight - QSLConst.qsl_kStatusBarFrameH)
  576. }
  577. break
  578. case .ScrollBottom:
  579. self.homeFriendView.snp.updateConstraints { make in
  580. if(QSLBaseManager.shared.isVip()){
  581. make.top.equalTo(QSLConst.qsl_kScreenH - QSLConst.qsl_kTabbarFrameH - 56.rpx - 40.rpx)
  582. }else{
  583. make.top.equalTo(QSLConst.qsl_kScreenH - QSLConst.qsl_kTabbarFrameH - 56.rpx - 40.rpx - 48.rpx)
  584. }
  585. }
  586. break
  587. default:
  588. break
  589. }
  590. }
  591. func addFriendAction(isSmall: Bool) {
  592. if isSmall {
  593. QSLJumpManager.shared.pushToAdd(type: .homesmall)
  594. } else {
  595. QSLJumpManager.shared.pushToAdd(type: .homebig)
  596. }
  597. }
  598. func refreshBtnAction() {
  599. QSEventHandle.eventPush(eventName: QSLGravityConst.home_locate)
  600. self.loadData()
  601. }
  602. // 轨迹
  603. func routeBtnAction(model: QSLUserModel) {
  604. if QSLBaseManager.shared.isVip() {
  605. if !QSLBaseManager.shared.isLogin() {
  606. QSLJumpManager.shared.pushToLogin(type: .contact)
  607. return
  608. }
  609. }else{
  610. QSLJumpManager.shared.pushToVip(type: .contact)
  611. return
  612. }
  613. QSLJumpManager.shared.pushToRoad(type: .home, model: model)
  614. }
  615. // 点击列表的定位按钮
  616. func locateBtnAction(model: QSLUserModel) {
  617. if !QSLBaseManager.shared.isVip() {
  618. self.view.toast(text: "请先开通会员")
  619. return
  620. }
  621. if model.blockedMe {
  622. return
  623. }
  624. let location = CLLocationCoordinate2D(latitude: model.location.lat, longitude: model.location.lng)
  625. self.homeMapView.setCenter(location, animated: true)
  626. for point in self.viewModel.friendLocationList {
  627. if point.userId == model.friendId {
  628. self.homeMapView.removeAnnotation(point.pointAnnotation)
  629. point.pointAnnotation?.subtitle = "350"
  630. self.homeMapView.addAnnotation(point.pointAnnotation)
  631. }
  632. }
  633. }
  634. func emptyFriPhoneViewClick() {
  635. if let vc = self.tabBarController {
  636. QSLFriendAddAlertView.show(vc: vc) {
  637. }
  638. }
  639. }
  640. func homeFriPhoneViewClick() {
  641. if let vc = self.tabBarController {
  642. QSLFriendAddAlertView.show(vc: vc) {
  643. }
  644. }
  645. }
  646. }
  647. // MARK: - 设置UI相关方法
  648. extension QSLHomeController {
  649. // 设置基础UI
  650. func setUpUI() {
  651. view.addSubview(homeMapView)
  652. homeMapView.snp.makeConstraints { make in
  653. make.edges.equalTo(0)
  654. }
  655. view.addSubview(homeFriendBtn)
  656. homeFriendBtn.snp.makeConstraints { make in
  657. make.size.equalTo(CGSize(width: 56.rpx, height: 56.rpx))
  658. make.top.equalTo(QSLConst.qsl_kStatusBarFrameH + 28.rpx)
  659. make.right.equalTo(-2.rpx)
  660. }
  661. //
  662. // view.addSubview(homeLocateBtnView)
  663. // homeLocateBtnView.snp.makeConstraints { make in
  664. // make.size.equalTo(CGSize(width: 40, height: 40))
  665. // make.top.equalTo(self.homeButtonsView.snp.bottom).offset(16)
  666. // make.right.equalTo(QSLHomeViewModel.UX.viewRight)
  667. // }
  668. view.addSubview(homeFriendView)
  669. homeFriendView.snp.makeConstraints { make in
  670. make.left.right.equalTo(0)
  671. make.top.equalTo(QSLConst.qsl_kScreenH - viewModel.friendViewHeight - QSLConst.qsl_kTabbarFrameH)
  672. make.height.equalTo(QSLConst.qsl_kScreenH - QSLConst.qsl_kTabbarFrameH)
  673. }
  674. let friViewTopY = QSLConst.qsl_kScreenH - viewModel.friendViewHeight - QSLConst.qsl_kTabbarFrameH
  675. homeFriendView.scrollCenterHeight = friViewTopY
  676. homeFriendView.snp.updateConstraints { make in
  677. make.top.equalTo(friViewTopY)
  678. }
  679. }
  680. }