检查应用更新时读取json错误

时间:2018-02-15 18:52:18

标签: ios swift

我正在使用以下代码检查更新是否可用。但它给了我错误的版本号。所以,实际上没有更新可用。

enum VersionError: Error {
    case invalidResponse, invalidBundleInfo
}

static func isUpdateAvailable() throws -> Bool {
    guard let info = Bundle.main.infoDictionary,
        let currentVersion = info["CFBundleShortVersionString"] as? String,
        let identifier = info["CFBundleIdentifier"] as? String,
        let url = URL(string: "http://itunes.apple.com/tr/lookup?bundleId=\(identifier)") else {
            throw VersionError.invalidBundleInfo
    }
    let data = try Data(contentsOf: url)
    guard let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any] else {
        throw VersionError.invalidResponse
    }
    if let result = (json["results"] as? [Any])?.first as? [String: Any], let version = result["version"] as? String {

        print("version: \(version)")   //writes 1.1
        print("currentVersion: \(currentVersion)") //writes 1.1.1
        return version != currentVersion
    }
    throw VersionError.invalidResponse
}

我手动下载了文件,版本号为1.1.1。应该如此。但代码给了我1.1。我找不出有什么问题。

顺便说一句,更新今天刚刚发布。我认为它不应该与此有关。

网址:http://itunes.apple.com/tr/lookup?bundleId=com.sahin.lingustica

1 个答案:

答案 0 :(得分:0)

在你的方法中有比较问题比较两个版本字符串使用此

version.compare(currentVersion, options: .numeric) == .orderedDescending ? true : false

我的方法有变化试试这个

static func isUpdateAvailable() throws -> Bool {
    guard let info = Bundle.main.infoDictionary,
        let currentVersion = info["CFBundleShortVersionString"] as? String,
        let identifier = info["CFBundleIdentifier"] as? String,
        let url = URL(string: "http://itunes.apple.com/tr/lookup?bundleId=\(identifier)") else {
            throw VersionError.invalidBundleInfo
    }
    let data = try Data(contentsOf: url)
    guard let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any] else {
        throw VersionError.invalidResponse
    }
    if let result = (json["results"] as? [Any])?.first as? [String: Any], let version = result["version"] as? String {

        print("version: \(version)")   //writes 1.1
        print("currentVersion: \(currentVersion)") //writes 1.1.1
        rreturn version.compare(currentVersion, options: .numeric) == .orderedDescending ? true : false
    }
    throw VersionError.invalidResponse
}