스위프트 빌드 버전과 빌드 데이트 구하기

프로그래밍/iOS 관련2018. 4. 2. 13:48

안녕하세요. 개발자 드리머즈입니다.


iOS 앱에서 앱의 버전과 빌드 데이트를 제공하는 건 아주 일반적입니다. 이를 통해 어느 버전을 사용하고 있는지 언제 만들어진 것인지 확인을 할 수 있습니다.

이번 포스팅에선 앱의 버전과 빌드 데이트 구하는 방법에 대해 보겠습니다.


앱의 버전 구하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var resourceFileDictionary: NSDictionary?
//Load content of Info.plist into resourceFileDictionary dictionary
if let path = Bundle.main.path(forResource: "Info", ofType: "plist") {
    resourceFileDictionary = NSDictionary(contentsOfFile: path)
}
 
if let resourceFileDictionaryContent = resourceFileDictionary {
    
    // Get something from our Info.plist like MinimumOSVersion
    //print("MinimumOSVersion = \(resourceFileDictionaryContent.object(forKey: "MinimumOSVersion")!)")
    
    //Or we can print out entire Info.plist dictionary to preview its content
    //print(resourceFileDictionaryContent)
    
    cell.lblLeft.text = "버전"
    cell.lblRight.text = String(describing: resourceFileDictionaryContent.object(forKey: "CFBundleShortVersionString")!+ "(" + String(describing: resourceFileDictionaryContent.object(forKey: "CFBundleVersion")!+ ")"
}
cs


위 코드를 사용하면 앱의 버전을 구할 수 있습니다.


Xcode에서 Version과 Build가 위처럼 되어있다면

위 코드에서 cell.lblRight.text는 0.4.2(0)의 값을 가지게 됩니다.

(cell.lblLeft와 cell.lblRight를 수정해서 사용해야 함)


코드를 살펴보면 알겠지만 ket를 달리하면 빌드 버전 뿐만 아니라 Info.plist에 있는 다른 속성?의 값들도 구할 수 있습니다.


앱의 빌드 데이트 구하기


1
2
3
4
5
6
7
8
9
var compileDate:Date
{
    let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as? String ?? "Info.plist"
    if let infoPath = Bundle.main.path(forResource: bundleName, ofType: nil),
        let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
        let infoDate = infoAttr[FileAttributeKey.creationDate] as? Date
    { return infoDate }
    return Date()
}
cs

swift파일에 위의 변수를 정의합니다.


1
2
3
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
cell.lblRight.text = dateFormatter.string(for: compileDate)
cs

그 다음에 위와 같은 코드를 사용하면

cell.lblRight.text는 2018-04-02와 같은 값을 가지게 됩니다.

(cell.lblRight는 수정해서 사용해야 함)


참고

스택오버플로우의 어느 질문글

작성자

Posted by 드리머즈

관련 글

댓글 영역