Skip to content

Instantly share code, notes, and snippets.

@wujianguo
Last active November 3, 2015 09:32
Show Gist options
  • Save wujianguo/d3e03336ad77a5fd01ea to your computer and use it in GitHub Desktop.
Save wujianguo/d3e03336ad77a5fd01ea to your computer and use it in GitHub Desktop.
ios swift check version
func checkVersion(appID: String, complete: (hasNewVersion: Bool, downloadAddr: String?) -> Void) {
NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "https://itunes.apple.com/lookup?id=\(appID)")!) { (data, response, error) -> Void in
dispatch_async(dispatch_get_main_queue()) { () -> Void in
if error != nil || data == nil {
complete(hasNewVersion: false, downloadAddr: nil)
return
}
do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
if let all = json as? NSDictionary {
if let results = all["results"] as? NSArray {
if results.count == 0 {
complete(hasNewVersion: false, downloadAddr: nil)
return
}
if let result = results.objectAtIndex(0) as? NSDictionary {
if let version = result["version"] as? String {
if let downUrl = result["trackViewUrl"] as? String {
if version != Util.curVersion {
complete(hasNewVersion: true, downloadAddr: downUrl)
return
}
}
}
}
}
}
complete(hasNewVersion: false, downloadAddr: nil)
} catch {
complete(hasNewVersion: false, downloadAddr: nil)
}
}
}.resume()
}
var curVersion: String {
if let info = NSBundle.mainBundle().infoDictionary as NSDictionary? {
let shortVersion: AnyObject? = info["CFBundleShortVersionString"]
let buildVersion: AnyObject? = info["CFBundleVersion"]
return "\(shortVersion!).\(buildVersion!)"
}
return "unknown"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment