Skip to content

Instantly share code, notes, and snippets.

@AmatsuZero
Last active May 16, 2018 08:55
Show Gist options
  • Save AmatsuZero/8d3f6f91cc1e90bcc39de65098fedeb7 to your computer and use it in GitHub Desktop.
Save AmatsuZero/8d3f6f91cc1e90bcc39de65098fedeb7 to your computer and use it in GitHub Desktop.
利用iTunes接口检查是否有更新
func isLatest(id: String, callback: @escaping (Bool?, Error?) -> Void) {
var components = URLComponents(string: "http://itunes.apple.com/lookup")
components?.queryItems = [URLQueryItem(name: "id", value: id)]
var request = URLRequest(url: (components?.url!)!)
request.httpMethod = "POST"
let task = URLSession.shared.dataTask(with: request) { (data, _, error) in
guard error == nil else {
callback(nil, error)
return
}
do {
let resp = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String:Any]
let results = resp?["results"] as? [[String : Any]]
if let version = results?.first?["version"] as? String,
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
var component: Int = 0
let currComponents = currentVersion.components(separatedBy: ".")
let remoteComponents = version.components(separatedBy: ".")
var ret = false
for (index, digit) in remoteComponents.enumerated() {
if index < currComponents.count - 1 {
let cur = currComponents[index]
if digit > cur {
ret = true
break
}
}
}
callback(ret, nil)
} else {
callback(false, nil)
}
} catch(let e) {
callback(nil, e)
}
}
task.resume()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment