Swift【App版本更新】
阿新 • • 發佈:2018-12-25
Swift有對應的版本更新庫(Siren),有需要的可以參考和使用。
iOS開發中,有時會有這種需求,在AppStore上出現新版本時,應用內彈窗提示使用者更新.自動提示更新的實現方案分為兩種: 第一種,自己伺服器提供一個介面,通過請求,獲取app的相關的版本資訊,如:是否需要更新,以及更新的地址等資訊 第二種,就是利用蘋果的appstore 提供的相關api進行查詢更新.http://itunes.apple.com/cn/lookup?id=你的APPId 採用方案1,實現邏輯: 1: 向自己伺服器請求當前版本資訊 2: 和App當前版本進行比較,如果返回的版本比當前本地版本新,彈窗並顯示更新日誌,根據點選的按鈕,控制使用者跳轉到AppStore更新
簡單實現
效果圖:
具體程式碼實現 [javascript] view plain copy
iOS開發中,有時會有這種需求,在AppStore上出現新版本時,應用內彈窗提示使用者更新.自動提示更新的實現方案分為兩種: 第一種,自己伺服器提供一個介面,通過請求,獲取app的相關的版本資訊,如:是否需要更新,以及更新的地址等資訊 第二種,就是利用蘋果的appstore 提供的相關api進行查詢更新.http://itunes.apple.com/cn/lookup?id=你的APPId 採用方案1,實現邏輯: 1: 向自己伺服器請求當前版本資訊 2: 和App當前版本進行比較,如果返回的版本比當前本地版本新,彈窗並顯示更新日誌,根據點選的按鈕,控制使用者跳轉到AppStore更新
具體程式碼實現 [javascript] view plain copy
- struct VersionInfo {
- var url: String //下載應用URL
- var title: String //title
- var message: String //提示內容
- var must_update: Bool //是否強制更新
- var version: String //版本
- }
- class VersionManager: NSObject {
-
//本地版本
- privatestatic func localVersion() -> String? {
- return Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String
- }
- static func versionUpdate() {
- //1 請求服務端資料,並進行解析,得到需要的資料
- //2 版本更新
-
handleUpdate(VersionInfo(url: "應用下載地址", title: "有新版本啦!", message:
- }
- /// 版本更新
- privatestatic 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)
- }
- }
- }
- // 版本比較
- privatestatic func versionCompare(localVersion: String, serverVersion: String) -> Bool {
- let result = localVersion.compare(serverVersion, options: .numeric, range: nil, locale: nil)
- if result == .orderedDescending || result == .orderedSame{
- returnfalse
- }
- returntrue
- }
- // 是否忽略當前版本更新
- privatestatic func isIgnoreCurrentVersionUpdate(_ version: String) -> Bool {
- return UserDefaults.standard.string(forKey: "IgnoreCurrentVersionUpdate") == version
- }
- }