XZ_iOS 获取App Store版本号和APP版本号并进行比较大小

1、从App Store获取版本号

 func appStoreVersion(appId: String) {
        let config = URLSessionConfiguration.default
        let session = URLSession(configuration: config)
        let url = URL(string: "https://itunes.apple.com/jp/lookup?id=\(appId)&country=CN")!
        let task = session.dataTask(with: url) { (data, response, error) in
            if let `data` = data, let dic = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                if let `dic` = dic, let results = dic["results"] as? [[String: Any]] {
                    if results.count > 0, let version = results[0]["version"] as? String {
                        self._storeVersion = version
                        if !hasUpdate {
                            _ = self.checkAppUpdate()
                        }
                    }
                }
            }
        }
        task.resume()
    }

2、获取APP版本号

var appVersion: String {
   return UserDefined.string(key: "CFBundleVersion")
}

class UserDefined {

    static func string(key: String) -> String {
        return Bundle.main.object(forInfoDictionaryKey: key) as! String
    }
}

3、比较大小

方法一:

if _storeVersion.compare(appVersion, options: String.CompareOptions.numeric) == ComparisonResult.orderedDescending {
    // App Store 版本大于 APP版本
    if !hasUpdate {
        print("弹出更新弹窗")
    }
}else {
    // App Store 版本小于 APP版本
}

方法二:

func compareVesionWithServerVersion() -> Bool {
    var storeVersionAarray = _storeVersion.components(separatedBy: ".")
    var appVersionArray = appVersion.components(separatedBy: ".")
    // 避免版本号的定义方式不同,比如,一个是 2.3,另一个是 2.4.3
    if storeVersionAarray.count > appVersionArray.count {
        appVersionArray.append("0")
    }else {
        storeVersionAarray.append("0")
    }

    for i in 0..<storeVersionAarray.count {
        let storeV = storeVersionAarray[i].intValue()
        let appV = appVersionArray[i].intValue()
          
        if storeV > appV {
            // 弹出强制更新弹窗
            return true
        }else {
            return false
        }
    }
    return false
}
发布了208 篇原创文章 · 获赞 52 · 访问量 14万+

猜你喜欢

转载自blog.csdn.net/understand_XZ/article/details/103538402