Actually Just want to implement functionality like if new version of the app is available on AppStore then end user will be notified for update the App.
There are so many answers on google but look at below my code.
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
}
and calling this function
_ = 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)
}
}
}
Problem is that If new version of app is ready to sell and I open old version of app then popup will open and when I click on update button, It will redirect on AppStore. But on AppStore rather then display "Update" button, it display "Open" button
So I checked in my code.
When I run below URL manually on browser
http://itunes.apple.com/in/lookup?bundleId=com.mycompany.appname
Then download .txt file and got accurate App version But In my code print(a["version"] as? String ?? "") it returns wrong version number.
Where I'm going wrong? Please correct me.
NOTE: I also used http://itunes.apple.com/lookup?bundleId=com.mycompany.appname means removed country code from URL but not worked for me.