seong_hye, the developer

SwiftUI) 어플 자동 업데이트 기능에 대해 정리하기 본문

IOS/SwiftUI

SwiftUI) 어플 자동 업데이트 기능에 대해 정리하기

seong_hye 2024. 3. 27.

 

📘자동 업데이트

새로운 버전이 있을 때 사용자에게 알리고 업데이트를 유도하는 기능에 대해 정리해보려 함


🔹기본 흐름

1. 현재 앱 버전 확인

Bundle.main.infoDictionary를 통해 현재 버전 추출

 

2. 서버 / API에서 최신 버전확인

App Sotre API를 통해 버전 정보 확인

 

3. 버전 비교

현재 사용자 어플 버전(1번 값)과 앱 스토어 버전(2번 값)을 비교

 

4. 사용자에게 업데이트 유도

버전 비교(3번 값)가 다를 경우 앱스토어로 이동하도록 유도


🔹사용자가 사용중인 현재 버전 가져오기

let current = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return }

 

🔹서버(App Store)에 올라와 있는 버전 가져오기

func fetchLatestVersion(bundleId: String, completion: @escaping (String?) -> Void {
	let url = URL(string: "https://itunes.apple.com/lookup?bundleId=\(bundleId)&timestamp=\(Date().timeIntervalSince1970)")!
    URLSession.shared.dataTask(with: url) {data, _, _ in
    	guard let data = data,
        	let result = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
            let appStoreVersion = results.first?["version"] as? String else {
            	completion(nil)
                return
            }
            compeletion(appStoreVersion)
    }.resume()
}

 

🔹버전 비교

사람마다 버전 올리는 방법이 다름

ex) 1.1 -> 1.2 / 1.1 -> 1.1.1

숫자로만 비교하긴 어려워서 .이 추가된 경우에 따라 값을 수정해 비교할 수 있도록 작성함

func isUpdateAvailable(current: String, latest: String) -> ComparisonResult {
	let currentNum = current.split(separator: ".").map { Int($0) ?? 0 }
    let latestNum = latest.split(separator: ".").map { Int($0) ?? 0 }
    let maxCount = max(currentNum.count, latestNum.count)
    
    for i in 0..<maxCount {
    	let part1 = i < currentNum.count ? currentNum[i] : 0
        let part2 = i < latestNum.count ? latestNum[i] : 0
        
        if part1 < part2 { return .orderedAscending }
        if part1 > part2 { return .orderedDescending }
    }
    return .orderedSame
}

 

해당

func checkForUpdate(completion: @escaping (Bool) -> Void) {
	let bundleId = Bundle.main.bundleIdentifier ?? ""
    fetchLatestVersion(bundleId: bundleId) { latestVersion in
    	guard let latest = latestVersion,
              let current = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String else { return }
              
		completion(self.isUpdateAvailable(current: current, latest: latest) == .orderedAscending)
    }
}


🔹Alert으로 사용자에게 알리기

앱이 최신 버전이 아닌 경우 alert를 띄우고사용자가 alert의 확인 버튼을 누르게 되면 해당 앱의 앱 스토어 페이지로 연동되도록 함

struct ContentView: View {
	@State private var showUpdateAlert = false
    
    var body: some View {
    	VStack {
        	LaucnScreentView()
            	.onAppear {
                	self.checkForUpdate { result in
                    	if result {
                        	self.showUpdateAlert = true
                        } else {
                        	... // 앱 관련 내용
                        }
                }
        }
        .alert("새로운 버전이 출시되었습니다.", isPresented: $showUpdateAlert) {
        	Button("업데이트") {
            	if let url = URL(string: "https://apps.apple.com/app/id(앱 개인번호)") {
                	UIApplication.shared.open(url)
                }
            }
        } message: {
        	Text("최신 기능을 사용하시려면 앱을 업데이트하세요.")
        }
    }
}

 

 

🔍 APP Store로 앱 위치 보여줄 때 번호 아는 방법

1. AppStore에 들어가 해당 어플의 URL 복사해서 사용하기

 

 

2. Apple 개발자 홈페이지로 들어가 해당 앱의 정보에서 Apple ID 가져오기


 

Comments