Skip to content

Instantly share code, notes, and snippets.

@sayler8182
Last active November 13, 2020 14:28
Show Gist options
  • Save sayler8182/6b68939d67e6960e0abab247d5ee5663 to your computer and use it in GitHub Desktop.
Save sayler8182/6b68939d67e6960e0abab247d5ee5663 to your computer and use it in GitHub Desktop.
// MARK: Updates
public class Updates: UpdatesProtocol {
enum StorageKeys: String {
case postponedVersion = "UpdatesPostponedVersion"
}
private let userDefaults = UserDefaults.standard
private let queue = DispatchQueue(label: "com.limbo.FormsUpdates", qos: .default)
private let bundleId: String
private let currentVersion: Version?
private var _appStoreVersion: Version?
private var postponedVersion: Version? {
get { return Version(self.userDefaults.object(forKey: StorageKeys.postponedVersion.rawValue) as? String) }
set { self.userDefaults.set(newValue?.description, forKey: StorageKeys.postponedVersion.rawValue) }
}
public convenience init(bundle bundleId: String,
version currentVersion: String) {
self.init(
bundle: bundleId,
version: Version(currentVersion))
}
public init(bundle bundleId: String,
version currentVersion: Version?) {
self.bundleId = bundleId
self.currentVersion = currentVersion
}
public func check(completion: @escaping ((UpdatesStatus) -> Void)) {
self.check(cancelToken: nil, completion: completion)
}
public func check(cancelToken: CancelToken?,
completion: @escaping ((UpdatesStatus) -> Void)) {
self.queue.async {
let status: UpdatesStatus = {
guard let appStore: Version = self.appStoreVersion() else { return .undefined }
guard let current: Version = self.currentVersion else { return .newVersion(appStore) }
guard appStore > current else { return .noChanges }
guard let postponed: Version = self.postponedVersion,
appStore != postponed else { return .newVersion(appStore) }
return UpdatesStatus.postponed
}()
guard cancelToken?.isCancelled != true else { return }
DispatchQueue.main.async { completion(status) }
}
}
public func reset() {
self.postponedVersion = nil
}
public func postpone() {
self.postponedVersion = self._appStoreVersion
}
private func appStoreVersion() -> Version? {
let version: Version? = {
let stringURL = String(format: "http://itunes.apple.com/lookup?bundleId=%@", self.bundleId)
guard let url = URL(string: stringURL),
let data = try? Data(contentsOf: url),
let jsonObject = try? JSONSerialization.jsonObject(with: data, options: [.allowFragments]),
let json = jsonObject as? [String: Any],
let results = json["results"] as? [Any],
let result = results.first as? [String: Any],
let version = result["version"] as? String else { return nil }
return Version(version)
}()
self._appStoreVersion = version
return version
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment