Files
SideStore/SideStoreApp/Sources/SideStoreAppKit/Operations/Operation.swift

81 lines
1.9 KiB
Swift
Raw Normal View History

2023-03-01 00:48:36 -05:00
//
// Operation.swift
// AltStore
//
// Created by Riley Testut on 6/7/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import Foundation
2023-03-01 14:36:52 -05:00
import RoxasUIKit
2023-03-01 00:48:36 -05:00
2023-03-01 19:09:33 -05:00
public class ResultOperation<ResultType>: Operation {
2023-03-01 00:48:36 -05:00
var resultHandler: ((Result<ResultType, Error>) -> Void)?
@available(*, unavailable)
2023-03-01 19:09:33 -05:00
public override func finish() {
2023-03-01 00:48:36 -05:00
super.finish()
}
func finish(_ result: Result<ResultType, Error>) {
guard !isFinished else { return }
if isCancelled {
resultHandler?(.failure(OperationError.cancelled))
} else {
resultHandler?(result)
}
super.finish()
}
}
2023-03-01 19:09:33 -05:00
public class Operation: RSTOperation, ProgressReporting {
public let progress = Progress.discreteProgress(totalUnitCount: 1)
2023-03-01 00:48:36 -05:00
private var backgroundTaskID: UIBackgroundTaskIdentifier?
2023-03-01 19:09:33 -05:00
public override var isAsynchronous: Bool {
2023-03-01 00:48:36 -05:00
true
}
override init() {
super.init()
progress.cancellationHandler = { [weak self] in self?.cancel() }
}
2023-03-01 19:09:33 -05:00
public override func cancel() {
2023-03-01 00:48:36 -05:00
super.cancel()
if !progress.isCancelled {
progress.cancel()
}
}
2023-03-01 19:09:33 -05:00
public override func main() {
2023-03-01 00:48:36 -05:00
super.main()
let name = "com.altstore." + NSStringFromClass(type(of: self))
backgroundTaskID = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in
guard let backgroundTask = self?.backgroundTaskID else { return }
self?.cancel()
UIApplication.shared.endBackgroundTask(backgroundTask)
self?.backgroundTaskID = .invalid
}
}
2023-03-01 19:09:33 -05:00
public override func finish() {
2023-03-01 00:48:36 -05:00
guard !isFinished else { return }
super.finish()
if let backgroundTaskID = backgroundTaskID {
UIApplication.shared.endBackgroundTask(backgroundTaskID)
self.backgroundTaskID = .invalid
}
}
}