1. 程式人生 > >Swift-App版本更新

Swift-App版本更新

struct VersionInfo {
    var url: String        //下載應用URL
    var title: String       //title
    var message: String       //提示內容
    var must_update: Bool  //是否強制更新
    var version: String     //版本
}
    
class VersionManager: NSObject {
    
    //本地版本
   private static func localVersion() -> String? {
        return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
    }
    
    static func versionUpdate() {
        //1 請求服務端資料,並進行解析,得到需要的資料
        //2 版本更新
        handleUpdate(VersionInfo(url: "應用下載地址", title: "有新版本啦!", message: "提示更新內容,解決了xxx等一系列問題,新增了xxx等功能!", must_update: false, version: "3.5"))
    }
    
    /// 版本更新
   private static func handleUpdate(_ info: VersionInfo) {
        guard let localVersion = localVersion()else { return }
        if isIgnoreCurrentVersionUpdate(info.version) { return }
        if versionCompare(localVersion: localVersion, serverVersion: info.version) {
            let alert = UIAlertController(title: info.title, message: info.message, preferredStyle: .alert)
            let update = UIAlertAction(title: "立即更新", style: .default, handler: { action in
                UIApplication.shared.open(URL(string: info.url)!)
            })
            alert.addAction(update)
            if !info.must_update { //是否強制更新
                let cancel = UIAlertAction(title: "忽略此版本", style: .cancel, handler: { action in
                    UserDefaults.standard.set(info.version, forKey: "IgnoreCurrentVersionUpdate")
                })
                alert.addAction(cancel)
            }
            if let vc = UIApplication.shared.keyWindow?.rootViewController {
                vc.present(alert, animated: true, completion: nil)
            }
        }
    }
    
   // 版本比較
   private static func versionCompare(localVersion: String, serverVersion: String) -> Bool {
        let result = localVersion.compare(serverVersion, options: .numeric, range: nil, locale: nil)
        if result == .orderedDescending || result == .orderedSame{
            return false
        }
            return true
    }
    
    // 是否忽略當前版本更新
    private static func isIgnoreCurrentVersionUpdate(_ version: String) -> Bool {
        return UserDefaults.standard.string(forKey: "IgnoreCurrentVersionUpdate") == version
    }
}
簡單說明: 1 程式碼的實現很簡單,上面只是簡單寫了一個測試資料,真正的資料需要自己在每次程式啟動之後向服務端請求資料。 2 提供了獲取本地版本、版本更新、版本比較、是否忽略當前版本更新等4個方法。isIgnoreCurrentVersionUpdate方法是表示當用戶選擇忽略版本之後下次啟動程式,對於當前版本不再進行更新提示 Swift有對應的版本更新庫(Siren),有需要的可以參考和使用。