UIDevice的简单使用

2369次阅读  |  发布于5年以前

什么是UIDevice

UIDevice提供了多种属性、类函数及状态通知,帮助我们全方位了解设备状况。从检测电池电量到定位设备与临近感应,UIDevice所做的工作就是为应用程序提供用户及设备的一些信息。UIDevice类还能够收集关于设备的各种具体细节,例如机型及iOS版本等。其中大部分属性都对开发工作具有积极的辅助作用。下面的代码简单的使用UIDevice获取手机属性。

说白了UIDevice就是可以获取苹果设备的一些设备上的信息,比如设备号,电池方面的问题,操作系统的版本号等等

UIDevice使用示例

下面是一段使用UIdevice的简单代码:

//
//  Device.swift
//  UIDevice
//
//  Created by Mao hua on 16/6/5.
//  Copyright © 2016年 Mao hua. All rights reserved.
//

import Foundation
import UIKit
class Device
{
    func show()
    {
        var dev:UIDevice = UIDevice.currentDevice();//获得当前设备

        //设备和系统基本信息
        print("设备名称\(dev.name)");
        print("设备类型\(dev.model)");
        print("本地化模式\(dev.localizedModel)");
        print("系统名称\(dev.systemName)");
        print("系统版本\(dev.systemVersion)");
        print("设备朝向\(dev.orientation)");
        print("UUID\(dev.identifierForVendor?.UUIDString)");
        //设备方向改变通知
        UIDeviceOrientationDidChangeNotification;
        //设备类型种类
        if(dev.userInterfaceIdiom == UIUserInterfaceIdiom.Phone)
        {
            print("iPhone设备");
        }
        else if(dev.userInterfaceIdiom == UIUserInterfaceIdiom.Pad)
        {
            print("iPad设备");
        }
        else if(dev.userInterfaceIdiom == UIUserInterfaceIdiom.TV)
        {
            print("Apple TV设备");
        }else if(dev.userInterfaceIdiom == UIUserInterfaceIdiom.CarPlay)
        {
            print("苹果车载设备");
        }
        else
        {
            print("未知设备");
        }

        //电池相关
        dev.batteryMonitoringEnabled = true;//设置电池是否被监视
        //判断当前电池状态
        if(dev.batteryState == UIDeviceBatteryState.Unknown)
        {
            print("未知状态");
        }
        else if(dev.batteryState == UIDeviceBatteryState.Unplugged)
        {
            print("未充电");
        }
        else if(dev.batteryState == UIDeviceBatteryState.Charging)
        {
            print("正在充电");
        }
        else if(dev.batteryState == UIDeviceBatteryState.Full)
        {
            print("正在充电,电量已满");
        }
        //当前电量等级 [0.0,1.0]
        print("\(dev.batteryLevel)");

        //电量等级改变通知
        UIDeviceBatteryLevelDidChangeNotification;
        //电池状态改变通知
        UIDeviceBatteryStateDidChangeNotification
        //以上两个通知要在batteryMonitoringEnabled,设置为true才有效


        //红外线感应
        //开启红外感应-- 用于检测手机是否靠近面部
        dev.proximityMonitoringEnabled = true;

        if(dev.proximityState == true)
        {
            print("靠近脸部");
        }
        else{
            print("没有靠近脸部");
        }

        //多任务环境监测
        //判断当前系统是否支持多任务
        if(dev.multitaskingSupported == true)
        {
            print("支持多任务");
        }
        else{
            print("不支持多任务");
        }
    }

}

Copyright© 2013-2020

All Rights Reserved 京ICP备2023019179号-8