iOS (實現檢查更新功能時)獲取App最新版本號

幕布_w發表於2024-05-18
func getAppVersionNumber() {
    let appId = "app的Id號"
    // 這裡要注意,國內App要使用"https://itunes.apple.com/cn/lookup?id="
    // 如果使用"https://itunes.apple.com/lookup?id="這個則獲取不到版本號
    let urlStr = String.init(format:"https://itunes.apple.com/cn/lookup?id=%@", appId)
    let url = URL(string: urlStr)
    URLSession.shared.dataTask(with: url) { (data, response, error) in
        if let data = data {
            do {
                if let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any],
                   let results = jsonObject["results"] as? [Any],
                   let firstResult = results.first as? [String: Any],
                   let version = firstResult["version"] as? String {
                    print("Latest version: \(version)")
                }
            } catch {
                print("Error parsing JSON: \(error)")
            }
        }
    }.resume()
}

相關文章