iOS实现对比App版本提示用户升级

如果要在app里加入提醒用户升级的功能,只需要几个步骤:

  1. 获取用户本地app的版本号
  2. 获取App Store上本app的版本号
  3. 做对比,如果版本号不同则提示用户升级

首先定义三个方法:

//弹出Alert窗口,传入一个url参数,可以是app在store的地址,引导用户更新.
func sendAlert(url:String) {
    
    let alertController = UIAlertController(title: "系统提示",
                                            message: "应用有最新版本了,请前往升级.", preferredStyle: .alert)
    let cancelAction = UIAlertAction(title: "取消", style: .cancel, handler: nil)
    let okAction = UIAlertAction(title: "好的", style: .default, handler: {
        action in
        UIApplication.shared.openURL(NSURL(string: url) as! URL) //跳转到app store对应地址
        
    })
    alertController.addAction(cancelAction)
    alertController.addAction(okAction)
    self.present(alertController, animated: true, completion: nil)
    
}


//获取本地的版本号
func getNowAppVersion() -> String {
    
    var listData: NSDictionary = NSDictionary()
    
    let filePath = Bundle.main.path(forResource: "Info.plist", ofType:nil )
    listData = NSDictionary(contentsOfFile: filePath!)!
    
    return  listData["CFBundleVersion"]!  as! String
    
}

//获取APP Store上的版本号,参数id是app store上的id
func getStoreAppVersion (id:String) -> String {
    
    let appurl = "https://itunes.apple.com/lookup?id=" + id
    
    do{
        
        let jsonData = NSData(contentsOf: NSURL(string: appurl)  as! URL)
        
        let json = try JSONSerialization.jsonObject(with: jsonData as! Data, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary
        
        let res = json["results"] as! NSArray
        
        let xx = res[0] as! NSDictionary
        
        return xx["version"]! as! String
        
        
    }  catch {
        NSLog("JSON解析失败")
    }
    return "getAppVersion error"
}

在启动ViewController里做对比版本操作即可达到标题的目的:

    
    override func viewDidAppear(_ animated: Bool){
        super.viewDidAppear(animated)
        
        let url = "app的地址,用户在弹出框确认更新时可以直接跳转过去"
        let id = "xxxxxxx"
        
        if getNowAppVersion()  == getStoreAppVersion(id: id) {
            NSLog("版本号相同")
        } else {
            NSLog("版本号不同")
            sendAlert(url: url)
        }
    
    }

这里有个小坑:
如果开发时填写的版本号是整数,例如1. 则从app store上获取的版本号会是1.0 , 而在用户本地获取的是1, 对比就失败了. 所以最好是在开发时,版本号填写精确到小数点后1位.


更新:

这样提交审核会被拒...别问我是怎么知道的.....(>﹏<)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,263评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,355评论 19 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 14,196评论 4 61
  • 假期第四周读了《正面管教》第十章摆脱家庭作业的困扰、第十一、十二章班会的8项技能。 1.如果一个孩子做得不好,随后...
    于向雨阅读 2,773评论 0 0
  • 对于我们普通的朋友来说中秋节离我们很远,但是在电商届血拼的不是一般的激烈了! 不知道有朋友知道不:前段时间的天猫上...
    姑苏夜郎阅读 6,450评论 0 0