Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active December 29, 2023 05:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/d8ba462f7dd86d47336e2c4a2414119c to your computer and use it in GitHub Desktop.
Save TuenTuenna/d8ba462f7dd86d47336e2c4a2414119c to your computer and use it in GitHub Desktop.
앱스토어 버전 체크

앱 버전 체커

import Foundation
import Alamofire

extension String {
    func versionCompare(_ otherVersion: String) -> ComparisonResult {
        let versionDelimiter = "."

        var versionComponents = self.components(separatedBy: versionDelimiter) // <1>
        var otherVersionComponents = otherVersion.components(separatedBy: versionDelimiter)

        let zeroDiff = versionComponents.count - otherVersionComponents.count // <2>

        if zeroDiff == 0 { // <3>
            // Same format, compare normally
            return self.compare(otherVersion, options: .numeric)
        } else {
            let zeros = Array(repeating: "0", count: abs(zeroDiff)) // <4>
            if zeroDiff > 0 {
                otherVersionComponents.append(contentsOf: zeros) // <5>
            } else {
                versionComponents.append(contentsOf: zeros)
            }
            return versionComponents.joined(separator: versionDelimiter)
                .compare(otherVersionComponents.joined(separator: versionDelimiter), options: .numeric) // <6>
        }
    }
}

class VersionCheck {

    public static let shared = VersionCheck()

    var newVersionAvailable: Bool?
    var appStoreVersion: String?

    func checkAppStore(callback: ((_ versionAvailable: Bool, _ version: String?)->Void)? = nil) {
        
        let ourBundleId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String
        print("ourBundleId: ", ourBundleId)
        AF.request("https://itunes.apple.com/kr/lookup?bundleId=\(ourBundleId)").responseJSON { response in
            var shouldUpdateApp: Bool = false
            var versionStr: String?
            if let json = response.value as? NSDictionary,
               let results = json["results"] as? NSArray,
               let entry = results.firstObject as? NSDictionary,
               let appVersionOnMarket = entry["version"] as? String,
               let ourVersion =  Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
            {
                
                // 오름차순이면 앱 업데이트를 해야한다.
                let compareResult = ourVersion.versionCompare(appVersionOnMarket)
                print(#file, #function, #line, "compareResult: \(self.getCompareResult(compareResult))")
                
                shouldUpdateApp = self.checkShouldUpdateApp(compareResult)
                    
                print("[앱 강제 업데이트 테스트] ourVersion: \(ourVersion)")
                print("[앱 강제 업데이트 테스트] appVersionOnMarket: \(appVersionOnMarket)")
                
                print("[앱 강제 업데이트 테스트] 앱 업데이트를 해야하는지 여부 shouldUpdateApp: \(shouldUpdateApp)")
                
                AppConfig.shared.updateAppVersionData(to: (versionOnTheMarket: appVersionOnMarket, localVersion: ourVersion))
                versionStr = appVersionOnMarket
            }

            self.appStoreVersion = versionStr
            self.newVersionAvailable = shouldUpdateApp
            callback?(shouldUpdateApp, versionStr)
        }
    }
    
    fileprivate func getCompareResult(_ result: ComparisonResult) -> String {
        print(#file, #function, #line, "")
        switch result {
        case .orderedSame: return "일치한다."
        case .orderedDescending: return "내림차순이다."
        case .orderedAscending: return "오름차순이다."
        }
    }
    
    fileprivate func checkShouldUpdateApp(_ result: ComparisonResult) -> Bool {
        print(#file, #function, #line, "")
        return result == .orderedAscending
    }
    
}

사용 예

  // 앱 버전 체크하기
  VersionCheck.shared.checkAppStore{ shouldUpdateApp, version in
      print("IS NEW VERSION AVAILABLE: shouldUpdateApp : \(shouldUpdateApp), APP STORE VERSION: \(String(describing: version))")
      if shouldUpdateApp { // 앱 업데이트 있음
          self.alertInfo = JsAlert("앱 업데이트가 있습니다.", "확인")
          return
      } else { // 앱 업데이트 없음
          DispatchQueue.main.asyncAfter(deadline: .now() + 2.1) { 
             /// 원하는 로직 처리
          }
      }
  }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment