├── .gitignore ├── .swiftpm └── xcode │ └── package.xcworkspace │ └── contents.xcworkspacedata ├── LICENSE ├── Package.resolved ├── Package.swift ├── README.md ├── Sources └── AppUpdately │ ├── AppUpdateNotifier.swift │ ├── Models │ ├── AppMetadata.swift │ └── AppMetadataResults.swift │ └── UpdateStatusFetcher.swift └── Tests └── AppUpdatelyTests └── UpdateStatusFetcherTests.swift /.gitignore: -------------------------------------------------------------------------------- 1 | # Xcode 2 | # 3 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 4 | 5 | ## User settings 6 | xcuserdata/ 7 | 8 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 9 | *.xcscmblueprint 10 | *.xccheckout 11 | 12 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 13 | build/ 14 | DerivedData/ 15 | *.moved-aside 16 | *.pbxuser 17 | !default.pbxuser 18 | *.mode1v3 19 | !default.mode1v3 20 | *.mode2v3 21 | !default.mode2v3 22 | *.perspectivev3 23 | !default.perspectivev3 24 | 25 | ## Obj-C/Swift specific 26 | *.hmap 27 | 28 | ## App packaging 29 | *.ipa 30 | *.dSYM.zip 31 | *.dSYM 32 | 33 | ## Playgrounds 34 | timeline.xctimeline 35 | playground.xcworkspace 36 | 37 | # Swift Package Manager 38 | # 39 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies. 40 | # Packages/ 41 | # Package.pins 42 | # Package.resolved 43 | # *.xcodeproj 44 | # 45 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata 46 | # hence it is not needed unless you have added a package configuration file to your project 47 | # .swiftpm 48 | 49 | .build/ 50 | 51 | # CocoaPods 52 | # 53 | # We recommend against adding the Pods directory to your .gitignore. However 54 | # you should judge for yourself, the pros and cons are mentioned at: 55 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control 56 | # 57 | # Pods/ 58 | # 59 | # Add this line if you want to avoid checking in source code from the Xcode workspace 60 | # *.xcworkspace 61 | 62 | # Carthage 63 | # 64 | # Add this line if you want to avoid checking in source code from Carthage dependencies. 65 | # Carthage/Checkouts 66 | 67 | Carthage/Build/ 68 | 69 | # Accio dependency management 70 | Dependencies/ 71 | .accio/ 72 | 73 | # fastlane 74 | # 75 | # It is recommended to not store the screenshots in the git repo. 76 | # Instead, use fastlane to re-generate the screenshots whenever they are needed. 77 | # For more information about the recommended setup visit: 78 | # https://docs.fastlane.tools/best-practices/source-control/#source-control 79 | 80 | fastlane/report.xml 81 | fastlane/Preview.html 82 | fastlane/screenshots/**/*.png 83 | fastlane/test_output 84 | 85 | # Code Injection 86 | # 87 | # After new code Injection tools there's a generated folder /iOSInjectionProject 88 | # https://github.com/johnno1962/injectionforxcode 89 | 90 | iOSInjectionProject/ 91 | -------------------------------------------------------------------------------- /.swiftpm/xcode/package.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Antoine van der Lee 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "Mocker", 6 | "repositoryURL": "https://github.com/WeTransfer/Mocker.git", 7 | "state": { 8 | "branch": null, 9 | "revision": "077c52a31f5ebb649ebe546cc77d8647760b2279", 10 | "version": "2.5.5" 11 | } 12 | } 13 | ] 14 | }, 15 | "version": 1 16 | } 17 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.5 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "AppUpdately", 8 | platforms: [ 9 | .iOS(.v13), 10 | .macOS(.v10_15) 11 | ], 12 | products: [ 13 | .library(name: "AppUpdately", targets: ["AppUpdately"]), 14 | ], 15 | dependencies: [ 16 | .package(url: "https://github.com/WeTransfer/Mocker.git", .upToNextMajor(from: "2.3.0")) 17 | ], 18 | targets: [ 19 | .target( 20 | name: "AppUpdately", 21 | dependencies: []), 22 | .testTarget( 23 | name: "AppUpdatelyTests", 24 | dependencies: ["AppUpdately", "Mocker"]), 25 | ] 26 | ) 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # AppUpdately 2 | 3 | Fetch the update status for a given app bundle identifier, without the need of any remote configuration. Simply provide your app's bundle identifier and compare the resulting update status. 4 | 5 | Supports macOS and iOS. 6 | 7 | ## Usage 8 | 9 | The fetcher automatically fetches the bundle identifier. You can use the following code example: 10 | 11 | ```swift 12 | var cancellable: AnyCancellable? 13 | cancellable = UpdateStatusFetcher().fetch { result in 14 | defer { cancellable?.cancel() } 15 | guard let status = try? result.get() else { return } 16 | 17 | switch status { 18 | case .upToDate: 19 | break 20 | case .updateAvailable(let version, let storeURL): 21 | // Use the information to present your update alert or view. 22 | } 23 | } 24 | ``` 25 | 26 | Or with [async/await](https://www.avanderlee.com/swift/async-await/): 27 | 28 | ```swift 29 | Task { 30 | let fetcher = UpdateStatusFetcher() 31 | let status = try await fetcher.fetch() 32 | 33 | switch status { 34 | case .upToDate: 35 | break 36 | case .updateAvailable(let version, let storeURL): 37 | // Use the information to present your update alert or view. 38 | } 39 | } 40 | ``` 41 | 42 | ### Update notifier 43 | You can make use of the `AppUpdateNotifier` which takes care of keeping track of seen updates. 44 | 45 | ```swift 46 | let updateNotifier = AppUpdateNotifier(userDefaults: standard) 47 | updateNotifier.updateStatusIfNeeded() 48 | 49 | print(updateNotifier.lastStatus) // For example: .upToDate 50 | ``` 51 | 52 | `AppUpdateNotifier` is an `ObservableObject` and can be used in SwiftUI. `lastStatus` is a published property which can be observed. 53 | 54 | You can use `updateNotifier.triggerPresenterIfNeeded(presenter: ...)` to use as a simple trigger for presenting a view in response to an available update. 55 | 56 | ## Installation 57 | ### Swift Package Manager 58 | 59 | Add `https://github.com/AvdLee/AppUpdately.git` within Xcode's package manager. 60 | 61 | #### Manifest File 62 | 63 | Add AppUpdately as a package to your `Package.swift` file and then specify it as a dependency of the Target in which you wish to use it. 64 | 65 | ```swift 66 | import PackageDescription 67 | 68 | let package = Package( 69 | name: "MyProject", 70 | platforms: [ 71 | .macOS(.v10_15) 72 | .iOS(.v13) 73 | ], 74 | dependencies: [ 75 | .package(url: "https://github.com/AvdLee/AppUpdately.git", .upToNextMajor(from: "1.0.0")) 76 | ], 77 | targets: [ 78 | .target( 79 | name: "MyProject", 80 | dependencies: ["AppUpdately"]), 81 | .testTarget( 82 | name: "MyProjectTests", 83 | dependencies: ["MyProject"]), 84 | ] 85 | ) 86 | ``` 87 | 88 | ## License 89 | 90 | AppUpdately is available under the MIT license. See the LICENSE file for more info. 91 | -------------------------------------------------------------------------------- /Sources/AppUpdately/AppUpdateNotifier.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | import SwiftUI 3 | import Combine 4 | 5 | /// An instance taking care of presenting a new update. 6 | public protocol AppUpdatePresenter { 7 | 8 | /// Will be called when an available update should be presented to 9 | /// the user. 10 | /// This method is only called once per version to prevent update spam. 11 | /// - Returns: `true` if presenting succeeded. You can return `false` if you want to postpone the app update presentation. 12 | func presentUpdate(for version: String, storeURL: URL) -> Bool 13 | } 14 | 15 | /// Monitoring for app updates and automatically refresh the status 16 | /// whenever the app becomes active. 17 | /// 18 | /// Checks only once per day. 19 | public final class AppUpdateNotifier: ObservableObject { 20 | 21 | public static let standard = AppUpdateNotifier(userDefaults: .standard) 22 | 23 | /// The last known status. Defaults to `upToDate`. 24 | @Published 25 | public private(set) var lastStatus: UpdateStatusFetcher.Status = .upToDate 26 | 27 | private let userDefaults: UserDefaults 28 | 29 | /// The last time a fetch was made. 30 | private var lastFetch: Date? 31 | 32 | /// The last time we notified. Defaults to a very old date. 33 | private var lastNotify: Date { 34 | get { 35 | let timeInterval = userDefaults.double(forKey: "app_updately_last_notify") 36 | return Date(timeIntervalSince1970: timeInterval) 37 | } 38 | set { 39 | userDefaults.set(newValue.timeIntervalSince1970, forKey: "app_updately_last_notify") 40 | } 41 | } 42 | private lazy var fetcher: UpdateStatusFetcher = UpdateStatusFetcher() 43 | private var cancellable: AnyCancellable? 44 | 45 | init(userDefaults: UserDefaults) { 46 | self.userDefaults = userDefaults 47 | } 48 | 49 | /// Fetches the status if allowed to fetch. Only one fetch per day takes place. 50 | public func updateStatusIfNeeded() { 51 | guard allowedToFetch() else { return } 52 | lastFetch = Date() 53 | cancellable = fetcher.fetch { result in 54 | guard let status = try? result.get() else { 55 | return 56 | } 57 | DispatchQueue.main.async { 58 | self.lastStatus = status 59 | } 60 | } 61 | } 62 | 63 | /// Can be used to trigger a presenter if the user didn't see an update view for the available update yet. 64 | public func triggerPresenterIfNeeded(updatePresenter: AppUpdatePresenter) { 65 | guard case let UpdateStatusFetcher.Status.updateAvailable(version, storeURL) = lastStatus else { 66 | return 67 | } 68 | 69 | let userDefaultsKey = "app_updately_notified_\(version)" 70 | let didNotifyForVersion = userDefaults.bool(forKey: userDefaultsKey) 71 | guard !didNotifyForVersion else { return } 72 | guard updatePresenter.presentUpdate(for: version, storeURL: storeURL) else { return } 73 | userDefaults.set(true, forKey: userDefaultsKey) 74 | } 75 | 76 | private func allowedToFetch() -> Bool { 77 | guard let lastFetch = lastFetch else { 78 | return true 79 | } 80 | return lastFetch < Date().addingTimeInterval(-86000) // -1 day 81 | } 82 | } 83 | -------------------------------------------------------------------------------- /Sources/AppUpdately/Models/AppMetadata.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | // A list of App metadata with details around a given app. 4 | struct AppMetadata: Codable { 5 | /// The URL pointing to the App Store Page. 6 | /// E.g: https://apps.apple.com/br/app/rocketsim-for-xcode/id1504940162?mt=12&uo=4 7 | let trackViewUrl: URL 8 | 9 | /// The current latest version available in the App Store. 10 | let version: String 11 | } 12 | -------------------------------------------------------------------------------- /Sources/AppUpdately/Models/AppMetadataResults.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | struct AppMetadataResults: Codable { 4 | let results: [AppMetadata] 5 | } 6 | -------------------------------------------------------------------------------- /Sources/AppUpdately/UpdateStatusFetcher.swift: -------------------------------------------------------------------------------- 1 | import Combine 2 | import Foundation 3 | 4 | /// Fetches the latest update using a lookup and compares it to 5 | /// the current app version. 6 | /// A status is returned based on comparing both versions. 7 | public struct UpdateStatusFetcher { 8 | public enum Status: Equatable { 9 | /// The current app version is newer than the latest App Store. 10 | case newerVersion 11 | case upToDate 12 | case updateAvailable(version: String, storeURL: URL) 13 | } 14 | 15 | public enum FetchError: LocalizedError { 16 | case metadata 17 | case bundleShortVersion 18 | 19 | public var errorDescription: String? { 20 | switch self { 21 | case .metadata: 22 | return "Metadata could not be found" 23 | case .bundleShortVersion: 24 | return "Bundle short version could not be found" 25 | } 26 | } 27 | } 28 | 29 | let url: URL 30 | private let bundleIdentifier: String 31 | private let decoder: JSONDecoder = JSONDecoder() 32 | private let urlSession: URLSession 33 | 34 | var currentVersionProvider: () -> String? = { 35 | if let debugVersion = ProcessInfo.processInfo.environment["AppUpdatelyDebugVersion"] { 36 | return debugVersion 37 | } 38 | return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String 39 | } 40 | 41 | public init(bundleIdentifier: String = Bundle.main.bundleIdentifier!, urlSession: URLSession = .shared) { 42 | url = URL(string: "https://itunes.apple.com/lookup?bundleId=\(bundleIdentifier)")! 43 | self.bundleIdentifier = bundleIdentifier 44 | self.urlSession = urlSession 45 | } 46 | 47 | public func fetch(_ completion: @escaping (Result) -> Void) -> AnyCancellable { 48 | urlSession 49 | .dataTaskPublisher(for: url) 50 | .map(\.data) 51 | .decode(type: AppMetadataResults.self, decoder: decoder) 52 | .tryMap({ metadataResults -> Status in 53 | guard let appMetadata = metadataResults.results.first else { 54 | throw FetchError.metadata 55 | } 56 | return try updateStatus(for: appMetadata) 57 | }) 58 | .sink { completionStatus in 59 | switch completionStatus { 60 | case .failure(let error): 61 | print("Update status fetching failed: \(error)") 62 | completion(.failure(error)) 63 | case .finished: 64 | break 65 | } 66 | } receiveValue: { status in 67 | print("Update status is \(status)") 68 | completion(.success(status)) 69 | } 70 | } 71 | 72 | @available(iOS 15.0, *) 73 | @available(macOS 12.0, *) 74 | public func fetch() async throws -> Status { 75 | let data = try await urlSession.data(from: url).0 76 | let metadataResults = try decoder.decode(AppMetadataResults.self, from: data) 77 | guard let appMetadata = metadataResults.results.first else { 78 | throw FetchError.metadata 79 | } 80 | return try updateStatus(for: appMetadata) 81 | } 82 | 83 | private func updateStatus(for appMetadata: AppMetadata) throws -> Status { 84 | guard let currentVersion = currentVersionProvider() else { 85 | throw UpdateStatusFetcher.FetchError.bundleShortVersion 86 | } 87 | 88 | switch currentVersion.compare(appMetadata.version) { 89 | case .orderedDescending: 90 | return UpdateStatusFetcher.Status.newerVersion 91 | case .orderedSame: 92 | return UpdateStatusFetcher.Status.upToDate 93 | case .orderedAscending: 94 | return UpdateStatusFetcher.Status.updateAvailable(version: appMetadata.version, storeURL: appMetadata.trackViewUrl) 95 | } 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /Tests/AppUpdatelyTests/UpdateStatusFetcherTests.swift: -------------------------------------------------------------------------------- 1 | import XCTest 2 | @testable import AppUpdately 3 | import Mocker 4 | 5 | final class UpdateStatusFetcherTests: XCTestCase { 6 | 7 | private var fetcher: UpdateStatusFetcher! 8 | private let mockedTrackViewURL = URL(string: "https://apps.apple.com/br/app/rocketsim-for-xcode/id1504940162?mt=12&uo=4")! 9 | 10 | override func setUpWithError() throws { 11 | try super.setUpWithError() 12 | 13 | let configuration = URLSessionConfiguration.default 14 | configuration.protocolClasses = [MockingURLProtocol.self] 15 | let urlSession = URLSession(configuration: configuration) 16 | fetcher = UpdateStatusFetcher(bundleIdentifier: "com.swiftlee.rocketsim", urlSession: urlSession) 17 | } 18 | 19 | override func tearDownWithError() throws { 20 | try super.tearDownWithError() 21 | fetcher = nil 22 | } 23 | 24 | func testSameVersion() { 25 | mock(currentVersion: "2.0.0", latestVersion: "2.0.0") 26 | XCTAssertStatusEquals(.upToDate) 27 | } 28 | 29 | func testNewerVersion() { 30 | mock(currentVersion: "3.0.0", latestVersion: "2.0.0") 31 | XCTAssertStatusEquals(.upToDate) 32 | } 33 | 34 | func testOlderVersion() { 35 | mock(currentVersion: "1.0.0", latestVersion: "2.0.0") 36 | XCTAssertStatusEquals(.updateAvailable(version: "2.0.0", storeURL: mockedTrackViewURL)) 37 | } 38 | 39 | @available(macOS 12.0, *) 40 | func testSameVersionAsync() async throws { 41 | mock(currentVersion: "2.0.0", latestVersion: "2.0.0") 42 | let status = try await fetcher.fetch() 43 | XCTAssertEqual(status, .upToDate) 44 | } 45 | 46 | @available(macOS 12.0, *) 47 | func testNewerVersionAsync() async throws { 48 | mock(currentVersion: "3.0.0", latestVersion: "2.0.0") 49 | let status = try await fetcher.fetch() 50 | XCTAssertEqual(status, .upToDate) 51 | } 52 | 53 | @available(macOS 12.0, *) 54 | func testOlderVersionAsync() async throws { 55 | mock(currentVersion: "1.0.0", latestVersion: "2.0.0") 56 | let status = try await fetcher.fetch() 57 | XCTAssertEqual(status, .updateAvailable(version: "2.0.0", storeURL: mockedTrackViewURL)) 58 | } 59 | } 60 | 61 | extension UpdateStatusFetcherTests { 62 | func XCTAssertStatusEquals(_ expectedStatus: UpdateStatusFetcher.Status, function: String = #function, line: UInt = #line) { 63 | let expectation = expectation(description: "Status should be fetched") 64 | let cancellable = fetcher.fetch { result in 65 | switch result { 66 | case .success(let status): 67 | XCTAssertEqual(status, expectedStatus, line: line) 68 | case .failure(let error): 69 | XCTFail("Fetching failed with \(error)") 70 | } 71 | expectation.fulfill() 72 | } 73 | addTeardownBlock { 74 | cancellable.cancel() 75 | } 76 | wait(for: [expectation], timeout: 10.0) 77 | } 78 | 79 | func mock(currentVersion: String, latestVersion: String) { 80 | fetcher.currentVersionProvider = { 81 | currentVersion 82 | } 83 | Mock(url: fetcher.url, dataType: .json, statusCode: 200, data: [.get: mockedResult(for: latestVersion).jsonData]) 84 | .register() 85 | } 86 | 87 | func mockedResult(for version: String) -> AppMetadataResults { 88 | AppMetadataResults(results: [ 89 | .init(trackViewUrl: mockedTrackViewURL, version: version) 90 | ]) 91 | } 92 | } 93 | 94 | public extension Encodable { 95 | /// Returns a `Data` representation of the current `Encodable` instance to use for mocking purposes. Force unwrapping as it's only used for tests. 96 | var jsonData: Data { 97 | let encoder = JSONEncoder() 98 | return try! encoder.encode(self) 99 | } 100 | } 101 | --------------------------------------------------------------------------------