Object-C写法:
//获取手机程序的版本号
NSString *ver = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
NSString *appId = @"1268501964";//在开发者账号中查看10位数
NSDictionary *dict = @{@"id": appId};
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
[mgr.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil]];
[mgr GET:@"https://itunes.apple.com/cn/lookup" parameters:dict progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSArray *array = responseObject[@"results"];
if (array.count != 0) {// 先判断返回的数据是否为空
NSDictionary *dict = array[0];
// 当前版本小于App Store版本
if ([dict[@"version"] compare:ver options:NSNumericSearch] == NSOrderedDescending) {
// 提示更新
if (!updateAlert.visible) {
[updateAlert show];
}
}
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
跳转AppStore更新:
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://itunes.apple.com/cn/app/%E8%8E%B1%E4%BB%98mpos/id1268501964?mt=8"]];
Swift写法:
//获取appstore上的最新版本号
let appId = "1449439909"
//获取当前手机安装使用的版本号
let localVersion:String = Bundle.main.infoDictionary!["CFBundleShortVersionString"] as! String
//post请求
httpRequest.post("http://itunes.apple.com/lookup?id=" + appId, parameters:nil, success: { (oper, data) -> Void in
if data != nil {
let dic = data as! NSDictionary
if let resultCount = dic["resultCount"] as? NSNumber {
if resultCount.intValue > 0 {
if let arr = dic["results"] as? NSArray {
if let dict = arr.firstObject as? NSDictionary {
if let version = dict["version"] as? String {
if version > localVersion {
let alertC = UIAlertController(title: "有新版本", message: "前去更新版本?", preferredStyle: .alert)
alertC.addAction(UIAlertAction(title: "去更新", style: .default, handler: { (UIAlertAction) in
self.updateApp(appId: appId)
}))
alertC.addAction(UIAlertAction(title: "下次再说", style: .cancel, handler: { (UIAlertAction) in
}))
UIApplication.shared.keyWindow?.rootViewController?.present(alertC, animated: true, completion: nil)
}
}
}
}
}
}
}
}) { (opeation, error) -> Void in
}
跳转AppStore更新:
let updateUrl:URL = URL.init(string: "https://itunes.apple.com/cn/app/%E8%8E%B1%E4%BB%98mpos/id"+appId+"?mt=8")!
if #available(iOS 10.0, *) {
UIApplication.shared.open(updateUrl, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(updateUrl)
}
|