iOS使用Swift语言检查并提示更新
项目要上线了,产品要求跟安卓一样,一进去有一个提示框提示更新。虽然苹果在 Settings/iTunes Store & App Store 选项中有自动更新这一选项,而且添加版本号等等有被拒绝的危险。但是..总之我建议大家要据理力争。不过既然需求下来了,我们应该怎么做呢?
按照与之前的思路,我们是获取本地的版本号,以及从AppStore下载下来最新的版本号,两者进行比较,若本地版本号较低,则跳转至AppStore进行更新。首次使用Swift语言挑战,可能会有预知不到的错误,这样我们就分步做一下。
1. 获取本地版本号
最简单。直接上代码。
// 取出本地版本号
let localVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
通过目录列表的信息字典,取出本地版本号。
2. 获取AppStore的版本号
这个我们需要通过特定网址,请求AppStore的版本信息并解析出来。边上代码边分析:
2.1 配置网络请求
// AppStore地址(字符串)
let path = NSString(format: "http://itunes.apple.com/cn/lookup?id=%@", appStoreId) as String
// AppStore地址(URL)
let url = NSURL(string: path)
// 配置网络请求参数
let request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 10.0)
request.HTTPMethod = "POST"
这里需要说明的一点是:cachePolicy的意思是缓存机制;其类型是个枚举,有以下几项:(自我感觉跑题了..)
public enum NSURLRequestCachePolicy : UInt {
case UseProtocolCachePolicy // 默认行为
case ReloadIgnoringLocalCacheData // 不使用缓存
case ReloadIgnoringLocalAndRemoteCacheData // Unimplemented (未实现) // 不使用任何缓存
public static var ReloadIgnoringCacheData: NSURLRequestCachePolicy { get }
case ReturnCacheDataElseLoad // 使用缓存(不管它是否过期),如果缓存中没有,那从网络加载吧
case ReturnCacheDataDontLoad // 离线模式:使用缓存(不管它是否过期),但是不从网络加载
case ReloadRevalidatingCacheData // Unimplemented (未实现) // 在使用前去服务器验证
}
我们选择的是 ReloadIgnoringLocalCacheData ,也就是不使用缓存;毕竟版本号是随时更新的。
2.2 请求网络
// 开始网络请求
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue()) {
(response, data, error) in
// 声明获取的数据字典
let receiveStatusDic = NSMutableDictionary()
if data != nil {
do {
// JSON解析data
let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers)
// 取出版本号
// 判断是否resultCount为空
if let resultCount = dic["resultCount"] as? NSNumber {
// 判断resultCount的数量是否大于0
if resultCount.integerValue > 0 {
// 设置请求状态(1代表成功,0代表失败)
receiveStatusDic.setValue("1", forKey: "status")
// 判断results是否为空
if let arr = dic["results"] as? NSArray {
if let dict = arr.firstObject as? NSDictionary {
// 取出version
if let version = dict["version"] as? String {
receiveStatusDic.setValue(version, forKey: "version")
// 存网络版本号到UserDefaults里面
NSUserDefaults.standardUserDefaults().setObject(version, forKey: "Version")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
}
}
}
}catch let error {
print("checkUpdate -------- \(error)")
receiveStatusDic.setValue("0", forKey: "status")
}
}else {
receiveStatusDic.setValue("0", forKey: "status")
}
// 取出版本号后(若有则status为1,若没有则status为0),执行方法
self.performSelectorOnMainThread(#selector(self.checkUpdateWithData(_:)), withObject: receiveStatusDic, waitUntilDone: false)
}
没有使用三方库诸如AFNetWorking或者SwiftHTTP来请求网络,主要是考虑三方库的版本差异;使用的系统的 NSURLConnection 进行网络请求,不过似乎过期了,应该使用NSURLSession;使用 NSJSONSerialization 来解析JSON数据。不要看步骤多,主要用来判断数据是否为空以及添加请求结果的状态了。同时将AppStore中的版本信息缓存到NSUserDefaults中,缓存一下。最后将请求后的数据与请求状态传递至处理数据的方法中即可。
3.判断版本号
// 判断版本号
@objc private func checkUpdateWithData(data: NSDictionary) {
// 判断请求网络版本号的状态
let status = data["status"] as? String
// 取出本地版本号
let localVersion = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleShortVersionString") as! String
if status == "1" {
let storeVersion = data["version"] as! String
self.compareVersion(localVersion, storeVersion: storeVersion)
return
}
if let storeVersion = NSUserDefaults.standardUserDefaults().objectForKey("Version") as? String {
self.compareVersion(localVersion, storeVersion: storeVersion)
}
}
没啥好说的,对比两个版本号。若本地版本号较低,则执行下面的方法(跳转AppStore更新或者单纯的提醒一下用户该更新了)。
4. 更新
private func compareVersion(localVersion: String, storeVersion: String) {
if localVersion.compare(storeVersion) == NSComparisonResult.OrderedAscending {
//做你想做的事情
let alertController = UIAlertController.init(title: "更新可用", message: "\(NSBundle.mainBundle().infoDictionary!["CFBundleDisplayName"])的新版本可用。请立即更新至\(storeVersion)。", preferredStyle: UIAlertControllerStyle.Alert)
let confirmAction = UIAlertAction.init(title: "更新", style: UIAlertActionStyle.Default, handler: {
(alertAction) in
})
let nextTimeAction = UIAlertAction.init(title: "下一次", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(confirmAction)
alertController.addAction(nextTimeAction)
self.window?.rootViewController?.presentViewController(alertController, animated: true, completion: nil)
}
}
我做的是跳转AppStore更新。就这样
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2021/06/04 07:46