Blame view

Twear/Motion(运动)/StartMotionVC.swift 16.3 KB
75d24c15   yangbin   123
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
  //
  //  StartMotionVC.swift
  //  Twear
  //
  //  Created by yangbin on 2021/12/28.
  //
  
  import UIKit
  import SnapKit
  import SwiftDate
  import CoreLocation
  import MBProgressHUD
  
  class StartMotionVC: UIViewController {
      
      @IBOutlet weak var mapBackView: UIView!
      @IBOutlet weak var countImageView: UIImageView!
      @IBOutlet weak var detailView: UIView!
      
      @IBOutlet weak var stopButton: ProgressButton!
      @IBOutlet weak var mapButton: UIButton!
      
      @IBOutlet weak var startButton: UIButton!
      @IBOutlet weak var pauseButton: UIButton!
      
      @IBOutlet weak var calorieLabel: UILabel!
      @IBOutlet weak var timeLabel: UILabel!
      @IBOutlet weak var speedLabel: UILabel!
      
      @IBOutlet weak var mapTimeLabel: UILabel!
      @IBOutlet weak var mapDistanceLabel: UILabel!
      @IBOutlet weak var distanceLabel: UILabel!
      private lazy var mapView: MAMapView = MAMapView()
      private var count: Int = 3
      
      private var speedArray: [Float] = []
      var isRecord: Bool = false
      var motionType: TrainType = .running
      var time: Int = 0
      var distance: Float = 0
      var speed: Float = 0
      var calorie: Float = 0
      var startDate = Date()
      
      var coordinateArray: [CLLocationCoordinate2D] = []
      var locationArray: [CLLocation] = []
      private lazy var locationManager: AMapLocationManager = AMapLocationManager()
      
      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
          
          GCDTimer.shared.scheduledDispatchTimer(WithTimerName: "count_down", timeInterval: 1, queue: .main, repeats: true) {[weak self] in
              self?.countDown()
          }
          locationManager.startUpdatingLocation()
          locationManager.startUpdatingHeading()
      }
      
      override func viewDidLoad() {
          super.viewDidLoad()
          stopButton.progressClosure = { [weak self] in
              self?.stopMotion()
  //            self?.dismiss(animated: true)
          }
          initMapView()
      }
      
      func initMapView() {
          MAMapView.updatePrivacyShow(.didShow, privacyInfo: .didContain)
          MAMapView.updatePrivacyAgree(.didAgree)
          AMapServices.shared().enableHTTPS = true
          mapView.showsUserLocation = false
          let compassX = mapView.compassOrigin.x
          mapView.compassOrigin = CGPoint(x: compassX-5, y: 120)
          mapView.userTrackingMode = .followWithHeading
          mapView.zoomLevel = 17.5
          mapView.delegate = self
          mapView.mapLanguage = (AppSettings.shared.language == .Chinese) ? 0 : 1 
  //        mapView.distanceFilter = 10
  //        mapView.desiredAccuracy = kCLLocationAccuracyBestForNavigation
          mapView.frame = mapBackView.frame
          
          mapBackView.addSubview(mapView)
          mapBackView.sendSubviewToBack(mapView)
          
          mapBackView.isHidden = true
          
          locationManager.delegate = self
          
          locationManager.pausesLocationUpdatesAutomatically = false
  //        locationManager.allowsBackgroundLocationUpdates = true
          locationManager.distanceFilter = 5
          locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
          locationManager.allowsBackgroundLocationUpdates = true
  //        locationManager.startUpdatingLocation()
      }
      
      func startMotion() {
          time += 1
          timeLabel.toTimeType3(length: time)
          mapTimeLabel.toTimeType3(length: time)
      }
      
      func stopMotion() {
          isRecord = false
          if distance > 60 {
              var altitude: Double = 0
              if let minAltitude = locationArray.min(\.altitude)?.altitude, let maxAltitude = locationArray.max(\.altitude)?.altitude {
                  altitude = maxAltitude - minAltitude
              }
              let motion = MotionModel(type: motionType, date: DateInRegion().date - time.seconds, length: time, calorie: calorie, distance: Int(distance), steps: 0, altitude: altitude)
              motion.add()
  //            MBProgressHUD.showh("..test")
              let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Motion", identifier: "EndMotionVC") as! EndMotionVC
              vc.modalPresentationStyle = .fullScreen
              vc.coordinateArray = coordinateArray
              vc.calorie = calorie
              vc.distance = distance
              vc.length = time
              vc.date = startDate
              vc.speedArray = speedArray
              self.present(vc, animated: true, completion: nil)
  //            self.dismiss(animated: true, completion: nil)
          } else {
              let view = BottomAlertView(title: LocString("本次运动距离太短,将不保存记录"), sureText: LocString("我知道了"))
              view.clickClosure = {[weak self] index in
                  self?.dismiss(animated: true)
              }
              view.show()
          }
      }
      
      @IBAction func continueMotion(_ sender: Any) {
          isRecord = true
          showStopButton(false)
          GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartMotion", timeInterval: 1, queue: .main, repeats: true) { [weak self] in
              self?.startMotion()
          }
      }
      
      @IBAction func pauseMotion(_ sender: Any) {
          isRecord = false
          showStopButton(true)
          if GCDTimer.shared.isExistTimer(WithTimerName: "StartMotion") {
              GCDTimer.shared.cancleTimer(WithTimerName: "StartMotion")
          }
      }
      
      
      func showStopButton(_ isShow: Bool) {
          pauseButton.isHidden = isShow
          self.startButton.isHidden = !isShow
          self.stopButton.isHidden = !isShow
          let centerX = isShow ? SCREEN_WIDTH/2*0.55 : SCREEN_WIDTH/2
          UIView.animate(withDuration: 0.3) {
              self.stopButton.center.x = centerX
              self.startButton.center.x = SCREEN_WIDTH-centerX
          } completion: { finish in
          }
      }
      
      func countDown() {
          if count > 0 {
              countImageView.image = UIImage(named: "count_down_\(count)")
              let animation = CABasicAnimation(keyPath: "transform.scale")
              animation.fromValue = 0.5
              animation.toValue = 1
              animation.duration = 0.5
              animation.beginTime = 0
              if count == 1 {
                  hideMap(1)
              }
              self.countImageView.layer.add(animation, forKey: nil)
              count -= 1
          } else {
              if GCDTimer.shared.isExistTimer(WithTimerName: "count_down") {
                  GCDTimer.shared.cancleTimer(WithTimerName: "count_down")
              }
              self.countImageView.isHidden = true
              self.mapButton.isHidden = false
              self.detailView.isHidden = false
              isRecord = true
              startDate = DateInRegion().date
              GCDTimer.shared.scheduledDispatchTimerNotNow(WithTimerName: "StartMotion", timeInterval: 1, queue: .main, repeats: true) { [weak self] in
                  self?.startMotion()
              }
          }
      }
      
      
      @IBAction func showMap(_ sender: Any) {
          mapBackView.isHidden = false
          mapBackView.isUserInteractionEnabled = false
          UIView.animate(withDuration: 0.3) {
              self.mapBackView.center = self.view.center
              self.mapBackView.transform = .identity
  //            self.view.layoutIfNeeded()
          } completion: { finish in
              self.mapBackView.isUserInteractionEnabled = true
          }
          
      }
      
      @IBAction func hideMap(_ sender: Any) {
          UIView.animate(withDuration: 0.3) {
              self.mapBackView.transform = CGAffineTransform.init(scaleX: 0.02, y: 0.02)
              self.mapBackView.center = self.mapButton.center
  //            self.view.layoutIfNeeded()
          } completion: { finish in
              self.mapBackView.isHidden = true
          }
      }
      
      deinit {
          print("deinit\(NSStringFromClass(type(of: self)))!!!!!!!")
      }
      
      private func distanceToCalorie(_ distance: Float) -> Float {
          let user = UserInfo
          var weight = user.weight
          if user.weight < 15 {
              weight = 65
          }
          if user.gender == 1 {
              return Float((weight - 10)) * distance
          } else {
              return Float((weight - 10)) * distance * 1.3
          }
      }
      /*
       // MARK: - Navigation
       
       // In a storyboard-based application, you will often want to do a little preparation before navigation
       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       // Get the new view controller using segue.destination.
       // Pass the selected object to the new view controller.
       }
       */
      
  }
  extension StartMotionVC: AMapLocationManagerDelegate {
  
      
      func amapLocationManager(_ manager: AMapLocationManager!, didUpdate location: CLLocation!) {
  //        mapView.showsUserLocation
          if !isRecord {
              return
          }
  //        if !updatingLocation {
  //            return
  //        }
  //        guard let location = userLocation.location else {
  //            return
  //        }
          if coordinateArray.count == 0 {
              coordinateArray.append(location.coordinate)
              locationArray.append(location)
          } else {
              let lastCoordinate = coordinateArray.last!
              let point1 = MAMapPointForCoordinate(lastCoordinate)
              let point2 = MAMapPointForCoordinate(location.coordinate)
              let dis = MAMetersBetweenMapPoints(point1, point2)
  //            print(Float(dis))
              distance += Float(dis)
  //            print(distance)
              if distance == 0 {
                  return
              }
              distanceLabel.text = String(format:"%.2f", distance/1000)
              mapDistanceLabel.text = String(format:"%.2f", distance/1000)
              speed = Float(time)/(distance/1000)
              if speed > 0 {
                  speedArray.append(speed)
              }
              speedLabel.text = "\(String(format:"%02d", Int(speed)/60))\(String(format:"%02d", Int(speed)%60))″"
              calorie = distanceToCalorie(distance/1000)
              calorieLabel.text = String(format:"%.2f", calorie)
          }
          
          print("添加")
  //        print(location!.getDistanceFrom(userLocation.location))
          self.coordinateArray.append(location.coordinate)
          self.locationArray.append(location)
          updatePath()
      }
  }
  
  
  extension StartMotionVC: MAMapViewDelegate {
  //    func mapView(_ mapView: MAMapView!, viewFor annotation: MAAnnotation!) -> MAAnnotationView! {
  //          if annotation is MAUserLocation {
  //              var userView = mapView.dequeueReusableAnnotationView(withIdentifier: "userAnnotationIdentifer")
  //              if userView == nil {
  //                  userView = MAAnnotationView(annotation: annotation, reuseIdentifier: "userAnnotationIdentifer")
  //              }
  //              userView!.image = UIImage(named: "firmware_update")
  //              return userView!
  //          }
  //          return nil
  //      }
      
      
      
      func mapView(_ mapView: MAMapView!, didUpdate userLocation: MAUserLocation!, updatingLocation: Bool) {
  //        if updatingLocation {
  //            let userView = mapView.view(for: userLocation)
  //
  //                   //取方向信息
  //            if let userHeading = userLocation.heading {
  //                //根据方向旋转箭头
  //                userView?.rotateWithHeading(heading: userHeading)
  //            }
                     
                     
  //        }
          /*
          if !isRecord {
              return
          }
          if !updatingLocation {
              return
          }
          guard let location = userLocation.location else {
              return
          }
          if coordinateArray.count == 0 {
              coordinateArray.append(location.coordinate)
          } else {
              let lastCoordinate = coordinateArray.last!
              let point1 = MAMapPointForCoordinate(lastCoordinate)
              let point2 = MAMapPointForCoordinate(location.coordinate)
              let dis = MAMetersBetweenMapPoints(point1, point2)
  //            print(Float(dis))
              distance += Float(dis)
  //            print(distance)
              if distance == 0 {
                  return
              }
              distanceLabel.text = String(format:"%.2f", distance/1000)
              mapDistanceLabel.text = String(format:"%.2f", distance/1000)
              speed = Float(time)/(distance/1000)
              speedLabel.text = "\(String(format:"%02d", Int(speed)/60))\(String(format:"%02d", Int(speed)%60))″"
              calorieLabel.text = String(format:"%.2f", distanceToCalorie(distance/1000)/1000)
          }
          
          print("添加")
  //        print(location!.getDistanceFrom(userLocation.location))
          self.coordinateArray.append(location.coordinate)
          
          updatePath()
  */
  //        if isRecording {
  //            // filter the result
  //            if userLocation.location.horizontalAccuracy < 100.0 {
  //
  //                addLocation(location: userLocation.location)
  //            }
  //        }
  //
  //        var speed = location!.speed
  //        if speed < 0.0 {
  //            speed = 0.0
  //        }
  //
  //        let infoArray: [(String, String)] = [
  //            ("coordinate", NSString(format: "<%.4f, %.4f>", location!.coordinate.latitude, location!.coordinate.longitude) as String),
  //            ("speed", NSString(format: "%.2fm/s(%.2fkm/h)", speed, speed * 3.6) as String),
  //            ("accuracy", "\(location!.horizontalAccuracy)m"),
  //            ("altitude", NSString(format: "%.2fm", location!.altitude) as String)]
  //
  //        statusView!.showStatusInfo(info: infoArray)
          
      }
      
      func updatePath () {
         
         // 每次获取到新的定位点重新绘制路径
         
         // 移除掉除之前的overlay
         let overlays = self.mapView.overlays
         self.mapView.removeOverlays(overlays)
         
         let polyline = MAPolyline(coordinates: &self.coordinateArray, count: UInt(self.coordinateArray.count))
          self.mapView.add(polyline)
  
         // 将最新的点定位到界面正中间显示
          let lastCoord = self.coordinateArray[self.coordinateArray.count - 1]
          self.mapView.setCenter(lastCoord, animated: true)
     }
      
      func mapView(_ mapView: MAMapView!, rendererFor overlay: MAOverlay!) -> MAOverlayRenderer! {
          if let poly = overlay as? MAPolyline {
              let polylineView = MAPolylineRenderer(polyline: poly)
              polylineView!.lineWidth = 6
              polylineView!.strokeColor = UIColor(red: 4 / 255.0, green:  181 / 255.0, blue:  108 / 255.0, alpha: 1.0)
              polylineView!.lineJoinType = kMALineJoinRound
              polylineView!.lineCapType = kMALineCapRound
              return polylineView
          } else {
              return nil
          }
      }
  //
  //    func mapView(mapView: MAMapView!, viewForOverlay overlay: MAOverlay!) -> MAOverlayView! {
  //        if overlay.isKindOfClass(MAPolyline) {
  //            let polylineView = MAPolylineView(overlay: overlay)
  //            polylineView.lineWidth = 6
  //            polylineView.strokeColor = UIColor(red: 4 / 255.0, green:  181 / 255.0, blue:  108 / 255.0, alpha: 1.0)
  //
  //            return polylineView
  //        }
  //
  //        return nil
  //    }
      
      func mapView(_ mapView: MAMapView, didChange mode: MAUserTrackingMode, animated: Bool) {
  //        if mode == MAUserTrackingMode.none {
  //            locationButton?.setImage(imageNotLocate, for: UIControlState.normal)
  //        }
  //        else {
  //            locationButton?.setImage(imageLocated, for: UIControlState.normal)
  //        }
      }
  
  }
  extension MAAnnotationView {
      
      /// 根据heading信息旋转大头针视图
      ///
      /// - Parameter heading: 方向信息
      func rotateWithHeading(heading: CLHeading) {
          
          //将设备的方向角度换算成弧度
          let headings = Double.pi * heading.magneticHeading / 180.0
          //创建不断旋转CALayer的transform属性的动画
          let rotateAnimation = CABasicAnimation(keyPath: "transform")
          //动画起始值
          let formValue = self.layer.transform
          rotateAnimation.fromValue = NSValue(caTransform3D: formValue)
          //绕Z轴旋转heading弧度的变换矩阵
          let toValue = CATransform3DMakeRotation(CGFloat(headings), 0, 0, 1)
          //设置动画结束值
          rotateAnimation.toValue = NSValue(caTransform3D: toValue)
          rotateAnimation.duration = 0.35
          rotateAnimation.isRemovedOnCompletion = true
          //设置动画结束后layer的变换矩阵
          self.layer.transform = toValue
          
          //添加动画
          self.layer.add(rotateAnimation, forKey: nil)
          
      }
  }