[iOS] Swift 강제 업데이트 Alert 설정

chaentopia·2023년 10월 16일
1
post-thumbnail

swift에서 강제 업데이트 Alert을 설정하였다.

⭐ 사용자가 앱스토어의 자동 업데이트를 활성화 하지 않은 경우 최신이 아닌 버전의 앱을 사용하게 될 수도 있다. 때문에 앱 진입 시 업데이트를 해야만 앱을 사용할 수 있도록 설정해줄 수 있다.

가장 치명적인 부분은 앱 사용에 있어서 아주 큰 이슈가 발생했을 때 강제 업데이트를 주지 않는다면 안되기 때문에 업데이트 안내 코드를 넣어주어야 한다. (예를 들면 회원가입 오류.. 예를 들면 서버 BASE URL 변경.. )

간단한 원리

현재 버전과 앱스토어의 버전을 체크하고, 앱스토어의 버전이 높을 경우 앱스토어 화면으로 전환되도록 한다.

0. 준비

당연히 앱스토어에 있는 최신 버전을 확인해야 하기 때문에 앱스토어에 올라온 상태여야 한다.

앱스토어에 올라가기 전에는 옵셔널 처리를 해줘도 좋다.

1. 앱스토어 버전 체크

// AppStoreCheck.swift

import UIKit

class AppStoreCheck {
    
    // 현재 버전 : 타겟 -> 일반 -> Version
    static let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    
    // 개발자가 내부적으로 확인하기 위한 용도 : 타겟 -> 일반 -> Build
    static let buildNumber = Bundle.main.infoDictionary?["CFBundleVersion"] as? String
    static let appStoreOpenUrlString = "itms-apps://itunes.apple.com/app/apple-store/(여기에AppID)"
    
    // 앱 스토어 최신 정보 확인
    func latestVersion() -> String? {
        let appleID = "(여기에AppID)"
        guard let url = URL(string: "https://itunes.apple.com/lookup?id=\(appleID)&country=kr"),
              let data = try? Data(contentsOf: url),
              let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any],
              let results = json["results"] as? [[String: Any]],
              let appStoreVersion = results[0]["version"] as? String else {
            return nil
        }
        return appStoreVersion
    }
    
    // 앱 스토어로 이동 -> urlStr 에 appStoreOpenUrlString 넣으면 이동
    func openAppStore() {
        guard let url = URL(string: AppStoreCheck.appStoreOpenUrlString) else { return }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }
}

2. 사용

앱스토어의 버전과 기기의 버전을 체크해서 강제 업데이트를 띄우도록 한다.
버전은 대체로 [Major].[Minor].[Patch] 의 컨벤션을 따르는데, 우리는 Major와 Minor가 바뀔 때만 강제 업데이트를 사용할 수 있도록 했다. (Patch는 사소한 버그를 수정할 때 버전업 하기로 했다.)

// SceneDelegate.swift

	// 업데이트가 필요한지 확인 후 업데이트 알럿을 띄우는 메소드
	func checkAndUpdateIfNeeded() {
        AppStoreCheck().latestVersion { marketingVersion in
            DispatchQueue.main.async {
                guard let marketingVersion = marketingVersion else {
                    print("앱스토어 버전을 찾지 못했습니다.")
                    return
                }
                
                // 현재 기기의 버전
                let currentProjectVersion = AppStoreCheck.appVersion ?? ""
                
                // 앱스토어의 버전을 .을 기준으로 나눈 것
                let splitMarketingVersion = marketingVersion.split(separator: ".").map { $0 }
                
                // 현재 기기의 버전을 .을 기준으로 나눈 것
                let splitCurrentProjectVersion = currentProjectVersion.split(separator: ".").map { $0 }
                
                if splitCurrentProjectVersion.count > 0 && splitMarketingVersion.count > 0 {
                
                    // 현재 기기의 Major 버전이 앱스토어의 Major 버전보다 낮다면 알럿을 띄운다.
                    if splitCurrentProjectVersion[0] < splitMarketingVersion[0] {
                        self.showUpdateAlert(version: marketingVersion)
                    // 현재 기기의 Minor 버전이 앱스토어의 Minor 버전보다 낮다면 알럿을 띄운다.
                    } else if splitCurrentProjectVersion[1] < splitMarketingVersion[1] {
                        self.showUpdateAlert(version: marketingVersion)
                    // Patch의 버전이 다르거나 최신 버전이라면 아무 알럿도 띄우지 않는다.
                    } else {
                        print("현재 최신 버전입니다.")
                    }
                }
            }
        }
    }
    
    // 알럿을 띄우는 메소드
    func showUpdateAlert(version: String) {
        let alert = UIAlertController(
            title: "업데이트 알림",
            message: "더 나은 서비스를 위해 옐로가 수정되었어요! 업데이트해주시겠어요?",
            preferredStyle: .alert
        )
        
        let updateAction = UIAlertAction(title: "업데이트", style: .default) { _ in
        	
            // 업데이트 버튼을 누르면 해당 앱스토어로 이동한다.
            AppStoreCheck().openAppStore()
        }
        
        alert.addAction(updateAction)
        window?.rootViewController?.present(alert, animated: true, completion: nil)
    }
// SceneDelegate.swift
...
       self.window?.makeKeyAndVisible()
       self.checkAndUpdateIfNeeded()
...

화면이 띄워질 때마다 업데이트 버전을 확인해준다.

⭐️ Background에 있다가 Foreground로 들어왔을 때도 확인을 해주기 위해 SceneDelegate의 sceneWillEnterForeground()에도 불러와준다.

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
        self.checkAndUpdateIfNeeded()
    }
profile
the pale blue dot

0개의 댓글