การดึงหมายเลข Build และ Version ของแอป iOS
ในบทความนี้เราจะเรียนรู้วิธีการดึงและแสดงหมายเลข Build และ Version ของแอป iOS โดยใช้ Swift
ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Xcode
เปิด Xcode → New Project → Single View Application → ตั้งชื่อว่า "ShowBuildAndVersion"
ขั้นตอนที่ 2: ออกแบบหน้าจอใน Main.storyboard
เพิ่ม Label 2 ตัวตามภาพประกอบ เพื่อแสดง Version และ Build number
ขั้นตอนที่ 3: เชื่อม IBOutlet สำหรับ Label ทั้งสอง
@IBOutlet weak var buildLabel: UILabel! @IBOutlet weak var versionLabel: UILabel!
ขั้นตอนที่ 4: ตั้งค่า Build และ Version ใน Project Settings
ไปที่ Target → General → ตั้งค่า Version และ Build ตามต้องการ
ขั้นตอนที่ 5: ดึงค่าจาก infoDictionary ใน viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
versionLabel.text = "Version: \(version)"
}
if let build = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
buildLabel.text = "Build: \(build)"
}
}
infoDictionary ของ main bundle จะเก็บค่าเหล่านี้ด้วย Key คือ CFBundleShortVersionString สำหรับ Version และ CFBundleVersion สำหรับ Build number
ขั้นตอนที่ 6: รันโปรเจกต์เพื่อทดสอบ
รันแอปและควรจะเห็นหมายเลข Version และ Build แสดงบน Label ตามที่ตั้งค่าไว้