iOS 获取电池电量,屏幕亮度,蓝牙状态

1、电池电量

    func openBatteryListening(){
        UIDevice.current.isBatteryMonitoringEnabled = true
        NotificationCenter.default.addObserver(self, selector: #selector(BatteryChange), name:UIDevice.batteryLevelDidChangeNotification, object: nil)
    }
   @objc func BatteryChange(notification:NSNotification){
        print("电池电量:\(UIDevice.current.batteryLevel*100) %")
    }

2、屏幕亮度

  func openBrightnessListening(){
       NotificationCenter.default.addObserver(self, selector: #selector(brightnessChange), name:UIScreen.brightnessDidChangeNotification, object: nil)
   }
   
   @objc func brightnessChange(){
       print("屏幕亮度:\(String(format: "%.2f",UIScreen.main.brightness*100.0)) %")
   }

3、蓝牙状态

var _CBlueToothCentralManager:CBCentralManager?

func openBlueToothStateChangeListening(){
        _CBlueToothCentralManager = CBCentralManager(delegate: self, queue: nil)
 }    
func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if(central.state == CBManagerState.poweredOff){
            print("蓝牙状态:关闭")
        }else{
            print("蓝牙状态:开启")
       }
}

4、获取磁盘空间

func openFreeDiskspace(){
    var totalSpace = 0.0
    var totalFreeSpace = 0.0
    var totalUsedSpace = 0.0
        
   if let path:String = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last{
     do{
           let dictionary = try FileManager.default.attributesOfFileSystem(forPath: path)
           let fileSystemSizeInBytes = dictionary[FileAttributeKey.systemSize] as! NSNumber
           let freeFileSystemSizeInBytes = dictionary[FileAttributeKey.systemFreeSize] as! NSNumber
            totalSpace = Double(truncating: fileSystemSizeInBytes)
            totalFreeSpace = Double(truncating: freeFileSystemSizeInBytes)
            totalUsedSpace = totalSpace - totalFreeSpace;
                //
            let freePercent = totalFreeSpace/totalSpace;
            let usedPercent = totalUsedSpace/totalSpace;
                
            print("iphone磁盘未使用率 =\(String(format: "%.2f",freePercent*100.0))%")
            print("iphone磁盘使用率  =\(String(format: "%.2f",usedPercent*100.0)) %")
            print("iphone磁盘总大小  =\(((totalSpace/1000.0)/1000.0/1000.0)) GB")
            print("iphone磁盘已使用大小    =\(((totalUsedSpace/1000.0)/1000.0/1000.0)) GB")
            print("iphone磁盘剩余大小    =\(((totalFreeSpace/1000.0)/1000.0/1000.0)) GB")
                
            print("Memory Capacity of \(((totalSpace/1000.0)/1000.0/1000.0)) GB with \( ((totalFreeSpace/1000.0)/1000.0)/1000.0)) GB Free memory available.")
                
       }catch{
           print(error)
        }
     }  
}

你可能感兴趣的:(iOS 获取电池电量,屏幕亮度,蓝牙状态)