iOS 獲取設備信息之UIDevice的使用,Swift 基於 API

這篇文章是基於 UIDevice 的 API進行分析的。最後給出了 UIDevice 的使用方法,包括能夠訪問設備名稱,系統版本,UUID,監測電量變化,電池電量狀態,監測屏幕方向變化,以及監測iPhone 是否在接近用戶的身體。git

UIDevice

UIDevice 是 UIKit 框架下Core App 中的設備環境的一個類。用來表示當前的設備,能夠使用 UIDevice 實例作什麼事情呢? 具體總結以下: 1.使用UIDevice對象獲取有關設備的信息,如名稱,設備型號以及操做系統名稱和版本。 2.能夠使用UIDevice實例來檢測設備特性的變化,例如物理方向。 3.能夠使用orientation屬性獲取當前方向,並能夠在設備方向改變的時候使用通知來做出相應的處理。 4.能夠使用UIDevice實例獲取有關電池充電狀態和充電水平更改的信息和通知。 5.還提供對接近傳感器狀態的訪問。接近傳感器檢測用戶是否將設備保持靠近他們的臉部。僅在須要時才啓用電池監控或接近感應。 6.還能夠使用實例方法在自定義輸入和鍵盤附件視圖中播放鍵盤輸入點擊。github

源碼分析

import Foundation
import UIKit

// 設備方向。一個枚舉
public enum UIDeviceOrientation : Int {

    
    case unknown   

    case portrait   // 豎直屏,home 鍵在下邊

    case portraitUpsideDown //  豎直屏,Home 鍵在上邊

    case landscapeLeft // 橫屏,Home 在右邊

    case landscapeRight // 橫屏,home 在左邊

    case faceUp // 平放,正面朝上

    case faceDown // 平放,正面朝下
}

// 設備方向的擴展。 用於判斷方向,只有 get 屬性
extension UIDeviceOrientation {
    // 是不是橫屏
    public var isLandscape: Bool { get }
    // 是不是豎屏
    public var isPortrait: Bool { get }
    // 是否平放
    public var isFlat: Bool { get }
    // 有效的界面方向
    public var isValidInterfaceOrientation: Bool { get }
}

// 電池狀態枚舉
public enum UIDeviceBatteryState : Int {

    
    case unknown

    case unplugged // 放電

    case charging // 充電,少於100%

    case full // 充滿
}
// available in iPhone 3.0

// 當前設備的界面類型 枚舉
public enum UIUserInterfaceIdiom : Int {

    
    case unspecified   // 未知。未指明

    @available(iOS 3.2, *)
    case phone // iPhone and iPod touch 風格的UI

    @available(iOS 3.2, *)
    case pad // iPad UI

    @available(iOS 9.0, *)
    case tv // Apple TV style UI

    @available(iOS 9.0, *)
    case carPlay // CarPlay style UI ,車載屏
}

//  方法。設備是不是豎屏,返回 Bool 值
public func UIDeviceOrientationIsPortrait(_ orientation: UIDeviceOrientation) -> Bool
// 設備是不是橫屏,返回 Bool 值
public func UIDeviceOrientationIsLandscape(_ orientation: UIDeviceOrientation) -> Bool

//  UIDevice類
@available(iOS 2.0, *)
open class UIDevice : NSObject {

     //類屬性,獲取當前設備實例
    open class var current: UIDevice { get }
     //實例屬性,設備名     
    open var name: String { get } // e.g. "My iPhone"
     //實例屬性,設備型號
    open var model: String { get } // e.g. @"iPhone", @"iPod touch"
     //實例屬性,設備定位型號
    open var localizedModel: String { get } // localized version of model
     //實例屬性,設備系統名稱
    open var systemName: String { get } // e.g. @"iOS"
     //實例屬性,設備系統版本
    open var systemVersion: String { get } // e.g. @"4.0"
     //實例屬性,設備方向
    open var orientation: UIDeviceOrientation { get } 
     //實例屬性,設備的 UUID
    @available(iOS 6.0, *)
    open var identifierForVendor: UUID? { get } 
     //實例屬性,一個布爾值,指示接收器是否生成方向通知(true)或不指定(false)
    open var isGeneratingDeviceOrientationNotifications: Bool { get }
     // 開始設備方向更改通知的生成。
    open func beginGeneratingDeviceOrientationNotifications() // nestable
     // 結束設備方向更改通知的生成。
    open func endGeneratingDeviceOrientationNotifications()

    // 指示是否啓用電池監控(true)或(否false)
    @available(iOS 3.0, *)
    open var isBatteryMonitoringEnabled: Bool // default is NO

    // 電池的狀態
    @available(iOS 3.0, *)
    open var batteryState: UIDeviceBatteryState { get } // UIDeviceBatteryStateUnknown if monitoring disabled

    // 電量 是個小數,用百分比展現
    @available(iOS 3.0, *)
    open var batteryLevel: Float { get } // 0 .. 1.0. 若是電池狀態未知,爲-1

    //表示是否啓用接近用戶監測(true)或不(false)。
    @available(iOS 3.0, *)
    open var isProximityMonitoringEnabled: Bool // default is NO

    // 表示接近傳感器是否接近user(true)或not(false)
    @available(iOS 3.0, *)
    open var proximityState: Bool { get } // always returns NO if no proximity detector

    // 設備是否支持接近用戶監測
    @available(iOS 4.0, *)
    open var isMultitaskingSupported: Bool { get }

    // 用戶在當前設備上使用的界面風格,是上邊的一個枚舉
    @available(iOS 3.2, *)
    open var userInterfaceIdiom: UIUserInterfaceIdiom { get }

    // 用來播放可用的鍵盤輸入點擊聲,只有用戶容許輸入聲音是纔有用
    @available(iOS 4.2, *)
    open func playInputClick() // Plays a click only if an enabling input view is on-screen and user has enabled input clicks.
}

// 協議,輸入視圖的按鍵聲音
public protocol UIInputViewAudioFeedback : NSObjectProtocol {

    // 獲取設備是否開啓鍵盤輸入聲音,若是是 YES 輸入是將會播放聲音
    optional public var enableInputClicksWhenVisible: Bool { get } // If YES, an input view will enable playInputClick.
}

// 能夠用來監聽的一些狀態。用於通知的發送,設備狀態改變時的監聽。
public func UI_USER_INTERFACE_IDIOM() -> UIUserInterfaceIdiom
extension NSNotification.Name {

    // 設備方向改變
    public static let UIDeviceOrientationDidChange: NSNotification.Name

    // 電池狀態改變
    @available(iOS 3.0, *)
    public static let UIDeviceBatteryStateDidChange: NSNotification.Name

    // 電量改變
    @available(iOS 3.0, *)
    public static let UIDeviceBatteryLevelDidChange: NSNotification.Name

    // 設備接近狀態改變
    @available(iOS 3.0, *)
    public static let UIDeviceProximityStateDidChange: NSNotification.Name
}

複製代碼

================華麗麗分割線,代碼來了===============swift

//  ViewController.swift
//  DeviceOrientation
//  Created by YHY on 2017/3/22.
//  Copyright © 2017年 太陽在線. All rights reserved.

import UIKit

class ViewController: UIViewController {
	
	var deviceInfo: [String]!
	
	@IBOutlet weak var name: UILabel!
	
	@IBOutlet weak var model: UILabel!
	
	@IBOutlet weak var localizedModel: UILabel!
	
	@IBOutlet weak var systemName: UILabel!
	
	@IBOutlet weak var systemVersion: UILabel!
	
	@IBOutlet weak var orientation: UILabel!
	
	@IBOutlet weak var batteryState: UILabel!
	
	@IBOutlet weak var batteryLevel: UILabel!
	
	@IBOutlet weak var proximityState: UILabel!
	
	@IBOutlet weak var userInterfaceIdiom: UILabel!
	
	@IBOutlet weak var multitaskingSupported: UILabel!
	
	@IBOutlet weak var identifierForVendor: UILabel!
	
	@IBOutlet weak var proximity: UILabel!
	
	var i = 0,j = 0
	
	override func viewDidLoad() {
		super.viewDidLoad()

		
		let device = UIDevice.current
		// 啓用電池監控,啓用以後有關電池的監測才能夠用
		device.isBatteryMonitoringEnabled = true
		// 啓用用戶接近
		device.isProximityMonitoringEnabled = true
		print("設備名:" + device.name)
		print("設備型號:" + device.model)
		print("設備定位型號:" + device.localizedModel)
		print("設備系統:" + device.systemName)
		print("系統版本:" + device.systemVersion)
		print("UUID:" + String(describing: device.identifierForVendor) )
		print("電量:\(UIDevice.current.batteryLevel * 100)%")
		print("是否支持接近用戶監測:" + String(device.isMultitaskingSupported))
		
		
		
                name.text = "設備名:" + device.name
                model.text = "設備型號:" + device.model
                localizedModel.text = "設備定位型號:" + device.localizedModel
                systemName.text = "設備系統:" + device.systemName
                systemVersion.text = "系統版本:" + device.systemVersion
                identifierForVendor.text = "UUID:" + String(describing: device.identifierForVendor!)
                batteryLevel.text = "電量:" + String(device.batteryLevel)
                multitaskingSupported.text = "是否支持接近用戶監測:" + String(device.isMultitaskingSupported)
		
	
		switch device.userInterfaceIdiom {
			case .carPlay:
				print("用戶界面風格:車載屏")
			    userInterfaceIdiom.text = "用戶界面風格:車載屏"
			case .pad:
				print("用戶界面風格:iPad")
			    userInterfaceIdiom.text = "用戶界面風格:iPad"
			case .phone:
				print("用戶界面風格:iPhone")
			    userInterfaceIdiom.text = "用戶界面風格:iPhone"
			case.tv:
				print("用戶界面風格: TV")
				userInterfaceIdiom.text = "用戶界面風格: TV"
			default:
				print("用戶界面風格:未知")
			    userInterfaceIdiom.text = "用戶界面風格:未知"
		}
	}
	
	override func viewWillAppear(_ animated: Bool) {
		super.viewWillAppear(animated)
		
		// 監聽設備方向變化
		NotificationCenter.default.addObserver(self, selector: #selector(change), name: .UIDeviceOrientationDidChange, object: nil)
		// 監聽電池狀態
		NotificationCenter.default.addObserver(self, selector: #selector(battery), name: .UIDeviceBatteryStateDidChange, object: nil)
		// 監聽電量
		NotificationCenter.default.addObserver(self, selector: #selector(batteryLevels), name: .UIDeviceBatteryLevelDidChange, object: nil)
		// 監聽設備是否接近用戶
		NotificationCenter.default.addObserver(self, selector: #selector(proximityStates), name: .UIDeviceProximityStateDidChange, object: nil)
		
	}
 
	func change() {
		let orienta = UIDevice.current.orientation
		print(orienta)
		
		switch orienta {
			case .faceDown:
				
			    orientation.text = "設備方向:臉朝地"
			case .faceUp:
			
			    orientation.text = "設備方向:臉朝上"
			case .landscapeLeft:
				
			    orientation.text = "設備方向:頭朝左"
			case .landscapeRight:
				
			    orientation.text = "設備方向:頭朝右"
			case .portrait:
				
			    orientation.text = "設備方向:正立"
			case .portraitUpsideDown:
				
			    orientation.text = "設備方向:倒立"
			default:
			
			    orientation.text = "設備方向:還在懵逼"
		}
		
	}
	
	func battery() {
		let batteryStatu = UIDevice.current.batteryState
		
		switch batteryStatu {
			case .charging:
				print("正在充電")
				 batteryState.text = "電池狀態:正在充電"
			case .full:
				print("滿電量")
				batteryState.text = "電池狀態:滿電量"
			case .unplugged:
				print("放電")
				batteryState.text = "電池狀態:在放電"
			default:
				print("我也不知道在幹嗎")
				batteryState.text = "電池狀態:我也不知道在幹嗎"
			}
		
	}
	
	func batteryLevels() {
		print("電量",UIDevice.current.batteryLevel)
		batteryLevel.text = "通知電量變爲:\(UIDevice.current.batteryLevel * 100)%"

	}
	
	
	func proximityStates() {
		print("是否接近用戶:",UIDevice.current.proximityState)
		if UIDevice.current.proximityState {
			i += 1
			proximity.text = "接近了用戶\(i)次"
		
		}else {
			j += 1
			proximityState.text = "離開了\(j)次"
		}
		
	}
	
	override func viewDidDisappear(_ animated: Bool) {
		super.viewDidDisappear(animated)
		
		UIDevice.current.endGeneratingDeviceOrientationNotifications()
		NotificationCenter.default.removeObserver(self)
	}

}

複製代碼

結果展現

Demo 下載bash

相關文章
相關標籤/搜索