簡體   English   中英

iOS 13 - 如何檢查用戶是否已接受藍牙權限?

[英]iOS 13 - How to check if user has accepted Bluetooth permission?

作為 iOS 13 的一部分,應用程序現在需要請求許可才能訪問藍牙。 在此處輸入圖片說明

如何檢查用戶是否接受了藍牙權限?

嘗試這個:

 var isBluetoothPermissionGranted: Bool {
    if #available(iOS 13.1, *) {
        return CBCentralManager.authorization == .allowedAlways
    } else if #available(iOS 13.0, *) {
        return CBCentralManager().authorization == .allowedAlways
    }
    // Before iOS 13, Bluetooth permissions are not required
    return true
}

CBCentralManager擴展了CBManager 從 iOS 13 開始, CBManager具有authorization屬性。

使用此屬性來確定權限是未知的、允許的、拒絕的還是受限的。

需要說明的是,在 iOS 下,需要使用實例屬性authorization ,而不是同名的 type 屬性。 請確保您訪問authorization的實例CBCentralManager

Swift 5 IOS 13基於接受的答案

    func isBluetoothAuthorized() -> Bool {
        if #available(iOS 13.0, *) {
            return CBCentralManager().authorization == .allowedAlways
        }
        return CBPeripheralManager.authorizationStatus() == .authorized
    }

有趣的是,從iOS 13.1開始,可以在不分配CBManager的情況下檢查 BT 權限。 這是一個巨大的優勢,因為如果之前沒有詢問/給予 BT 權限,初始化CBManager將自動觸發系統彈出窗口。

  func checkPermission() -> CBManagerAuthorization {
    if #available(iOS 13.1, *) {
      return checkPermissionBeforeCBManagerAllocation()
    } else {
      return checkPermissionLegacy()
    }
  }

  @available(iOS 13.1, *)
  private func checkPermissionBeforeCBManagerAllocation() -> CBManagerAuthorization {
    CBCentralManager.authorization
  }

  private func checkPermissionLegacy() -> CBManagerAuthorization {
    let manager = CBCentralManager(delegate: self, queue: nil)

    return manager.authorization
  }

以上只是iOS 13.x版本的示例,不處理低於此版本的任何內容。

這是我將使用的(適用於所有 iOS 的完整解決方案): Swift 5

class MainViewController: UIViewController {
    var isiOSBluetoothOn = false
       
    @IBAction func onBluetoothButtonClicked(_ sender: Any){
        if (isiOSBluetoothOn) {
            let newVC = self.storyboard?.instantiateViewController(withIdentifier: "blevc")
            self.navigationController?.pushViewController(newVC!, animated: true)
        } else {
            if #available(iOS 13.0, *) {
                if (CBCentralManager().authorization != .allowedAlways) {   //System will automatically ask user to turn on iOS system Bluetooth if this returns false
                   openAppOrSystemSettingsAlert(title: "Bluetooth permission is currently disabled for the application. Enable Bluetooth from the application settings.", message: "")
                }
            } else {
                let appName = Bundle.main.infoDictionary?["CFBundleName"] as? String
                openAppOrSystemSettingsAlert(title: "\"\(appName ?? "You Application Nam")\" would like to use Bluetooth for new connections", message: "You can allow new connections in Settings")
            }
        }
    }
                
    func openAppOrSystemSettingsAlert(title: String, message: String) {
        let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)
        let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
            guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else { return }
            if UIApplication.shared.canOpenURL(settingsUrl) {
                UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                    print("Settings opened: \(success)") // Prints true
                })
            }
        }
        alertController.addAction(settingsAction)
        let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
        alertController.addAction(cancelAction)
        present(alertController, animated: true, completion: nil)
    }
}

extension MainViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
           isiOSBluetoothOn = true
            break
        case .poweredOff:
           isiOSBluetoothOn = false
            break
        default:
            break
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM