Blame view

Twear/Tools/SystemAuth.swift 20.6 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
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
  //
  //  SystemAuth.swift
  //  Authorization
  //
  //  Created by 柯南 on 2020/9/4.
  //  Copyright © 2020 LTM. All rights reserved.
  //
  
  import UIKit
  
  /// 媒体资料库/Apple Music
  import MediaPlayer
  import Alamofire
  import Photos
  import UserNotifications
  import Contacts
  /// Siri权限
  import Intents
  /// 语音转文字权限
  import Speech
  /// 日历提醒事项
  import EventKit
  /// FaceTouchID
  import LocalAuthentication
  import HealthKit
  import HomeKit
  /// 运动与健身权限
  import CoreMotion
  /// 防止获取无效 计步器
  private let cmPedometer = CMPedometer()
  
  typealias AuthClouser = ((Bool)->())
  
  /// 定义私有全局变量,解决在iOS 13 定位权限弹框自动消失的问题
  private let locationAuthManager = CLLocationManager()
  
  /**
   escaping 逃逸闭包的生命周期
   
   1闭包作为参数传递给函数
   
   2退出函数
   
   3闭包被调用闭包生命周期结束
   即逃逸闭包的生命周期长于函数函数退出的时候逃逸闭包的引用仍被其他对象持有不会在函数结束时释放
   经常使用逃逸闭包的2个场景
   异步调用: 如果需要调度队列中异步调用闭包比如网络请求成功的回调和失败的回调这个队列会持有闭包的引用至于什么时候调用闭包或闭包什么时候运行结束都是不确定上边的例子
   存储: 需要存储闭包作为属性全局变量或其他类型做稍后使用例子待补充
   */
  public class SystemAuth {
      
      /**
       媒体资料库/Apple Music权限
       
       - parameters: action 权限结果闭包
       */
      class func authMediaPlayerService(clouser :@escaping AuthClouser) {
          if #available(iOS 9.3, *) {
              let authStatus = MPMediaLibrary.authorizationStatus()
    
          switch authStatus {
              /// 未作出选择
          case .notDetermined:
              MPMediaLibrary.requestAuthorization { (status) in
                  if status == .authorized{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
              /// 用户明确拒绝此应用程序的授权或在设置中禁用该服务
          case .denied:
              clouser(false)
              /// 该应用程序未被授权使用该服务由于用户无法改变对该服务的主动限制此状态并且个人可能没有拒绝授权
          case .restricted:
              clouser(false)
              /// 已授权
          case .authorized:
              clouser(true)
              /// 扩展以后可能有的状态,做保护措施
          @unknown default:
              clouser(false)
          }
          } else {
              // Fallback on earlier versions
          }
      }
      
      /**
       联网权限
       
       - parameters: action 权限结果闭包
       */
  //    class func authNetwork(clouser: @escaping AuthClouser) {
  //
  //        let reachabilityManager = NetworkReachabilityManager(host: "www.baidu.com")
  //
  //        switch reachabilityManager?.networkReachabilityStatus {
  //        case .reachable(.cellular):
  //            clouser(true)
  //        case .reachable(.ethernetOrWiFi):
  //            clouser(true)
  //        case .none:
  //            clouser(false)
  //        case .notReachable:
  //            clouser(false)
  //            //            let status = reachabilityManager?.flags
  //            //            switch status {
  //            //            case .none:
  //            //                clouser(false)
  //            //            case .some(.connectionAutomatic):
  //            //                clouser(false)
  //            //            case .some(.connectionOnDemand):
  //            //                clouser(false)
  //            //            case .some(.connectionOnTraffic):
  //            //                clouser(false)
  //            //            case .some(.connectionRequired):
  //            //                clouser(false)
  //            //            case .some(.interventionRequired):
  //            //                clouser(false)
  //            //            case .some(.isDirect):
  //            //                clouser(false)
  //            //            case .some(.isLocalAddress):
  //            //                clouser(false)
  //            //            case .some(.isWWAN):
  //            //                clouser(false)
  //            //            case .some(.reachable):
  //            //                clouser(false)
  //            //            case .some(.transientConnection):
  //            //                clouser(false)
  //            //            case .init(rawValue: 0):
  //            //                clouser(false)
  //            //            case .some(_):
  //            //                clouser(false)
  //            //            }
  //        case .unknown:
  //            clouser(false)
  //        }
  //    }
      
      /**
       相机权限
       
       - parameters: action 权限结果闭包
       */
      class func authCamera(clouser: @escaping AuthClouser) {
          let authStatus = AVCaptureDevice.authorizationStatus(for: .video)
          switch authStatus {
          case .notDetermined:
              AVCaptureDevice.requestAccess(for: .video) { (result) in
                  if result{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .denied:
              clouser(false)
          case .restricted:
              clouser(false)
          case .authorized:
              clouser(true)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       相册权限
       
       - parameters: action 权限结果闭包
       */
      class func authPhotoLib(clouser: @escaping AuthClouser) {
          let authStatus = PHPhotoLibrary.authorizationStatus()
          switch authStatus {
          case .notDetermined:
              PHPhotoLibrary.requestAuthorization { (status) in
                  if status == .authorized{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .denied:
              clouser(false)
          case .restricted:
              clouser(false)
          case .authorized:
              clouser(true)
          case .limited:
              clouser(false)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       麦克风权限
       
       - parameters: action 权限结果闭包
       */
      class func authMicrophone(clouser: @escaping AuthClouser) {
          let authStatus = AVAudioSession.sharedInstance().recordPermission
          switch authStatus {
          case .undetermined:
              AVAudioSession.sharedInstance().requestRecordPermission { (result) in
                  if result{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .denied:
              clouser(false)
          case .granted:
              clouser(true)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       定位权限
       
       - parameters: action 权限结果闭包(有无权限,是否第一次请求权限)
       */
      class func authLocation(clouser: @escaping ((Bool,Bool)->())) {
          let authStatus = CLLocationManager.authorizationStatus()
          
          switch authStatus {
          case .notDetermined:
              //由于IOS8中定位的授权机制改变 需要进行手动授权
              locationAuthManager.requestAlwaysAuthorization()
              locationAuthManager.requestWhenInUseAuthorization()
              let status = CLLocationManager.authorizationStatus()
              if  status == .authorizedAlways || status == .authorizedWhenInUse {
                  DispatchQueue.main.async {
                      clouser(true && CLLocationManager.locationServicesEnabled(), true)
                  }
              } else {
                  DispatchQueue.main.async {
                      clouser(false, true)
                  }
              }
          case .restricted:
              clouser(false, false)
          case .denied:
              clouser(false, false)
          case .authorizedAlways:
              clouser(true && CLLocationManager.locationServicesEnabled(), false)
          case .authorizedWhenInUse:
              clouser(true && CLLocationManager.locationServicesEnabled(), false)
          @unknown default:
              clouser(false, false)
          }
      }
      
      /**
       推送权限
       
       - parameters: action 权限结果闭包
       */
      class func authNotification(clouser: @escaping AuthClouser){
          if #available(iOS 10.0, *) {
              UNUserNotificationCenter.current().getNotificationSettings(){ (setttings) in
                  switch setttings.authorizationStatus {
                  case .notDetermined:
                      UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .carPlay, .sound]) { (result, error) in
                          if result{
                              DispatchQueue.main.async {
                                  clouser(true)
                              }
                          }else{
                              DispatchQueue.main.async {
                                  clouser(false)
                              }
                          }
                      }
                  case .denied:
                      clouser(false)
                  case .authorized:
                      clouser(true)
                  case .ephemeral:
                      clouser(true)
                  case .provisional:
                      clouser(true)
                  @unknown default:
                      clouser(false)
                  }
              }
          } else {
              // Fallback on earlier versions
          }
      }
      
      /**
       运动与健身
       
       - parameters: action 权限结果闭包
       */
      class func authCMPedometer(clouser: @escaping AuthClouser){
          cmPedometer.queryPedometerData(from: Date(), to: Date()) { (pedometerData, error) in
              if pedometerData?.numberOfSteps != nil{
                  DispatchQueue.main.async {
                      clouser(true)
                  }
              }else{
                  DispatchQueue.main.async {
                      clouser(false)
                  }
              }
          }
      }
      
      /**
       通讯录权限
       
       - parameters: action 权限结果闭包
       */
      class func authContacts(clouser: @escaping AuthClouser){
          let authStatus = CNContactStore.authorizationStatus(for: .contacts)
          switch authStatus {
          case .notDetermined:
              CNContactStore().requestAccess(for: .contacts) { (result, error) in
                  if result{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .restricted:
              clouser(false)
          case .denied:
              clouser(false)
          case .authorized:
              clouser(true)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       Siri 权限
       
       - parameters: action 权限结果闭包
       */
      class func authSiri(clouser: @escaping AuthClouser){
          if #available(iOS 10.0, *) {
              let authStatus = INPreferences.siriAuthorizationStatus()
   
          switch authStatus {
          case .notDetermined:
              INPreferences.requestSiriAuthorization { (status) in
                  if status == .authorized{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .restricted:
              clouser(false)
          case .denied:
              clouser(false)
          case .authorized:
              clouser(true)
          @unknown default:
              clouser(false)
          }
          } else {
              // Fallback on earlier versions
          }
      }
      
      /**
       语音转文字权限
       
       - parameters: action 权限结果闭包
       */
      class func authSpeechRecognition(clouser: @escaping AuthClouser){
          if #available(iOS 10.0, *) {
              let authStatus = SFSpeechRecognizer.authorizationStatus()
              
              switch authStatus {
              case .notDetermined:
                  SFSpeechRecognizer.requestAuthorization { (status) in
                      if status == .authorized{
                          DispatchQueue.main.async {
                              clouser(true)
                          }
                      }else{
                          DispatchQueue.main.async {
                              clouser(false)
                          }
                      }
                  }
              case .restricted:
                  clouser(false)
              case .denied:
                  clouser(false)
              case .authorized:
                  clouser(true)
              @unknown default:
                  clouser(false)
              }
          } else {
              // Fallback on earlier versions
          }
      }
      
      /**
       提醒事项
       
       - parameters: action 权限结果闭包
       */
      class func authRreminder(clouser: @escaping AuthClouser){
          let authStatus = EKEventStore.authorizationStatus(for: .reminder)
          switch authStatus {
          case .notDetermined:
              EKEventStore().requestAccess(to: .reminder) { (result, error) in
                  if result{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .restricted:
              clouser(false)
          case .denied:
              clouser(false)
          case .authorized:
              clouser(true)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       日历
       
       - parameters: action 权限结果闭包
       */
      class func authEvent(clouser: @escaping AuthClouser){
          let authStatus = EKEventStore.authorizationStatus(for: .event)
          switch authStatus {
          case .notDetermined:
              EKEventStore().requestAccess(to: .event) { (result, error) in
                  if result{
                      DispatchQueue.main.async {
                          clouser(true)
                      }
                  }else{
                      DispatchQueue.main.async {
                          clouser(false)
                      }
                  }
              }
          case .restricted:
              clouser(false)
          case .denied:
              clouser(false)
          case .authorized:
              clouser(true)
          @unknown default:
              clouser(false)
          }
      }
      
      /**
       FaceID或者TouchID 认证
       
       - parameters: action 权限结果闭包
       */
      class func authFaceOrTouchID(clouser: @escaping ((Bool,Error)->())) {
          let context = LAContext()
          var error: NSError?
          let result = context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error)
          if result {
              context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: "认证") { (success, authError) in
                  if success{
                      print("成功")
                  }else{
                      print("失败")
                  }
              }
          }else{
              /**
               #define kLAErrorAuthenticationFailed                       -1
               #define kLAErrorUserCancel                                 -2
               #define kLAErrorUserFallback                               -3
               #define kLAErrorSystemCancel                               -4
               #define kLAErrorPasscodeNotSet                             -5
               #define kLAErrorTouchIDNotAvailable                        -6
               #define kLAErrorTouchIDNotEnrolled                         -7
               #define kLAErrorTouchIDLockout                             -8
               #define kLAErrorAppCancel                                  -9
               #define kLAErrorInvalidContext                            -10
               #define kLAErrorNotInteractive                          -1004
               
               #define kLAErrorBiometryNotAvailable              kLAErrorTouchIDNotAvailable
               #define kLAErrorBiometryNotEnrolled               kLAErrorTouchIDNotEnrolled
               
               */
              print("不可以使用")
          }
      }
      
      /**
       健康  (:体能训练iOS13 听力图 : 健身记录体能训练iOS13 听力图)
       
       - parameters: action 权限结果闭包
       */
      class func authHealth(clouser: @escaping AuthClouser){
          if HKHealthStore.isHealthDataAvailable(){
              let authStatus = HKHealthStore().authorizationStatus(for: .workoutType())
              switch authStatus {
              case .notDetermined:
                  if #available(iOS 13.0, *) {
                      HKHealthStore().requestAuthorization(toShare: [.audiogramSampleType(), .workoutType()], read: [.activitySummaryType(), .workoutType(), .audiogramSampleType()]) { (result, error) in
                          if result{
                              DispatchQueue.main.async {
                                  clouser(true)
                              }
                          }else{
                              DispatchQueue.main.async {
                                  clouser(false)
                              }
                          }
                      }
                  } else {
                      if #available(iOS 9.3, *) {
                          HKHealthStore().requestAuthorization(toShare: [.workoutType()], read: [.activitySummaryType(), .workoutType()]) { (result, error) in
                              if result{
                                  DispatchQueue.main.async {
                                      clouser(true)
                                  }
                              }else{
                                  DispatchQueue.main.async {
                                      clouser(false)
                                  }
                              }
                          }
                      } else {
                          // Fallback on earlier versions
                      }
                  }
              case .sharingDenied:
                  clouser(false)
              case .sharingAuthorized:
                  clouser(true)
              @unknown default:
                  clouser(false)
              }
          }else{
              clouser(false)
          }
      }
      
      /**
       家庭住宅数据
       
       - parameters: action 权限结果闭包
       */
      class func authHomeKit(clouser: @escaping AuthClouser) {
          if #available(iOS 13.0, *) {
              switch HMHomeManager().authorizationStatus {
              case .authorized:
                  clouser(true)
              case .determined:
                  clouser(false)
              case .restricted:
                  clouser(false)
              default:
                  clouser(false)
              }
          } else {
              if (HMHomeManager().primaryHome != nil) {
                  clouser(true)
              }else{
                  clouser(false)
              }
          }
      }
      
      /**
       系统设置
       
       - parameters: urlString 可以为系统,也可以为微信:weixin://QQ:mqq://
       - parameters: action 结果闭包
       */
      class func authSystemSetting(urlString :String?, clouser: @escaping AuthClouser) {
          var url: URL
          if (urlString != nil) && urlString?.count ?? 0 > 0 {
              url = URL(string: urlString!)!
          }else{
              url = URL(string: UIApplication.openSettingsURLString)!
          }
          
          if UIApplication.shared.canOpenURL(url){
              if #available(iOS 10.0, *) {
                  UIApplication.shared.open(url, options: [:]) { (result) in
                      if result{
                          clouser(true)
                      }else{
                          clouser(false)
                      }
                  }
              } else {
                  // Fallback on earlier versions
              }
          }else{
              clouser(false)
          }
      }
  }