如何在 Swift5 中检查我的应用程序在 App Store 中是否有新版本?

3

我正在检查我的应用程序版本。如果有新版本,我的应用程序会收到通知,并应该在App Store屏幕中按下OK按钮。尽管我一直在检查应用程序版本,但总是出现错误。

    func isUpdateAvailable(completion: @escaping (Bool?, Error?) -> Void) throws -> URLSessionDataTask {
        guard let info = Bundle.main.infoDictionary,
            let currentVersion = info["CFBundleShortVersionString"] as? String,
            let identifier = info["CFBundleIdentifier"] as? String,
            let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(identifier)") else {
                throw IXError.invalidBundleInfo
        }
        Log.Debug(currentVersion)
        let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
            do {
                if let error = error { throw error }
                guard let data = data else { throw IXError.invalidResponse }
                let json = try JSONSerialization.jsonObject(with: data, options: [.allowFragments]) as? [String: Any]
                guard let result = (json?["results"] as? [Any])?.first as? [String: Any], let version = result["version"] as? String else {
                    throw IXError.invalidResponse
                }
                completion(version != currentVersion, nil)
            } catch {
                completion(nil, error)
            }
        }
        task.resume()
        return task
    }

使用方法

        _ = try? isUpdateAvailable { (update, error) in
            if let error = error {
                Log.Error(error)
            } else if let update = update {
                Log.Info(update)
            }
        }

这是因为我的应用程序没有应用商店的原因吗?

  1. 如果我有一个应用商店,我能得到什么响应来知道是否有版本需要更新?
  2. 如何进入应用商店?

请帮我很多。


当我提供自己的捆绑标识符时,该端点似乎对我返回空值,因此请尝试检查文件是否有任何结果。无论如何,这个解决方案似乎不太可扩展或可靠,我建议在某个地方托管一个包含版本号的文件。这会增加一些开销,但更可靠。 - David Liaw
@DavidLiaw 你是在说我使用的函数不好吗?那么请问你能给我提供一个更好的解决方案吗? - iosbegindevel
4个回答

3

是的,你使用的方法必须是已经发布的应用程序。

如果你使用了未发布的应用程序,你将得到 results = []

像这样前往 App Store

let appId = "1454358806" // Replace with your appId
let appURL = URL.init(string: "itms-apps://itunes.apple.com/cn/app/id" + appId + "?mt=8") //Replace cn for your current country

UIApplication.shared.open(appURL!, options:[.universalLinksOnly : false]) { (success) in

}

注意:

这种方法可能不是非常及时,也就是说,您刚发布的应用即使能在 App Store 中搜索到,但是结果不会立即更新。更新信息需要大约1小时或更长时间后才能得到。


谢谢你提供一个好主意。不过,在移动屏幕时,屏幕需要更改为异步模式,这样黑屏会短暂显示,然后移动到屏幕上。我该怎么做呢? - iosbegindevel
你的意思是什么?我不太理解。 - Nullable
使用“isUpdateAvailable”函数时,应禁用屏幕移动。否则,它会运行缓慢。但是,当使用异步机器时,黑屏会短暂显示,然后移动到我指定的屏幕上。 - iosbegindevel
我在哪里可以获取我的应用程序ID? - iosbegindevel
1
如果您创建了发布应用程序,则可以在账户中心中获取appId。https://developer.apple.com/account/。您是否指出进入“应用商店”之前的黑色屏幕?我会仔细检查它。 - Nullable
显示剩余4条评论

2
我已经采用这种方式来更新我的新版本。
步骤1:我已经保存了我的当前版本,即将上线。 示例:
struct appVersion {
static let version = "1.3.45"

}

第二步:检查我的应用版本是否与实际应用版本相同。
示例:
if userDefaults.value(forKey: "liveAppVersion") != nil {
        if userDefaults.string(forKey: "liveAppVersion") != appVersion.version {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1){
                self.alertUpdate(msz: ConstantStr.updateStr.val, titleStr: "Alert!", btntext: "Update") { success in
                    if success == true {
                        if let url = URL(string: "itms-apps://itunes.apple.com/app/id1462877960") {
                            UIApplication.shared.open(url)
                        }
                    }}
            }
            
        }
        
    }
    else {
        UpdateVersion.share.appUpdateAvailable { success in
            if userDefaults.string(forKey: "liveAppVersion") != appVersion.version {
                DispatchQueue.main.asyncAfter(deadline: .now() + 1){
                    self.alertUpdate(msz: ConstantStr.updateStr.val, titleStr: "Alert!", btntext: "Update") { success in
                        if success == true {
                            if let url = URL(string: "itms-apps://itunes.apple.com/app/id1462877960") {
                                UIApplication.shared.open(url)
                            }
                        }}
                }
            }
        }
    }

步骤3:此方法将从应用商店检查当前版本。
示例:
     func appUpdateAvailable(handler:@escaping(Bool?) -> ())
{
    let storeInfoURL: String = "http://itunes.apple.com/lookup?bundleId=com.test.app"
      let urlOnAppStore = NSURL(string: storeInfoURL)
        if let dataInJSON = NSData(contentsOf: urlOnAppStore! as URL) {
            // Try to deserialize the JSON that we got
            if let dict: NSDictionary = try? JSONSerialization.jsonObject(with: dataInJSON as Data, options: JSONSerialization.ReadingOptions.allowFragments) as! [String: AnyObject] as NSDictionary {
                if let results:NSArray = dict["results"] as? NSArray {
                   if let version = (results[0] as AnyObject).value(forKey: "version") {
                       userDefaults.set(version, forKey: "liveAppVersion")
                        handler(true)
 
                    }
                }
            }
        }
   }



  

对于警报方法,当点击更新按钮时,可以跳转到App Store以更新当前版本。
func alertUpdate(msz: String, titleStr : String, btntext: String,handler:@escaping(Bool?) -> ()){
    let alert = UIAlertController(title: titleStr, message: msz, preferredStyle: .alert)
   
    let ok = UIAlertAction(title: btntext, style: .default) { alert in
       handler(true)
   }
   
    alert.addAction(ok)
    self.present(alert, animated: true)
}

终于! 你可以使用这个弹出窗口进行更新 在这里输入图片描述

1

我已经通过完成处理程序完成了这个操作

func appStoreVersion(callback: @escaping (Bool,String)->Void) {
    let bundleId = Bundle.main.infoDictionary!["CFBundleIdentifier"] as! String
    Alamofire.request("https://itunes.apple.com/lookup?bundleId=\(bundleId)").responseJSON { response in
      if let json = response.result.value as? NSDictionary, let results = json["results"] as? NSArray, let entry = results.firstObject as? NSDictionary, let appStoreVersion = entry["version"] as? String{
        callback(true,appStoreVersion)
      }else{
        callback(false, "-")
        }
    }
  }

appStoreVersion 包含您在应用商店中的应用版本。请记住:当您的应用在应用商店上线时,可能需要最多 24 小时才能看到最新版本。

以下是如何使用它:

appStoreVersion { (success,version) in
            appVersion = version
            self.VersionLabel.text = "App version \(appVersion)"

        }

你可以使用成功版本来完成一些不可恢复的事情,例如你没有连接或者其他情况。你可以在这个应用程序的设置选项卡中查看它的使用方式: https://apps.apple.com/us/app/group-expenses-light/id1285557503

当我尝试使用它时,我该如何使用它? - iosbegindevel

0

我也使用了完成处理程序。

private func getAppInfo(completion: @escaping (AppInfo?, Error?) -> Void) -> URLSessionDataTask? {
    guard let identifier = Bundle.main.infoDictionary?["CFBundleIdentifier"] as? String,
        let url = URL(string: "http://itunes.apple.com/lookup?bundleId=\(identifier)") else {
            DispatchQueue.main.async {
                completion(nil, VersionError.invalidBundleInfo)
            }
            return nil
    }

private func getVersion() {
_ = getAppInfo { info, error in
                if let appStoreAppVersion = info?.version {
                    let new = appStoreAppVersion.components(separatedBy: ".")
                    if let error = error {
                        print("error getting app store version: \(error)")
                    } else {
                        print(new)
                    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接