-
-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathAndroidAPI.swift
More file actions
89 lines (73 loc) · 2.03 KB
/
AndroidAPI.swift
File metadata and controls
89 lines (73 loc) · 2.03 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
//
// AndroidAPI.swift
// SwiftAndroid
//
// Created by Alsey Coleman Miller on 6/14/25.
//
#if os(Android)
import Android
import CAndroidNDK
#endif
import SwiftJava
/// Android API Level
public struct AndroidAPI: RawRepresentable, Equatable, Hashable, Codable, Sendable {
public let rawValue: Int32
public init(rawValue: Int32) {
assert(rawValue > 0)
self.rawValue = rawValue
}
}
public extension AndroidAPI {
/// Available since API level 24. Returns the API level of the device we're actually running on.
static var current: AndroidAPI {
get throws {
AndroidAPI(rawValue: try deviceAPILevel())
}
}
}
internal extension AndroidAPI {
static func deviceAPILevel() throws -> Int32 {
#if os(Android) && canImport(CAndroidNDK)
try ndkValue().get()
#else
try jniValue()
#endif
}
/// `Build.VERSION.SDK_INT`
static func jniValue() throws -> Int32 {
do {
let javaClass = try JavaClass<Build.VERSION>.init()
return javaClass.SDK_INT
}
catch let error as Throwable {
throw error
}
catch {
fatalError("Invalid error \(error)")
}
}
/// Available since API level 24. Returns the API level of the device we're actually running on.
static func ndkValue() -> Result<Int32, Exception> {
#if os(Android) && canImport(CAndroidNDK)
let value = android_get_device_api_level()
#else
let value: Int32 = -1
#endif
guard value != -1 else {
return .failure(Exception())
}
return .success(value)
}
}
// MARK: - CustomStringConvertible
extension AndroidAPI: CustomStringConvertible {
public var description: String {
rawValue.description
}
}
// MARK: - ExpressibleByIntegerLiteral
extension AndroidAPI: ExpressibleByIntegerLiteral {
public init(integerLiteral value: Int32) {
self.init(rawValue: value)
}
}