Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> iOS

Cách phát hiện phiên bản iOS đang chạy trên thiết bị

Khi phát triển app iOS, đôi khi cần biết phiên bản iOS trên thiết bị người dùng để xử lý tương thích tính năng. Cách đơn giản nhất:

Lấy phiên bản iOS

let systemVersion = UIDevice.current.systemVersion
print("Phiên bản iOS: \(systemVersion)")  // Ví dụ: "16.4"

So sánh phiên bản (Best Practice)

Không nên so sánh chuỗi trực tiếp (ví dụ: systemVersion >= "13.0" sai vì "13.0" < "2.0" theo alphabet).

Dùng OperatingSystemVersion hoặc #available:

Cách 1: #available (Compile-time, khuyến khích)

if #available(iOS 13.0, *) {
    // Code chỉ chạy trên iOS 13+
    // Dark Mode, Sign in with Apple, SwiftUI...
} else {
    // Fallback iOS 12-
}

Cách 2: OperatingSystemVersion (Runtime)

let currentVersion = ProcessInfo.processInfo.operatingSystemVersion
if currentVersion.majorVersion >= 13 {
    // iOS 13+
}

Cách 3: So sánh version string an toàn

let version = UIDevice.current.systemVersion
if version.compare("13.0", options: .numeric) != .orderedAscending {
    // version >= 13.0
}

Kết quả ví dụ

System Version – 12.0

Lưu ý: systemVersion trả về String (ví dụ "16.4.1"). Dùng #available cho compile-time check (an toàn nhất), OperatingSystemVersion cho logic runtime phức tạp.