实际上,只是想实现一些功能,例如,如果AppStore上提供了新版本的应用程序,则将通知最终用户更新该应用程序。
Google上有很多答案,但是请看下面我的代码。
func isUpdateAvailable(completion: @escaping (Bool?, Error?) -> Void) throws -> URLSessionDataTask {
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/in/lookup?bundleId=\(identifier)") else {
throw VersionError.invalidBundleInfo
}
print(currentVersion)
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
do {
if let error = error { throw error }
guard let data = data else { throw VersionError.invalidResponse }
let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any]
if let a = ((json?["results"] as? [Any])?.first) as? [String: Any] {
print(a["version"] as? String ?? "")
}
guard let result = (json?["results"] as? [Any])?.first as? [String: Any], let version = result["version"] as? String else {
throw VersionError.invalidResponse
}
completion(version != currentVersion, nil)
} catch {
completion(nil, error)
}
}
task.resume()
return task
}
并调用此函数
_ = try? appDelegate.isUpdateAvailable { (update, error) in
if let error = error {
print(error)
} else if let update = update {
if update {
let alert = UIAlertController(title: "New Version Available", message: "New version of application is available please update now!", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "Update", style: .default, handler: { (actionOk) in
if let url = URL(string: "itms-apps://itunes.apple.com/app/idXXXXXXXXX"),
UIApplication.shared.canOpenURL(url){
UIApplication.shared.open(url, options: [:])
}
}))
self.present(alert, animated: true, completion: nil)
}
}
}
问题是,如果新版本的应用程序已准备好出售,而我打开旧版本的应用程序,则弹出窗口将打开,当我单击更新按钮时,它将在AppStore上重定向。 但是在AppStore上,而不是显示“更新”按钮,而是显示“打开”按钮
所以我检查了我的代码。
当我在浏览器上手动在URL下运行时
http://itunes.apple.com/in/lookup?bundleId=com.mycompany.appname
然后下载 .txt 文件,并获得准确的应用版本,但是在我的代码
print(a["version"] as? String ?? "")
中,它返回了错误的版本号。我要去哪里错了?请纠正我。
注意:我也使用http://itunes.apple.com/lookup?bundleId=com.mycompany.appname表示从URL中删除了国家代码,但对我不起作用。
最佳答案
您的代码看起来正确。正如Coeur所说,Apple会逐步推出新更新,并且不会立即发布。通常在24小时后完成更新。
就个人而言,我不会采用这种方法。最好从服务器获取版本,并且您可以在发布该应用程序24小时后更新该值。您将对其有更多控制。假设您的新应用存在错误。您可以选择不提示用户更新到该版本。
侧面提示:
关于ios - iOS无法从iTunes获得准确的App版本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52291954/