feat(training): 为请求操作接入通用Loading
This commit is contained in:
@@ -97,6 +97,9 @@ final class TrainingRemoteReadingViewModel {
|
|||||||
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
|
/// 当前后端是否允许继续有效学习,完成或只读任务不建立新会话。
|
||||||
var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
|
var canStudy: Bool { progress?.canStudy == true && progress?.readingCompleted == false && !isInvalidated }
|
||||||
|
|
||||||
|
/// 同课程快照中已读取的正文可直接复用,页面无需为缓存切换显示请求进度。
|
||||||
|
func isSectionCached(id: String) -> Bool { bodies[id] != nil }
|
||||||
|
|
||||||
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
|
/// 首次只取元信息、目录第一页、首节正文和小型进度,不预取附件或其他小节正文。
|
||||||
func load() async {
|
func load() async {
|
||||||
guard !isLoading, !isInvalidated else { return }
|
guard !isLoading, !isInvalidated else { return }
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ final class GlobalLoadingManager {
|
|||||||
static let shared = GlobalLoadingManager()
|
static let shared = GlobalLoadingManager()
|
||||||
|
|
||||||
private var loadingCount = 0
|
private var loadingCount = 0
|
||||||
|
private var requestTokens: Set<UUID> = []
|
||||||
private weak var hostWindow: UIWindow?
|
private weak var hostWindow: UIWindow?
|
||||||
private var overlayView: GlobalLoadingOverlayView?
|
private var overlayView: GlobalLoadingOverlayView?
|
||||||
|
|
||||||
@@ -19,13 +20,14 @@ final class GlobalLoadingManager {
|
|||||||
|
|
||||||
/// 当前是否正在展示 Loading。
|
/// 当前是否正在展示 Loading。
|
||||||
var isShowing: Bool {
|
var isShowing: Bool {
|
||||||
loadingCount > 0
|
loadingCount > 0 || !requestTokens.isEmpty
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 增加 Loading 引用计数并展示遮罩。
|
/// 增加 Loading 引用计数并展示遮罩。
|
||||||
func show() {
|
func show() {
|
||||||
|
let wasShowing = isShowing
|
||||||
loadingCount += 1
|
loadingCount += 1
|
||||||
guard loadingCount == 1 else { return }
|
guard !wasShowing else { return }
|
||||||
attachOverlayIfNeeded()
|
attachOverlayIfNeeded()
|
||||||
overlayView?.present()
|
overlayView?.present()
|
||||||
}
|
}
|
||||||
@@ -34,18 +36,41 @@ final class GlobalLoadingManager {
|
|||||||
func hide() {
|
func hide() {
|
||||||
guard loadingCount > 0 else { return }
|
guard loadingCount > 0 else { return }
|
||||||
loadingCount -= 1
|
loadingCount -= 1
|
||||||
guard loadingCount == 0 else { return }
|
dismissOverlayIfIdle()
|
||||||
overlayView?.dismiss()
|
}
|
||||||
overlayView?.removeFromSuperview()
|
|
||||||
|
/// 为一次请求持有 Loading;使用令牌避免迟到回调结束其它请求的展示。
|
||||||
|
func beginRequest() -> UUID {
|
||||||
|
let token = UUID()
|
||||||
|
let wasShowing = isShowing
|
||||||
|
requestTokens.insert(token)
|
||||||
|
if !wasShowing {
|
||||||
|
attachOverlayIfNeeded()
|
||||||
|
overlayView?.present()
|
||||||
|
}
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 仅结束仍有效的请求令牌,重复结束或 hideAll 后的旧令牌均无副作用。
|
||||||
|
func endRequest(_ token: UUID) {
|
||||||
|
guard requestTokens.remove(token) != nil else { return }
|
||||||
|
dismissOverlayIfIdle()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 强制关闭所有 Loading。
|
/// 强制关闭所有 Loading。
|
||||||
func hideAll() {
|
func hideAll() {
|
||||||
|
requestTokens = []
|
||||||
loadingCount = 0
|
loadingCount = 0
|
||||||
overlayView?.dismiss()
|
overlayView?.dismiss()
|
||||||
overlayView?.removeFromSuperview()
|
overlayView?.removeFromSuperview()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func dismissOverlayIfIdle() {
|
||||||
|
guard !isShowing else { return }
|
||||||
|
overlayView?.dismiss()
|
||||||
|
overlayView?.removeFromSuperview()
|
||||||
|
}
|
||||||
|
|
||||||
private func attachOverlayIfNeeded() {
|
private func attachOverlayIfNeeded() {
|
||||||
guard let window = keyWindow else { return }
|
guard let window = keyWindow else { return }
|
||||||
hostWindow = window
|
hostWindow = window
|
||||||
|
|||||||
@@ -7,6 +7,9 @@ final class TrainingCenterViewController: TrainingBaseViewController {
|
|||||||
/// 差异化列表中的任务与考试记录标识。
|
/// 差异化列表中的任务与考试记录标识。
|
||||||
private enum Item: Hashable { case task(String), attempt(String) }
|
private enum Item: Hashable { case task(String), attempt(String) }
|
||||||
private var reloadTask: Task<Void, Never>?
|
private var reloadTask: Task<Void, Never>?
|
||||||
|
private var reloadLoadingToken: UUID?
|
||||||
|
private var moreTask: Task<Void, Never>?
|
||||||
|
private var moreLoadingToken: UUID?
|
||||||
private var searchTask: Task<Void, Never>?
|
private var searchTask: Task<Void, Never>?
|
||||||
private let service: any TrainingDataServing
|
private let service: any TrainingDataServing
|
||||||
private let viewModel = TrainingRemoteCenterViewModel()
|
private let viewModel = TrainingRemoteCenterViewModel()
|
||||||
@@ -184,6 +187,8 @@ final class TrainingCenterViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override func bindActions() {
|
override func bindActions() {
|
||||||
|
retryButton.accessibilityIdentifier = "training.center.retry"
|
||||||
|
moreButton.accessibilityIdentifier = "training.center.more"
|
||||||
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
|
refreshControl.addTarget(self, action: #selector(reloadTapped), for: .valueChanged)
|
||||||
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
|
retryButton.addTarget(self, action: #selector(reloadTapped), for: .touchUpInside)
|
||||||
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
|
viewAllButton.addTarget(self, action: #selector(viewAllTapped), for: .touchUpInside)
|
||||||
@@ -274,24 +279,67 @@ final class TrainingCenterViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func reloadTapped() {
|
@objc private func reloadTapped() {
|
||||||
|
scheduleReload(showsLoading: true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func releaseReloadLoading() {
|
||||||
|
if let token = reloadLoadingToken { endRequestLoading(token) }
|
||||||
|
reloadLoadingToken = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private func releaseMoreLoading() {
|
||||||
|
if let token = moreLoadingToken { endRequestLoading(token) }
|
||||||
|
moreLoadingToken = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private func scheduleReload(showsLoading: Bool) {
|
||||||
|
if showsLoading {
|
||||||
|
searchTask?.cancel()
|
||||||
|
searchTask = nil
|
||||||
|
}
|
||||||
reloadTask?.cancel()
|
reloadTask?.cancel()
|
||||||
reloadTask = Task { @MainActor [weak self] in await self?.reload() }
|
releaseReloadLoading()
|
||||||
|
moreTask?.cancel()
|
||||||
|
moreTask = nil
|
||||||
|
releaseMoreLoading()
|
||||||
|
let token = showsLoading ? beginRequestLoading() : nil
|
||||||
|
reloadLoadingToken = token
|
||||||
|
reloadTask = Task { @MainActor in
|
||||||
|
defer {
|
||||||
|
if let token { endRequestLoading(token) }
|
||||||
|
if reloadLoadingToken == token { reloadLoadingToken = nil }
|
||||||
|
}
|
||||||
|
await reload()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
|
@objc private func tabTapped(_ button: UIButton) { if let tab = TrainingCenterTab(rawValue: button.tag) { selectTab(tab) } }
|
||||||
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; reloadTapped() }
|
@objc private func filterTapped(_ button: UIButton) { viewModel.filter = button.tag == 0 ? .pendingExam : .completed; reloadTapped() }
|
||||||
@objc private func searchChanged() {
|
@objc private func searchChanged() {
|
||||||
viewModel.setKeyword(searchField.text ?? "")
|
viewModel.setKeyword(searchField.text ?? "")
|
||||||
reloadTask?.cancel()
|
reloadTask?.cancel()
|
||||||
|
releaseReloadLoading()
|
||||||
|
moreTask?.cancel()
|
||||||
|
moreTask = nil
|
||||||
|
releaseMoreLoading()
|
||||||
searchTask?.cancel()
|
searchTask?.cancel()
|
||||||
moreButton.isHidden = true
|
moreButton.isHidden = true
|
||||||
searchTask = Task { @MainActor [weak self] in
|
searchTask = Task { @MainActor [weak self] in
|
||||||
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
|
do { try await Task.sleep(for: .milliseconds(300)) } catch { return }
|
||||||
self?.reloadTapped()
|
self?.scheduleReload(showsLoading: false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@objc private func moreTapped() {
|
@objc private func moreTapped() {
|
||||||
Task { @MainActor [weak self] in
|
guard moreTask == nil, viewModel.hasMore, !viewModel.isLoading, !viewModel.isLoadingMore else { return }
|
||||||
guard let self else { return }
|
let token = beginRequestLoading()
|
||||||
|
moreLoadingToken = token
|
||||||
|
moreTask = Task { @MainActor in
|
||||||
|
defer {
|
||||||
|
endRequestLoading(token)
|
||||||
|
if moreLoadingToken == token {
|
||||||
|
moreLoadingToken = nil
|
||||||
|
moreTask = nil
|
||||||
|
}
|
||||||
|
}
|
||||||
await viewModel.loadMore(service: service)
|
await viewModel.loadMore(service: service)
|
||||||
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
|
if viewModel.isIdentityInvalid { navigationController?.popToRootViewController(animated: false); return }
|
||||||
applyState()
|
applyState()
|
||||||
|
|||||||
@@ -26,6 +26,13 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
private var contentIsReady = false
|
private var contentIsReady = false
|
||||||
private var contentLoadFailed = false
|
private var contentLoadFailed = false
|
||||||
private var pageIsVisible = false
|
private var pageIsVisible = false
|
||||||
|
private var userRequestID: UUID?
|
||||||
|
|
||||||
|
/// 用户操作独占的请求票据;缓存复用仍防重复操作,但不展示全局进度。
|
||||||
|
private struct UserRequest {
|
||||||
|
let id: UUID
|
||||||
|
let loadingToken: UUID?
|
||||||
|
}
|
||||||
|
|
||||||
/// 当前任务标识,成绩页可复用已有课程页面。
|
/// 当前任务标识,成绩页可复用已有课程页面。
|
||||||
var taskID: String { viewModel.taskID }
|
var taskID: String { viewModel.taskID }
|
||||||
@@ -106,10 +113,16 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
override func viewDidAppear(_ animated: Bool) {
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
super.viewDidAppear(animated)
|
super.viewDidAppear(animated)
|
||||||
pageIsVisible = true
|
pageIsVisible = true
|
||||||
if viewModel.task == nil { loadCourse() }
|
let previousContent = contentTask
|
||||||
else {
|
contentTask = Task { @MainActor [weak self] in
|
||||||
contentTask = Task { @MainActor [weak self] in
|
guard let self else { return }
|
||||||
guard let self else { return }
|
await previousContent?.value
|
||||||
|
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self,
|
||||||
|
userRequestID == nil else { return }
|
||||||
|
if viewModel.task == nil { loadCourse() }
|
||||||
|
else if viewModel.currentSection == nil, let id = viewModel.currentSectionID { selectSection(id) }
|
||||||
|
else {
|
||||||
|
if contentNavigation == nil { renderCurrentSection() }
|
||||||
await viewModel.refreshProgress()
|
await viewModel.refreshProgress()
|
||||||
applyState()
|
applyState()
|
||||||
resumeReading()
|
resumeReading()
|
||||||
@@ -120,6 +133,7 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
override func viewWillDisappear(_ animated: Bool) {
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
super.viewWillDisappear(animated)
|
super.viewWillDisappear(animated)
|
||||||
pageIsVisible = false
|
pageIsVisible = false
|
||||||
|
contentTask?.cancel()
|
||||||
pauseReading()
|
pauseReading()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -131,20 +145,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func loadCourse() {
|
private func loadCourse() {
|
||||||
|
guard let request = beginUserRequest(showsLoading: true) else { return }
|
||||||
pauseReading()
|
pauseReading()
|
||||||
contentIsReady = false
|
contentIsReady = false
|
||||||
contentLoadFailed = false
|
contentLoadFailed = false
|
||||||
contentNavigation = nil
|
contentNavigation = nil
|
||||||
contentTask = Task { @MainActor [weak self] in
|
contentTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
await viewModel.load()
|
await performUserRequest(request) { await self.viewModel.load() }
|
||||||
guard !Task.isCancelled else { return }
|
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
|
||||||
renderCurrentSection()
|
renderCurrentSection()
|
||||||
applyState()
|
applyState()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private func selectSection(_ id: String) {
|
private func selectSection(_ id: String) {
|
||||||
|
guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return }
|
||||||
isOpeningResource = false
|
isOpeningResource = false
|
||||||
pauseReading()
|
pauseReading()
|
||||||
contentIsReady = false
|
contentIsReady = false
|
||||||
@@ -152,8 +168,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
contentNavigation = nil
|
contentNavigation = nil
|
||||||
contentTask = Task { @MainActor [weak self] in
|
contentTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
await viewModel.selectSection(id: id)
|
await performUserRequest(request) { await self.viewModel.selectSection(id: id) }
|
||||||
guard !Task.isCancelled else { return }
|
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
|
||||||
renderCurrentSection()
|
renderCurrentSection()
|
||||||
applyState()
|
applyState()
|
||||||
}
|
}
|
||||||
@@ -186,8 +202,13 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
|
|
||||||
private func applyState() {
|
private func applyState() {
|
||||||
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
|
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
|
||||||
sectionsButton.isEnabled = !viewModel.isLoading && !viewModel.sections.isEmpty
|
let canInteract = userRequestID == nil
|
||||||
attachmentsButton.isEnabled = !viewModel.isLoading && (viewModel.course?.attachmentCount ?? 0) > 0
|
sectionsButton.isUserInteractionEnabled = canInteract
|
||||||
|
attachmentsButton.isUserInteractionEnabled = canInteract
|
||||||
|
actionButton.isUserInteractionEnabled = canInteract
|
||||||
|
guard canInteract else { return }
|
||||||
|
sectionsButton.isEnabled = !viewModel.sections.isEmpty
|
||||||
|
attachmentsButton.isEnabled = (viewModel.course?.attachmentCount ?? 0) > 0
|
||||||
if let progress = viewModel.progress, progress.readingCompleted {
|
if let progress = viewModel.progress, progress.readingCompleted {
|
||||||
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
|
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
|
||||||
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
|
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
|
||||||
@@ -229,6 +250,26 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
actionButton.configuration = configuration
|
actionButton.configuration = configuration
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private func beginUserRequest(showsLoading: Bool) -> UserRequest? {
|
||||||
|
guard userRequestID == nil, !viewModel.isInvalidated else { return nil }
|
||||||
|
let request = UserRequest(id: UUID(), loadingToken: showsLoading ? beginRequestLoading() : nil)
|
||||||
|
userRequestID = request.id
|
||||||
|
applyState()
|
||||||
|
return request
|
||||||
|
}
|
||||||
|
|
||||||
|
private func endUserRequest(_ request: UserRequest) {
|
||||||
|
if let token = request.loadingToken { endRequestLoading(token) }
|
||||||
|
guard userRequestID == request.id else { return }
|
||||||
|
userRequestID = nil
|
||||||
|
applyState()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func performUserRequest<Value>(_ request: UserRequest, operation: () async -> Value) async -> Value {
|
||||||
|
defer { endUserRequest(request) }
|
||||||
|
return await operation()
|
||||||
|
}
|
||||||
|
|
||||||
@objc private func pauseReading() {
|
@objc private func pauseReading() {
|
||||||
readingTimer?.invalidate()
|
readingTimer?.invalidate()
|
||||||
readingTimer = nil
|
readingTimer = nil
|
||||||
@@ -252,9 +293,12 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
|
|
||||||
private func resumeReading(retrying: Bool = false) {
|
private func resumeReading(retrying: Bool = false) {
|
||||||
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
|
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), readingTask == nil else { return }
|
||||||
|
let request = retrying ? beginUserRequest(showsLoading: true) : nil
|
||||||
|
guard !retrying || request != nil else { return }
|
||||||
let pendingClose = closingTask
|
let pendingClose = closingTask
|
||||||
readingTask = Task { @MainActor [weak self] in
|
readingTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
|
defer { if let request { endUserRequest(request) } }
|
||||||
await pendingClose?.value
|
await pendingClose?.value
|
||||||
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
|
guard isContentVisible, viewModel.canStudy, (retrying || viewModel.readingErrorMessage == nil), !Task.isCancelled else {
|
||||||
readingTask = nil
|
readingTask = nil
|
||||||
@@ -299,6 +343,7 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func actionTapped() {
|
@objc private func actionTapped() {
|
||||||
|
guard userRequestID == nil else { return }
|
||||||
if let progress = viewModel.progress, progress.readingCompleted {
|
if let progress = viewModel.progress, progress.readingCompleted {
|
||||||
pauseReading()
|
pauseReading()
|
||||||
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
|
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
|
||||||
@@ -334,13 +379,17 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func sectionsTapped() {
|
@objc private func sectionsTapped() {
|
||||||
|
guard userRequestID == nil, !viewModel.sections.isEmpty else { return }
|
||||||
isOpeningResource = true
|
isOpeningResource = true
|
||||||
pauseReading()
|
pauseReading()
|
||||||
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
|
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
|
||||||
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
|
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
|
||||||
loadMore: { [weak self] in
|
loadMore: { [weak self] in
|
||||||
guard let self else { return ([], false) }
|
guard let self else { return ([], false) }
|
||||||
await viewModel.loadMoreSections()
|
guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else {
|
||||||
|
return (sectionRows(), viewModel.hasMoreSections)
|
||||||
|
}
|
||||||
|
await performUserRequest(request) { await self.viewModel.loadMoreSections() }
|
||||||
applyState()
|
applyState()
|
||||||
if let error = viewModel.errorMessage { showToast(error) }
|
if let error = viewModel.errorMessage { showToast(error) }
|
||||||
return (sectionRows(), viewModel.hasMoreSections)
|
return (sectionRows(), viewModel.hasMoreSections)
|
||||||
@@ -353,18 +402,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func attachmentsTapped() {
|
@objc private func attachmentsTapped() {
|
||||||
|
guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return }
|
||||||
isOpeningResource = true
|
isOpeningResource = true
|
||||||
pauseReading()
|
pauseReading()
|
||||||
contentTask = Task { @MainActor [weak self] in
|
contentTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
await viewModel.loadAttachments()
|
await performUserRequest(request) { await self.viewModel.loadAttachments() }
|
||||||
guard !Task.isCancelled else { return }
|
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
|
||||||
if viewModel.isInvalidated { applyState(); return }
|
if viewModel.isInvalidated { applyState(); return }
|
||||||
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
|
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
|
||||||
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
|
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
|
||||||
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
|
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
|
||||||
guard let self else { return ([], false) }
|
guard let self else { return ([], false) }
|
||||||
await viewModel.loadAttachments(loadMore: true)
|
guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else {
|
||||||
|
return (attachmentRows(), viewModel.hasMoreAttachments)
|
||||||
|
}
|
||||||
|
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
|
||||||
applyState()
|
applyState()
|
||||||
if let error = viewModel.errorMessage { showToast(error) }
|
if let error = viewModel.errorMessage { showToast(error) }
|
||||||
return (attachmentRows(), viewModel.hasMoreAttachments)
|
return (attachmentRows(), viewModel.hasMoreAttachments)
|
||||||
@@ -387,11 +440,14 @@ final class TrainingCourseViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func openAttachment(_ id: String) {
|
private func openAttachment(_ id: String) {
|
||||||
|
guard let request = beginUserRequest(showsLoading: true) else { return }
|
||||||
isOpeningResource = true
|
isOpeningResource = true
|
||||||
pauseReading()
|
pauseReading()
|
||||||
contentTask = Task { @MainActor [weak self] in
|
contentTask = Task { @MainActor [weak self] in
|
||||||
guard let self else { return }
|
guard let self else { return }
|
||||||
guard let link = await viewModel.authorizeAttachment(id: id), !Task.isCancelled else {
|
let link = await performUserRequest(request) { await self.viewModel.authorizeAttachment(id: id) }
|
||||||
|
guard pageIsVisible, navigationController?.topViewController === self, !Task.isCancelled else { return }
|
||||||
|
guard let link else {
|
||||||
isOpeningResource = false
|
isOpeningResource = false
|
||||||
if let error = viewModel.errorMessage { showToast(error) }
|
if let error = viewModel.errorMessage { showToast(error) }
|
||||||
applyState()
|
applyState()
|
||||||
|
|||||||
@@ -11,6 +11,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
private var navigationIsScheduled = false
|
private var navigationIsScheduled = false
|
||||||
private var hasAppeared = false
|
private var hasAppeared = false
|
||||||
private var isPerformingOperation = false
|
private var isPerformingOperation = false
|
||||||
|
private var requestLoadingToken: UUID?
|
||||||
private var needsReloadOnReturn = false
|
private var needsReloadOnReturn = false
|
||||||
private var renderedQuestion: TrainingQuestionItem?
|
private var renderedQuestion: TrainingQuestionItem?
|
||||||
private var optionButtons: [String: UIButton] = [:]
|
private var optionButtons: [String: UIButton] = [:]
|
||||||
@@ -100,7 +101,7 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
hasAppeared = true
|
hasAppeared = true
|
||||||
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
guard !isPerformingOperation, !viewModel.isBusy else { return }
|
||||||
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
|
if viewModel.submittedAttempt != nil || viewModel.shouldReturnToCenter {
|
||||||
beginOperation(message: "正在确认考试状态…")
|
beginOperation(message: "正在确认考试状态…", showsLoading: false)
|
||||||
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
|
Task { @MainActor in await viewModel.validateIdentity(); finishOperation() }
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
@@ -206,14 +207,19 @@ final class TrainingExamViewController: TrainingBaseViewController {
|
|||||||
for button in buttons { button.isUserInteractionEnabled = enabled }
|
for button in buttons { button.isUserInteractionEnabled = enabled }
|
||||||
}
|
}
|
||||||
|
|
||||||
private func beginOperation(message: String) {
|
private func beginOperation(message: String, showsLoading: Bool = true) {
|
||||||
isPerformingOperation = true
|
isPerformingOperation = true
|
||||||
|
if showsLoading { requestLoadingToken = beginRequestLoading() }
|
||||||
setOperationInteractionEnabled(false)
|
setOperationInteractionEnabled(false)
|
||||||
statusLabel.text = message
|
statusLabel.text = message
|
||||||
statusLabel.textColor = AppColor.textSecondary
|
statusLabel.textColor = AppColor.textSecondary
|
||||||
}
|
}
|
||||||
|
|
||||||
private func finishOperation() {
|
private func finishOperation() {
|
||||||
|
if let requestLoadingToken {
|
||||||
|
endRequestLoading(requestLoadingToken)
|
||||||
|
self.requestLoadingToken = nil
|
||||||
|
}
|
||||||
isPerformingOperation = false
|
isPerformingOperation = false
|
||||||
applyState()
|
applyState()
|
||||||
scheduleNavigationIfNeeded()
|
scheduleNavigationIfNeeded()
|
||||||
|
|||||||
@@ -13,6 +13,8 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
private var showsDetails = false
|
private var showsDetails = false
|
||||||
private var usesInitialDetail: Bool
|
private var usesInitialDetail: Bool
|
||||||
private var resultLoadTask: Task<Void, Never>?
|
private var resultLoadTask: Task<Void, Never>?
|
||||||
|
private var isRequestInFlight = false
|
||||||
|
private var requestLoadingToken: UUID?
|
||||||
private let scrollView = UIScrollView()
|
private let scrollView = UIScrollView()
|
||||||
private let contentStack = UIStackView()
|
private let contentStack = UIStackView()
|
||||||
private let footer = UIView()
|
private let footer = UIView()
|
||||||
@@ -89,8 +91,14 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
/// 页面出现时只刷新该次成绩,解析在用户展开后加载。
|
/// 页面出现时只刷新该次成绩,解析在用户展开后加载。
|
||||||
func reload() async {
|
func reload() async {
|
||||||
if let resultLoadTask { await resultLoadTask.value; return }
|
if let resultLoadTask { await resultLoadTask.value; return }
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
|
||||||
|
!Task.isCancelled else { return }
|
||||||
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
|
let token = beginResultRequest()
|
||||||
let task = Task<Void, Never> { @MainActor [weak self] in
|
let task = Task<Void, Never> { @MainActor [weak self] in
|
||||||
await self?.performReload()
|
guard let self else { return }
|
||||||
|
defer { finishResultRequest(token) }
|
||||||
|
await performReload()
|
||||||
}
|
}
|
||||||
resultLoadTask = task
|
resultLoadTask = task
|
||||||
await task.value
|
await task.value
|
||||||
@@ -98,7 +106,6 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private func performReload() async {
|
private func performReload() async {
|
||||||
actionButton.isEnabled = false
|
|
||||||
await viewModel.load(service: service)
|
await viewModel.load(service: service)
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
if let detail = viewModel.detail {
|
if let detail = viewModel.detail {
|
||||||
@@ -110,7 +117,31 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted))
|
contentStack.addArrangedSubview(TrainingUI.text(viewModel.errorMessage ?? "成绩加载失败", color: TrainingUI.muted))
|
||||||
setActionTitle("重新加载")
|
setActionTitle("重新加载")
|
||||||
}
|
}
|
||||||
actionButton.isEnabled = true
|
}
|
||||||
|
|
||||||
|
/// 同步锁定请求动作,Loading 令牌只属于这一次真正发出的请求。
|
||||||
|
private func beginResultRequest() -> UUID {
|
||||||
|
isRequestInFlight = true
|
||||||
|
contentStack.isUserInteractionEnabled = false
|
||||||
|
actionButton.isUserInteractionEnabled = false
|
||||||
|
let token = beginRequestLoading()
|
||||||
|
requestLoadingToken = token
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 成功、失败和取消均释放原令牌,保持按钮正常外观。
|
||||||
|
private func finishResultRequest(_ token: UUID) {
|
||||||
|
endRequestLoading(token)
|
||||||
|
guard requestLoadingToken == token else { return }
|
||||||
|
requestLoadingToken = nil
|
||||||
|
isRequestInFlight = false
|
||||||
|
contentStack.isUserInteractionEnabled = true
|
||||||
|
actionButton.isUserInteractionEnabled = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 导航前主动释放本页请求;离页后的旧 defer 可以安全再次结束同一令牌。
|
||||||
|
private func finishCurrentRequestBeforeNavigation() {
|
||||||
|
if let token = requestLoadingToken { finishResultRequest(token) }
|
||||||
}
|
}
|
||||||
|
|
||||||
private func clearContent() {
|
private func clearContent() {
|
||||||
@@ -120,6 +151,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
private func leaveInaccessibleTaskIfNeeded() -> Bool {
|
private func leaveInaccessibleTaskIfNeeded() -> Bool {
|
||||||
let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid
|
let identityChanged = !validateIdentity() || viewModel.isIdentityInvalid
|
||||||
guard identityChanged || viewModel.isAccessRevoked else { return false }
|
guard identityChanged || viewModel.isAccessRevoked else { return false }
|
||||||
|
finishCurrentRequestBeforeNavigation()
|
||||||
clearContent()
|
clearContent()
|
||||||
if !identityChanged,
|
if !identityChanged,
|
||||||
let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) {
|
let center = navigationController?.viewControllers.first(where: { $0 is TrainingCenterViewController }) {
|
||||||
@@ -169,7 +201,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
|
let details = TrainingUI.button(showsDetails ? "收起答案解析" : "查看答案解析", secondary: true)
|
||||||
details.accessibilityIdentifier = "training.result.details"
|
details.accessibilityIdentifier = "training.result.details"
|
||||||
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
|
details.addTarget(self, action: #selector(toggleDetails), for: .touchUpInside)
|
||||||
details.isEnabled = attempt.reviewAvailable && !viewModel.isLoadingReviews
|
details.isEnabled = attempt.reviewAvailable
|
||||||
contentStack.addArrangedSubview(details)
|
contentStack.addArrangedSubview(details)
|
||||||
let learning = TrainingUI.button("返回学习", plain: true)
|
let learning = TrainingUI.button("返回学习", plain: true)
|
||||||
learning.accessibilityIdentifier = "training.result.learning"
|
learning.accessibilityIdentifier = "training.result.learning"
|
||||||
@@ -199,7 +231,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) }
|
if viewModel.isLoadingReviews { contentStack.addArrangedSubview(TrainingUI.text("正在加载解析…", color: TrainingUI.muted)) }
|
||||||
if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil {
|
if viewModel.hasMoreReviews || viewModel.reviewErrorMessage != nil {
|
||||||
let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true)
|
let more = TrainingUI.button(viewModel.reviewErrorMessage != nil ? "重试加载解析" : "加载更多解析", plain: true)
|
||||||
more.isEnabled = !viewModel.isLoadingReviews
|
more.accessibilityIdentifier = "training.result.reviews.more"
|
||||||
more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside)
|
more.addTarget(self, action: #selector(moreReviewsTapped), for: .touchUpInside)
|
||||||
contentStack.addArrangedSubview(more)
|
contentStack.addArrangedSubview(more)
|
||||||
}
|
}
|
||||||
@@ -210,24 +242,31 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func toggleDetails() {
|
@objc private func toggleDetails() {
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
guard let detail = viewModel.detail else { return }
|
guard let detail = viewModel.detail, detail.attempt.reviewAvailable else { return }
|
||||||
showsDetails.toggle()
|
showsDetails.toggle()
|
||||||
render(detail: detail)
|
render(detail: detail)
|
||||||
guard showsDetails else { return }
|
guard showsDetails, !viewModel.hasLoadedReviews else { return }
|
||||||
Task { @MainActor [weak self] in
|
loadReviewPage(nextPage: false)
|
||||||
guard let self else { return }
|
|
||||||
await viewModel.loadReviews(service: service)
|
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
|
||||||
if let current = viewModel.detail { render(detail: current) }
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc private func moreReviewsTapped() {
|
@objc private func moreReviewsTapped() {
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
Task { @MainActor [weak self] in
|
loadReviewPage(nextPage: viewModel.hasLoadedReviews)
|
||||||
guard let self else { return }
|
}
|
||||||
await viewModel.loadReviews(service: service, nextPage: viewModel.hasLoadedReviews)
|
|
||||||
|
/// 首次展开、翻页和失败重试才持有 Loading,已缓存解析切换不发请求。
|
||||||
|
private func loadReviewPage(nextPage: Bool) {
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews,
|
||||||
|
viewModel.detail?.attempt.reviewAvailable == true else { return }
|
||||||
|
if nextPage { guard viewModel.hasMoreReviews else { return } }
|
||||||
|
else { guard !viewModel.hasLoadedReviews else { return } }
|
||||||
|
let token = beginResultRequest()
|
||||||
|
Task { @MainActor in
|
||||||
|
defer { finishResultRequest(token) }
|
||||||
|
await viewModel.loadReviews(service: service, nextPage: nextPage)
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
if let current = viewModel.detail { render(detail: current) }
|
if let current = viewModel.detail { render(detail: current) }
|
||||||
}
|
}
|
||||||
@@ -235,8 +274,10 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
|
|
||||||
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
|
/// 无论是否通过都能返回本次课程,优先复用导航栈中的课程页面。
|
||||||
@objc private func returnToLearning() {
|
@objc private func returnToLearning() {
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
guard viewModel.detail != nil, let navigationController else { return }
|
guard viewModel.detail != nil, let navigationController else { return }
|
||||||
|
finishCurrentRequestBeforeNavigation()
|
||||||
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
|
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
|
||||||
navigationController.popToViewController(course, animated: true)
|
navigationController.popToViewController(course, animated: true)
|
||||||
} else {
|
} else {
|
||||||
@@ -245,9 +286,11 @@ final class TrainingResultViewController: TrainingBaseViewController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@objc private func actionTapped() {
|
@objc private func actionTapped() {
|
||||||
|
guard !isRequestInFlight, !viewModel.isLoading, !viewModel.isLoadingReviews else { return }
|
||||||
if leaveInaccessibleTaskIfNeeded() { return }
|
if leaveInaccessibleTaskIfNeeded() { return }
|
||||||
if loadFailed { loadResult(); return }
|
if loadFailed { loadResult(); return }
|
||||||
guard let detail = viewModel.detail, let navigationController else { return }
|
guard let detail = viewModel.detail, let navigationController else { return }
|
||||||
|
finishCurrentRequestBeforeNavigation()
|
||||||
if !detail.attempt.passed, detail.taskState.canRetry {
|
if !detail.attempt.passed, detail.taskState.canRetry {
|
||||||
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
|
navigationController.setViewControllers(Array(navigationController.viewControllers.dropLast()) + [TrainingExamViewController(taskID: taskID, service: service, resetDraft: true)], animated: true)
|
||||||
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
} else if let center = navigationController.viewControllers.last(where: { $0 is TrainingCenterViewController }) {
|
||||||
|
|||||||
@@ -281,12 +281,40 @@ final class TrainingRecordCell: UITableViewCell {
|
|||||||
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
|
/// 培训页面在账号或景区切换时立即关闭,停止展示旧身份记录。
|
||||||
@MainActor
|
@MainActor
|
||||||
class TrainingBaseViewController: BaseViewController {
|
class TrainingBaseViewController: BaseViewController {
|
||||||
|
private var requestLoadingTokens: Set<UUID> = []
|
||||||
|
|
||||||
|
/// 展示本页面请求持有的 App 通用 Loading,在完成或离开页面时释放。
|
||||||
|
func beginRequestLoading() -> UUID {
|
||||||
|
let token = GlobalLoadingManager.shared.beginRequest()
|
||||||
|
requestLoadingTokens.insert(token)
|
||||||
|
return token
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只释放本页面持有的令牌,迟到请求不能关闭其它页面的 Loading。
|
||||||
|
func endRequestLoading(_ token: UUID) {
|
||||||
|
guard requestLoadingTokens.remove(token) != nil else { return }
|
||||||
|
GlobalLoadingManager.shared.endRequest(token)
|
||||||
|
}
|
||||||
|
|
||||||
|
override func viewWillDisappear(_ animated: Bool) {
|
||||||
|
super.viewWillDisappear(animated)
|
||||||
|
endOwnedRequestLoading()
|
||||||
|
}
|
||||||
|
|
||||||
override func viewDidLoad() {
|
override func viewDidLoad() {
|
||||||
super.viewDidLoad()
|
super.viewDidLoad()
|
||||||
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange] {
|
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
|
||||||
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
|
NotificationCenter.default.addObserver(self, selector: #selector(contextChanged), name: name, object: nil)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@objc private func contextChanged() { navigationController?.popToRootViewController(animated: false) }
|
private func endOwnedRequestLoading() {
|
||||||
|
for token in requestLoadingTokens { GlobalLoadingManager.shared.endRequest(token) }
|
||||||
|
requestLoadingTokens = []
|
||||||
|
}
|
||||||
|
|
||||||
|
@objc private func contextChanged() {
|
||||||
|
endOwnedRequestLoading()
|
||||||
|
navigationController?.popToRootViewController(animated: false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -51,4 +51,48 @@ final class GlobalLoadingManagerTests: XCTestCase {
|
|||||||
manager.hide()
|
manager.hide()
|
||||||
XCTAssertFalse(manager.isShowing)
|
XCTAssertFalse(manager.isShowing)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 清理旧请求后,旧响应的释放不能关闭新请求或普通 show 持有的 Loading。
|
||||||
|
func testStaleRequestTokenDoesNotHideNewLoading() {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
let previous = manager.beginRequest()
|
||||||
|
manager.hideAll()
|
||||||
|
let current = manager.beginRequest()
|
||||||
|
manager.endRequest(previous)
|
||||||
|
XCTAssertTrue(manager.isShowing)
|
||||||
|
manager.endRequest(current)
|
||||||
|
XCTAssertFalse(manager.isShowing)
|
||||||
|
manager.show()
|
||||||
|
manager.endRequest(current)
|
||||||
|
XCTAssertTrue(manager.isShowing)
|
||||||
|
manager.hide()
|
||||||
|
XCTAssertFalse(manager.isShowing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求令牌与已有 show/hide 引用计数可以共存,重复结束不影响其它持有者。
|
||||||
|
func testRequestTokensRespectOtherLoadingOwners() {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.show()
|
||||||
|
let first = manager.beginRequest()
|
||||||
|
let second = manager.beginRequest()
|
||||||
|
manager.endRequest(first)
|
||||||
|
manager.endRequest(first)
|
||||||
|
XCTAssertTrue(manager.isShowing)
|
||||||
|
manager.hide()
|
||||||
|
XCTAssertTrue(manager.isShowing)
|
||||||
|
manager.endRequest(second)
|
||||||
|
XCTAssertFalse(manager.isShowing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 旧普通请求在全局清理后的迟到 hide 不能抵消新培训请求的独立票据。
|
||||||
|
func testLateLegacyHideCannotEndRequestToken() {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.show()
|
||||||
|
manager.hideAll()
|
||||||
|
let current = manager.beginRequest()
|
||||||
|
manager.hide()
|
||||||
|
XCTAssertTrue(manager.isShowing)
|
||||||
|
manager.endRequest(current)
|
||||||
|
XCTAssertFalse(manager.isShowing)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,353 @@
|
|||||||
|
import SafariServices
|
||||||
|
import UIKit
|
||||||
|
import WebKit
|
||||||
|
import XCTest
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 明确挂起响应,验证等待期间的进度与重复点击,而不依赖固定网络延时。
|
||||||
|
private actor TrainingCourseLoadingGate {
|
||||||
|
private var continuations: [CheckedContinuation<Void, Never>] = []
|
||||||
|
private var released = false
|
||||||
|
private(set) var requestCount = 0
|
||||||
|
|
||||||
|
/// 所有意外并发请求分别等待,方便断言请求数量。
|
||||||
|
func wait() async {
|
||||||
|
requestCount += 1
|
||||||
|
guard !released else { return }
|
||||||
|
await withCheckedContinuation { continuations.append($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 释放所有挂起响应,测试失败时也不会遗留 continuation。
|
||||||
|
func release() {
|
||||||
|
released = true
|
||||||
|
let pending = continuations
|
||||||
|
continuations = []
|
||||||
|
pending.forEach { $0.resume() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 真机课程请求交互:用户动作显示全局进度,缓存与自动读时不显示。
|
||||||
|
@MainActor
|
||||||
|
final class TrainingCourseRequestLoadingTests: XCTestCase {
|
||||||
|
private var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
|
override func tearDown() {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
super.tearDown()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 首次失败释放进度;主动重试保持按钮外观,快速重复点击不重复请求。
|
||||||
|
func testColdLoadFailureAndButtonRetryReleaseLoading() async throws {
|
||||||
|
let first = TrainingCourseLoadingGate()
|
||||||
|
let retry = TrainingCourseLoadingGate()
|
||||||
|
defer { Task { await first.release(); await retry.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure {
|
||||||
|
$0.taskHandler = { _ in await first.wait(); throw URLError(.timedOut) }
|
||||||
|
}
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||||
|
let window = try makeWindow(controller)
|
||||||
|
defer { closeWindow(window, controller: controller) }
|
||||||
|
try await waitUntil { await first.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await first.release()
|
||||||
|
let action = try button("training.reading.action", in: controller.view)
|
||||||
|
try await waitUntil { action.isEnabled && action.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing }
|
||||||
|
await source.configure {
|
||||||
|
$0.taskHandler = { _ in await retry.wait(); return TrainingRemoteFixtures.detail() }
|
||||||
|
}
|
||||||
|
let appearance = (action.isEnabled, action.alpha, action.configuration?.baseBackgroundColor)
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
XCTAssertEqual(action.isEnabled, appearance.0)
|
||||||
|
XCTAssertEqual(action.alpha, appearance.1)
|
||||||
|
XCTAssertEqual(action.configuration?.baseBackgroundColor, appearance.2)
|
||||||
|
XCTAssertFalse(action.isUserInteractionEnabled)
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await retry.requestCount == 1 }
|
||||||
|
let calls = await source.calls
|
||||||
|
XCTAssertEqual(calls.filter { $0.name == "task" }.count, 2)
|
||||||
|
await retry.release()
|
||||||
|
try await waitUntil { self.isReady(controller) }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 目录分页和未缓存正文显示进度;缓存切换无额外正文请求或进度闪烁。
|
||||||
|
func testDirectoryPaginationAndCachedSectionReuse() async throws {
|
||||||
|
let page = TrainingCourseLoadingGate()
|
||||||
|
let body = TrainingCourseLoadingGate()
|
||||||
|
defer { Task { await page.release(); await body.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure {
|
||||||
|
$0.sectionsHandler = { cursor in
|
||||||
|
if cursor != nil {
|
||||||
|
await page.wait()
|
||||||
|
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s3", order: 3, title: "后续小节")], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||||
|
}
|
||||||
|
return TrainingCursorPage(items: [TrainingSectionInfo(id: "s1", order: 1, title: "首节"), TrainingSectionInfo(id: "s2", order: 2, title: "第二节")], nextCursor: "next", hasMore: true, serverTime: nil)
|
||||||
|
}
|
||||||
|
$0.sectionHandler = { id in
|
||||||
|
if id == "s2" { await body.wait() }
|
||||||
|
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>\(id)</p>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||||
|
let window = try makeWindow(controller)
|
||||||
|
defer { closeWindow(window, controller: controller) }
|
||||||
|
try await waitUntil { self.isReady(controller) }
|
||||||
|
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 3)
|
||||||
|
selectRow(2, in: picker.table)
|
||||||
|
selectRow(2, in: picker.table)
|
||||||
|
try await waitUntil { await page.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await page.release()
|
||||||
|
try await waitUntil { self.rowTitle(2, in: picker.table) == "3. 后续小节" && !GlobalLoadingManager.shared.isShowing }
|
||||||
|
selectRow(1, in: picker.table)
|
||||||
|
try await waitUntil { await body.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await body.release()
|
||||||
|
try await waitUntil { self.isReady(controller) && controller.presentedViewController == nil }
|
||||||
|
let cached = try await openPicker("training.reading.sections", controller: controller, rows: 3)
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
selectRow(0, in: cached.table)
|
||||||
|
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
let calls = await source.calls
|
||||||
|
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 2)
|
||||||
|
XCTAssertEqual(calls.filter { $0.name == "sections" && $0.cursor == "next" }.count, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 附件第一页、下一页和授权请求显示进度,复用目录及呈现 Safari 前已释放进度。
|
||||||
|
func testAttachmentLoadingPaginationReuseAndAuthorization() async throws {
|
||||||
|
let first = TrainingCourseLoadingGate()
|
||||||
|
let next = TrainingCourseLoadingGate()
|
||||||
|
let authorization = TrainingCourseLoadingGate()
|
||||||
|
defer { Task { await first.release(); await next.release(); await authorization.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure {
|
||||||
|
$0.courseHandler = { TrainingCourseInfo(id: "course_1", title: "课程", introduction: "简介", sectionCount: 2, attachmentCount: 2) }
|
||||||
|
$0.attachmentsHandler = { cursor in
|
||||||
|
if cursor == nil { await first.wait() } else { await next.wait() }
|
||||||
|
let id = cursor == nil ? "a1" : "a2"
|
||||||
|
let item = TrainingAttachmentInfo(id: id, name: id, mimeType: "application/pdf", sizeBytes: 120,
|
||||||
|
fileID: id, downloadURL: nil, expiresAt: nil)
|
||||||
|
return TrainingCursorPage(items: [item], nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
|
||||||
|
}
|
||||||
|
$0.attachmentURLHandler = { id in
|
||||||
|
await authorization.wait()
|
||||||
|
return TrainingAttachmentLink(id: id, name: id, url: URL(string: "https://example.test/training.pdf")!, expiresAt: Date().addingTimeInterval(60))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||||
|
let window = try makeWindow(controller)
|
||||||
|
defer { closeWindow(window, controller: controller) }
|
||||||
|
try await waitUntil { self.isReady(controller) }
|
||||||
|
let attachments = try button("training.reading.attachments", in: controller.view)
|
||||||
|
attachments.sendActions(for: .touchUpInside)
|
||||||
|
attachments.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await first.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
XCTAssertTrue(attachments.isEnabled)
|
||||||
|
await first.release()
|
||||||
|
let picker = try await currentPicker(controller, rows: 2)
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
selectRow(1, in: picker.table)
|
||||||
|
try await waitUntil { await next.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await next.release()
|
||||||
|
try await waitUntil { self.rowTitle(1, in: picker.table) == "a2" && !GlobalLoadingManager.shared.isShowing }
|
||||||
|
try activate(try XCTUnwrap(picker.navigation.topViewController?.navigationItem.rightBarButtonItem))
|
||||||
|
try await waitUntil { controller.presentedViewController == nil && self.isReady(controller) }
|
||||||
|
attachments.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
let reused = try await currentPicker(controller, rows: 2)
|
||||||
|
let calls = await source.calls
|
||||||
|
XCTAssertEqual(calls.filter { $0.name == "attachments" }.count, 2)
|
||||||
|
selectRow(0, in: reused.table)
|
||||||
|
try await waitUntil { await authorization.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await authorization.release()
|
||||||
|
try await waitUntil { controller.presentedViewController is SFSafariViewController }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 离页取消请求后清理原票据,迟到响应不能隐藏其它请求,返回会补载并渲染原选中正文。
|
||||||
|
func testLeavingAndReturningRestoresCanceledSectionWithoutEndingOtherLoading() async throws {
|
||||||
|
let body = TrainingCourseLoadingGate()
|
||||||
|
defer { Task { await body.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure {
|
||||||
|
$0.sectionHandler = { id in
|
||||||
|
if id == "s2" { await body.wait() }
|
||||||
|
return TrainingSectionContent(id: id, order: id == "s1" ? 1 : 2, title: id, contentHTML: "<p>visible-\(id)</p>")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||||
|
let window = try makeWindow(controller)
|
||||||
|
defer { closeWindow(window, controller: controller) }
|
||||||
|
try await waitUntil { self.isReady(controller) }
|
||||||
|
let picker = try await openPicker("training.reading.sections", controller: controller, rows: 2)
|
||||||
|
selectRow(1, in: picker.table)
|
||||||
|
try await waitUntil { await body.requestCount == 1 }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
let navigation = try XCTUnwrap(controller.navigationController)
|
||||||
|
try await waitUntil {
|
||||||
|
controller.presentedViewController == nil && controller.transitionCoordinator == nil
|
||||||
|
&& navigation.transitionCoordinator == nil && !picker.navigation.isBeingDismissed
|
||||||
|
&& picker.navigation.transitionCoordinator == nil
|
||||||
|
}
|
||||||
|
let destination = UIViewController()
|
||||||
|
navigation.pushViewController(destination, animated: false)
|
||||||
|
// 正文响应仍被 gate 挂起;这里只等待 UIKit 完成真实离页与页面票据释放。
|
||||||
|
try await waitUntil {
|
||||||
|
navigation.topViewController === destination && destination.view.window === window
|
||||||
|
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
|
||||||
|
&& !GlobalLoadingManager.shared.isShowing
|
||||||
|
}
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
let other = GlobalLoadingManager.shared.beginRequest()
|
||||||
|
defer { GlobalLoadingManager.shared.endRequest(other) }
|
||||||
|
await body.release()
|
||||||
|
try await waitUntil { self.allViews(controller.view).compactMap { $0 as? UIButton }.allSatisfy { $0.isUserInteractionEnabled } }
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
GlobalLoadingManager.shared.endRequest(other)
|
||||||
|
navigation.popViewController(animated: false)
|
||||||
|
try await waitUntil {
|
||||||
|
navigation.topViewController === controller && controller.view.window === window
|
||||||
|
&& navigation.transitionCoordinator == nil && controller.transitionCoordinator == nil
|
||||||
|
}
|
||||||
|
let webView = try XCTUnwrap(allViews(controller.view).compactMap { $0 as? WKWebView }.first)
|
||||||
|
try await waitUntil {
|
||||||
|
guard self.isReady(controller), !webView.isLoading else { return false }
|
||||||
|
let text = try? await webView.evaluateJavaScript("document.body.textContent") as? String
|
||||||
|
return text?.contains("visible-s2") == true
|
||||||
|
}
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
let calls = await source.calls
|
||||||
|
XCTAssertEqual(calls.filter { $0.name == "section" }.count, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 正文就绪后的自动会话、暂停保存与恢复不显示进度,只有用户重试失败会话显示。
|
||||||
|
func testReadingRetryShowsLoadingAndAutomaticSessionRequestsDoNot() async throws {
|
||||||
|
let initial = TrainingCourseLoadingGate()
|
||||||
|
let retry = TrainingCourseLoadingGate()
|
||||||
|
let automatic = TrainingCourseLoadingGate()
|
||||||
|
defer { Task { await initial.release(); await retry.release(); await automatic.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.readingSeconds = 0
|
||||||
|
configuration.startReadingHandler = { _ in
|
||||||
|
await initial.wait()
|
||||||
|
throw URLError(.timedOut)
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let controller = TrainingCourseViewController(taskID: "task_1", service: source)
|
||||||
|
let window = try makeWindow(controller)
|
||||||
|
defer { closeWindow(window, controller: controller) }
|
||||||
|
try await waitUntil { await initial.requestCount == 1 }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await initial.release()
|
||||||
|
let action = try button("training.reading.action", in: controller.view)
|
||||||
|
try await waitUntil { action.isEnabled && action.configuration?.title == "重试保存并继续学习" }
|
||||||
|
await source.configure {
|
||||||
|
$0.startReadingHandler = { requestID in
|
||||||
|
await retry.wait()
|
||||||
|
return TrainingStudySession(sessionID: requestID, expiresAt: Date().addingTimeInterval(60), heartbeatIntervalSeconds: 5,
|
||||||
|
maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
XCTAssertTrue(GlobalLoadingManager.shared.isShowing)
|
||||||
|
XCTAssertTrue(action.isEnabled)
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await retry.requestCount == 1 }
|
||||||
|
await retry.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && !action.isEnabled && action.isUserInteractionEnabled }
|
||||||
|
await source.configure {
|
||||||
|
$0.startReadingHandler = { requestID in
|
||||||
|
await automatic.wait()
|
||||||
|
return TrainingStudySession(sessionID: requestID, expiresAt: Date().addingTimeInterval(60), heartbeatIntervalSeconds: 5,
|
||||||
|
maxHeartbeatGapSeconds: 15, progress: TrainingRemoteFixtures.progress(seconds: 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
NotificationCenter.default.post(name: UIApplication.willResignActiveNotification, object: nil)
|
||||||
|
try await waitUntil { await source.heartbeats.contains { $0.final } }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil)
|
||||||
|
try await waitUntil { await automatic.requestCount == 1 }
|
||||||
|
XCTAssertFalse(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await automatic.release()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeWindow(_ controller: TrainingCourseViewController) throws -> UIWindow {
|
||||||
|
let scene = try XCTUnwrap(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
|
||||||
|
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||||
|
let window = UIWindow(windowScene: scene)
|
||||||
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
window.rootViewController = navigation
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
return window
|
||||||
|
}
|
||||||
|
|
||||||
|
private func closeWindow(_ window: UIWindow, controller: TrainingCourseViewController) {
|
||||||
|
controller.presentedViewController?.dismiss(animated: false)
|
||||||
|
window.isHidden = true
|
||||||
|
window.rootViewController = nil
|
||||||
|
previousKeyWindow?.makeKey()
|
||||||
|
previousKeyWindow = nil
|
||||||
|
}
|
||||||
|
|
||||||
|
private func isReady(_ controller: TrainingCourseViewController) -> Bool {
|
||||||
|
guard let sections = try? button("training.reading.sections", in: controller.view) else { return false }
|
||||||
|
return sections.isEnabled && sections.isUserInteractionEnabled && !GlobalLoadingManager.shared.isShowing
|
||||||
|
}
|
||||||
|
|
||||||
|
private func openPicker(_ identifier: String, controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) {
|
||||||
|
try button(identifier, in: controller.view).sendActions(for: .touchUpInside)
|
||||||
|
return try await currentPicker(controller, rows: rows)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func currentPicker(_ controller: TrainingCourseViewController, rows: Int) async throws -> (navigation: UINavigationController, table: UITableView) {
|
||||||
|
try await waitUntil {
|
||||||
|
guard let navigation = controller.presentedViewController as? UINavigationController,
|
||||||
|
let picker = navigation.topViewController,
|
||||||
|
!navigation.isBeingPresented, picker.transitionCoordinator == nil,
|
||||||
|
let table = self.allViews(picker.view).compactMap({ $0 as? UITableView }).first else { return false }
|
||||||
|
return table.numberOfRows(inSection: 0) == rows
|
||||||
|
}
|
||||||
|
let navigation = try XCTUnwrap(controller.presentedViewController as? UINavigationController)
|
||||||
|
let picker = try XCTUnwrap(navigation.topViewController)
|
||||||
|
let table = try XCTUnwrap(allViews(picker.view).compactMap { $0 as? UITableView }.first)
|
||||||
|
return (navigation, table)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func selectRow(_ index: Int, in table: UITableView) {
|
||||||
|
table.delegate?.tableView?(table, didSelectRowAt: IndexPath(row: index, section: 0))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func rowTitle(_ index: Int, in table: UITableView) -> String? {
|
||||||
|
(table.cellForRow(at: IndexPath(row: index, section: 0))?.contentConfiguration as? UIListContentConfiguration)?.text
|
||||||
|
}
|
||||||
|
|
||||||
|
private func activate(_ item: UIBarButtonItem) throws {
|
||||||
|
let action = try XCTUnwrap(item.primaryAction)
|
||||||
|
let dispatcher = UIButton(type: .system)
|
||||||
|
dispatcher.addAction(action, for: .touchUpInside)
|
||||||
|
dispatcher.sendActions(for: .touchUpInside)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap { allViews($0) } }
|
||||||
|
|
||||||
|
private func button(_ identifier: String, in view: UIView) throws -> UIButton {
|
||||||
|
try XCTUnwrap(allViews(view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == identifier })
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(5))
|
||||||
|
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||||
|
let reached = await condition()
|
||||||
|
XCTAssertTrue(reached, "未在期限内进入预期 UI / 请求状态")
|
||||||
|
guard reached else { throw CancellationError() }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -64,6 +64,7 @@ actor TrainingDataStub: TrainingDataServing {
|
|||||||
var sectionsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingSectionInfo>)?
|
var sectionsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingSectionInfo>)?
|
||||||
var sectionHandler: (@Sendable (String) async throws -> TrainingSectionContent)?
|
var sectionHandler: (@Sendable (String) async throws -> TrainingSectionContent)?
|
||||||
var attachmentsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingAttachmentInfo>)?
|
var attachmentsHandler: (@Sendable (String?) async throws -> TrainingCursorPage<TrainingAttachmentInfo>)?
|
||||||
|
var attachmentURLHandler: (@Sendable (String) async throws -> TrainingAttachmentLink)?
|
||||||
var startReadingHandler: (@Sendable (String) async throws -> TrainingStudySession)?
|
var startReadingHandler: (@Sendable (String) async throws -> TrainingStudySession)?
|
||||||
var heartbeatHandler: (@Sendable (HeartbeatCall) async throws -> TrainingHeartbeatConfirmation)?
|
var heartbeatHandler: (@Sendable (HeartbeatCall) async throws -> TrainingHeartbeatConfirmation)?
|
||||||
var questionsHandler: (@Sendable (Int, Int) async throws -> TrainingQuestionPage)?
|
var questionsHandler: (@Sendable (Int, Int) async throws -> TrainingQuestionPage)?
|
||||||
@@ -151,6 +152,7 @@ actor TrainingDataStub: TrainingDataServing {
|
|||||||
/// 返回用于 Safari 的授权 HTTPS URL。
|
/// 返回用于 Safari 的授权 HTTPS URL。
|
||||||
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
func attachmentURL(courseID: String, attachmentID: String, taskID: String) async throws -> TrainingAttachmentLink {
|
||||||
calls.append(Call(name: "attachmentURL", taskID: taskID))
|
calls.append(Call(name: "attachmentURL", taskID: taskID))
|
||||||
|
if let handler = configuration.attachmentURLHandler { return try await handler(attachmentID) }
|
||||||
return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
return TrainingAttachmentLink(id: attachmentID, name: "培训附件", url: URL(string: "https://example.test/training.pdf")!, expiresAt: TrainingRemoteFixtures.now.addingTimeInterval(3600))
|
||||||
}
|
}
|
||||||
/// 只返回权威读时。
|
/// 只返回权威读时。
|
||||||
|
|||||||
@@ -0,0 +1,404 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
import UIKit
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 选项保存与跨页题目请求,分别验证成功和失败后的 Loading 释放。
|
||||||
|
enum TrainingLoadingExamScenario: String, CaseIterable, Sendable {
|
||||||
|
case selectionSuccess, selectionFailure, nextSuccess, nextFailure
|
||||||
|
var selectsAnswer: Bool { self == .selectionSuccess || self == .selectionFailure }
|
||||||
|
var fails: Bool { self == .selectionFailure || self == .nextFailure }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 列表显式分页和错误重试均应持有请求 Loading。
|
||||||
|
enum TrainingLoadingCenterScenario: String, CaseIterable, Sendable {
|
||||||
|
case nextPage, retry
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 让请求响应明确等待测试确认,观察同步 Loading 和页面离开后的迟到回调。
|
||||||
|
private actor TrainingLoadingRequestGate {
|
||||||
|
private var continuations: [CheckedContinuation<Void, Never>] = []
|
||||||
|
private var released = false
|
||||||
|
private(set) var requestCount = 0
|
||||||
|
|
||||||
|
/// 记录并挂起请求,不使用固定网络延时。
|
||||||
|
func wait() async {
|
||||||
|
requestCount += 1
|
||||||
|
if released { return }
|
||||||
|
await withCheckedContinuation { continuations.append($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 释放全部挂起响应,重复释放无副作用。
|
||||||
|
func release() {
|
||||||
|
released = true
|
||||||
|
let pending = continuations
|
||||||
|
continuations = []
|
||||||
|
pending.forEach { $0.resume() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 将全局 Loading 放进本例独立的真实 keyWindow,关闭后恢复原 keyWindow。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingLoadingWindowScope {
|
||||||
|
let window: UIWindow
|
||||||
|
private weak var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
|
/// 本例只接管窗口,不写入 AppStore 的账号、景区或店铺。
|
||||||
|
init(_ navigation: UINavigationController) throws {
|
||||||
|
let scene = try #require(UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first)
|
||||||
|
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||||
|
window = UIWindow(windowScene: scene)
|
||||||
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
|
window.rootViewController = navigation
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 隐藏测试窗口并恢复之前的应用窗口。
|
||||||
|
func close() {
|
||||||
|
window.isHidden = true
|
||||||
|
window.rootViewController = nil
|
||||||
|
previousKeyWindow?.makeKey()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 请求 Loading 的页面生命周期回归;每例清理全局展示并使用独立网络和持久化域。
|
||||||
|
@Suite("培训页面请求 Loading", .serialized)
|
||||||
|
@MainActor
|
||||||
|
struct TrainingRequestLoadingTests {
|
||||||
|
private let context = TrainingContext(accountScope: "training_loading", scenicID: 10, storeID: 3)
|
||||||
|
|
||||||
|
@Test("选项和翻题点击同步展示 App Loading,成功或失败均关闭", arguments: TrainingLoadingExamScenario.allCases)
|
||||||
|
func examRequestsOwnLoadingUntilResponse(scenario: TrainingLoadingExamScenario) async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let domain = try makeDefaults()
|
||||||
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
|
let gate = TrainingLoadingRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
if scenario.selectsAnswer {
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.wait()
|
||||||
|
if scenario.fails { throw URLError(.timedOut) }
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 30)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
configuration.questionsHandler = { offset, limit in
|
||||||
|
if offset == 10 {
|
||||||
|
await gate.wait()
|
||||||
|
if scenario.fails { throw URLError(.timedOut) }
|
||||||
|
}
|
||||||
|
return Self.questions(offset: offset, limit: limit)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
await source.seedDraft(revision: 5, answers: Dictionary(uniqueKeysWithValues: (1...30).map { ("q\($0)", ["A"]) }), lastOrder: 10)
|
||||||
|
let model = makeModel(defaults: domain.defaults)
|
||||||
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
#expect(scope.window.isKeyWindow)
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
let action = try #require(button(scenario.selectsAnswer ? "training.option.B" : "training.exam.next", in: controller.view))
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
// 不让出主 actor,要求点击处理当场持有 Loading,而非等网络 Task 启动。
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
|
#expect(model.isBusy)
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(await gate.requestCount == 1)
|
||||||
|
#expect(await source.savedRequests.count == (scenario.selectsAnswer ? 1 : 0))
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !model.isBusy && !manager.isShowing && (scenario.fails ? model.errorMessage != nil : model.canEdit) }
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(navigation.topViewController === controller)
|
||||||
|
if scenario.fails {
|
||||||
|
#expect(model.errorMessage != nil)
|
||||||
|
let retry = try #require(button("training.exam.submit", in: controller.view))
|
||||||
|
#expect(retry.isEnabled)
|
||||||
|
#expect(retry.title(for: .normal) == (scenario.selectsAnswer ? "重试保存" : "重试加载本题"))
|
||||||
|
} else {
|
||||||
|
#expect(model.currentIndex == (scenario.selectsAnswer ? 9 : 10))
|
||||||
|
#expect(model.currentSelectedIDs == (scenario.selectsAnswer ? ["B"] : ["A"]))
|
||||||
|
#expect(model.errorMessage == nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("答题卡打开和完成关闭是本地操作,不显示 Loading 或重读任务")
|
||||||
|
func localAnswerCardDoesNotStartRequestLoading() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let domain = try makeDefaults()
|
||||||
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.seedDraft(revision: 3, answers: ["q10": ["B"]], lastOrder: 10)
|
||||||
|
let model = makeModel(defaults: domain.defaults)
|
||||||
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
let before = await source.calls
|
||||||
|
let answerCard = try #require(controller.navigationItem.rightBarButtonItem)
|
||||||
|
try activate(answerCard)
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
try await waitUntil { controller.presentedViewController is UINavigationController }
|
||||||
|
let presented = try #require(controller.presentedViewController as? UINavigationController)
|
||||||
|
try await settleTransitions([controller, presented])
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
let card = try #require(presented.topViewController as? TrainingAnswerCardViewController)
|
||||||
|
let done = try #require(card.navigationItem.rightBarButtonItem)
|
||||||
|
try activate(done)
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
try await waitUntil { controller.presentedViewController == nil }
|
||||||
|
try await settleTransitions([navigation, controller, presented])
|
||||||
|
#expect(!manager.isShowing && !hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(await source.calls == before)
|
||||||
|
#expect(model.currentIndex == 9 && model.currentSelectedIDs == ["B"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("离开考试页立即释放自身 Loading,旧响应不能关闭后来请求的令牌")
|
||||||
|
func leavingExamReleasesOwnedLoadingWithoutHidingNewRequest() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let domain = try makeDefaults()
|
||||||
|
defer { domain.defaults.removePersistentDomain(forName: domain.name) }
|
||||||
|
let gate = TrainingLoadingRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.saveHandler = { request in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingDraftConfirmation(draftRevision: request.baseRevision + 1,
|
||||||
|
savedAt: TrainingRemoteFixtures.now, answeredCount: 1)
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let model = makeModel(defaults: domain.defaults)
|
||||||
|
let controller = TrainingExamViewController(taskID: "task_1", service: source, viewModel: model)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
try await waitUntil { model.canEdit && !manager.isShowing && self.button("training.exam.next", in: controller.view)?.isEnabled == true }
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
let optionA = try #require(button("training.option.A", in: controller.view))
|
||||||
|
optionA.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
let covering = UIViewController()
|
||||||
|
navigation.pushViewController(covering, animated: false)
|
||||||
|
try await settleTransitions([navigation, controller, covering])
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(model.isBusy)
|
||||||
|
let newerToken = manager.beginRequest()
|
||||||
|
defer { manager.endRequest(newerToken) }
|
||||||
|
#expect(manager.isShowing && hasVisibleOverlay(in: scope.window))
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { model.canEdit && model.currentSelectedIDs == ["A"] && optionA.isUserInteractionEnabled }
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(navigation.topViewController === covering)
|
||||||
|
manager.endRequest(newerToken)
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("培训列表下一页和错误重试同步展示 Loading,确认后关闭", arguments: TrainingLoadingCenterScenario.allCases)
|
||||||
|
func centerExplicitRequestsOwnLoading(scenario: TrainingLoadingCenterScenario) async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let gate = TrainingLoadingRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.attemptsHandler = { _, _, cursor in
|
||||||
|
if scenario == .retry { throw URLError(.timedOut) }
|
||||||
|
if cursor != nil { await gate.wait() }
|
||||||
|
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: cursor == nil ? "first" : "second")],
|
||||||
|
nextCursor: cursor == nil ? "next" : nil, hasMore: cursor == nil, serverTime: nil)
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let controller = TrainingCenterViewController(service: source, showsHistory: true)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
let identifier = scenario == .nextPage ? "training.center.more" : "training.center.retry"
|
||||||
|
let title = scenario == .nextPage ? "加载更多" : "重新加载"
|
||||||
|
try await waitUntil {
|
||||||
|
!manager.isShowing && self.centerButton(identifier: identifier, title: title, in: controller.view).map { !$0.isHidden && $0.isEnabled } == true
|
||||||
|
}
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
let action = try #require(centerButton(identifier: identifier, title: title, in: controller.view))
|
||||||
|
let table = try #require(allViews(controller.view).first { $0 is UITableView } as? UITableView)
|
||||||
|
let statistics = try statisticLabels(in: controller.view)
|
||||||
|
let initialStatistics = statistics.map(\.text)
|
||||||
|
if scenario == .retry {
|
||||||
|
#expect(rowCount(in: table) == 0)
|
||||||
|
await source.configure {
|
||||||
|
$0.attemptsHandler = { _, _, _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: "recovered")], nextCursor: nil, hasMore: false, serverTime: nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
#expect(rowCount(in: table) == 1)
|
||||||
|
#expect(initialStatistics == ["1", "0", "—"])
|
||||||
|
}
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
if scenario == .nextPage {
|
||||||
|
#expect(rowCount(in: table) == 1)
|
||||||
|
#expect(statistics.map(\.text) == initialStatistics)
|
||||||
|
}
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == (scenario == .nextPage ? 2 : 1) }
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(statistics.map(\.text) == ["1", "0", "—"])
|
||||||
|
#expect(navigation.topViewController === controller)
|
||||||
|
let requests = await source.calls.filter { $0.name == "attempts" }
|
||||||
|
#expect(requests.count == 2)
|
||||||
|
let expectedCursors: [String?] = scenario == .nextPage ? [nil, "next"] : [nil, nil]
|
||||||
|
#expect(requests.map(\.cursor) == expectedCursors)
|
||||||
|
#expect(await gate.requestCount == 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("切换列表按钮取消旧搜索防抖,不重发记录请求或提前关闭 Loading")
|
||||||
|
func centerTabRequestCancelsPendingSearchDebounce() async throws {
|
||||||
|
let manager = GlobalLoadingManager.shared
|
||||||
|
manager.hideAll()
|
||||||
|
defer { manager.hideAll() }
|
||||||
|
let gate = TrainingLoadingRequestGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
var configuration = TrainingDataStub.Configuration()
|
||||||
|
configuration.attemptsHandler = { _, _, _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingCursorPage(items: [TrainingRemoteFixtures.attempt(id: "records_target")],
|
||||||
|
nextCursor: nil, hasMore: false, serverTime: nil)
|
||||||
|
}
|
||||||
|
let source = TrainingDataStub(configuration: configuration)
|
||||||
|
let controller = TrainingCenterViewController(service: source)
|
||||||
|
let navigation = UINavigationController(rootViewController: controller)
|
||||||
|
let scope = try TrainingLoadingWindowScope(navigation)
|
||||||
|
defer { scope.close() }
|
||||||
|
let table = try #require(allViews(controller.view).first { $0 is UITableView } as? UITableView)
|
||||||
|
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == 1 }
|
||||||
|
controller.selectTab(.tasks)
|
||||||
|
let search = try #require(allViews(controller.view).compactMap { $0 as? UITextField }.first {
|
||||||
|
$0.accessibilityIdentifier == "training.search"
|
||||||
|
})
|
||||||
|
try await waitUntil { !manager.isShowing && !search.isHidden && self.rowCount(in: table) == 1 }
|
||||||
|
try await settleTransitions([navigation, controller])
|
||||||
|
let taskCallsBefore = await source.calls.filter { $0.name == "tasks" }
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempts" }.isEmpty)
|
||||||
|
|
||||||
|
search.text = "服务"
|
||||||
|
search.sendActions(for: .editingChanged)
|
||||||
|
#expect(!manager.isShowing)
|
||||||
|
// 仍在同一主 actor 回合内,按钮请求必须取消刚安排的 300ms 搜索任务。
|
||||||
|
controller.selectTab(.records)
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
try await waitUntil { await gate.requestCount > 0 }
|
||||||
|
// 此处只等待超过真实防抖期限,响应始终由 gate 控制,不能提前结束请求。
|
||||||
|
try await Task.sleep(for: .milliseconds(450))
|
||||||
|
#expect(manager.isShowing)
|
||||||
|
#expect(hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(await gate.requestCount == 1)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempts" }.count == 1)
|
||||||
|
#expect(await source.calls.filter { $0.name == "tasks" } == taskCallsBefore)
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !manager.isShowing && self.rowCount(in: table) == 1 }
|
||||||
|
#expect(!hasVisibleOverlay(in: scope.window))
|
||||||
|
#expect(button("training.tab.2", in: controller.view)?.accessibilityTraits.contains(.selected) == true)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempts" }.count == 1)
|
||||||
|
#expect(navigation.topViewController === controller)
|
||||||
|
}
|
||||||
|
|
||||||
|
private nonisolated static func questions(offset: Int, limit: Int) -> TrainingQuestionPage {
|
||||||
|
let end = min(30, offset + limit)
|
||||||
|
let items: [TrainingQuestionItem] = offset < end ? ((offset + 1)...end).map(TrainingRemoteFixtures.question) : []
|
||||||
|
return TrainingQuestionPage(paperSnapshotID: "paper_1", total: 30, offset: offset,
|
||||||
|
nextOffset: end < 30 ? end : nil, hasMore: end < 30, items: items)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeDefaults() throws -> (name: String, defaults: UserDefaults) {
|
||||||
|
let name = "TrainingRequestLoadingTests-\(UUID().uuidString)"
|
||||||
|
return (name, try #require(UserDefaults(suiteName: name)))
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeModel(defaults: UserDefaults) -> TrainingRemoteExamViewModel {
|
||||||
|
let scope = context
|
||||||
|
return TrainingRemoteExamViewModel(taskID: "task_1", context: scope,
|
||||||
|
pendingStore: TrainingPendingSubmissionStore(defaults: defaults), currentContext: { scope })
|
||||||
|
}
|
||||||
|
|
||||||
|
private func hasVisibleOverlay(in window: UIWindow) -> Bool {
|
||||||
|
window.subviews.contains { $0 is GlobalLoadingOverlayView && !$0.isHidden }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func allViews(_ view: UIView) -> [UIView] {
|
||||||
|
[view] + view.subviews.flatMap { allViews($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func button(_ identifier: String, in view: UIView) -> UIButton? {
|
||||||
|
allViews(view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == identifier }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func centerButton(identifier: String, title: String, in view: UIView) -> UIButton? {
|
||||||
|
button(identifier, in: view) ?? allViews(view).compactMap { $0 as? UIButton }.first {
|
||||||
|
($0.configuration?.title ?? $0.title(for: .normal)) == title
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func rowCount(in table: UITableView) -> Int {
|
||||||
|
table.numberOfSections > 0 ? table.numberOfRows(inSection: 0) : 0
|
||||||
|
}
|
||||||
|
|
||||||
|
private func statisticLabels(in view: UIView) throws -> [UILabel] {
|
||||||
|
let labels = allViews(view).compactMap { $0 as? UILabel }
|
||||||
|
return try ["待考试", "已完成", "最近得分"].map { title in
|
||||||
|
let caption = try #require(labels.first { $0.text == title })
|
||||||
|
let column = try #require(caption.superview as? UIStackView)
|
||||||
|
return try #require(column.arrangedSubviews.compactMap { $0 as? UILabel }.first { $0 !== caption })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func activate(_ item: UIBarButtonItem) throws {
|
||||||
|
if let action = item.primaryAction {
|
||||||
|
let dispatcher = UIButton(type: .system)
|
||||||
|
dispatcher.addAction(action, for: .touchUpInside)
|
||||||
|
dispatcher.sendActions(for: .touchUpInside)
|
||||||
|
} else {
|
||||||
|
let action = try #require(item.action)
|
||||||
|
UIApplication.shared.sendAction(action, to: item.target, from: item, for: nil)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func settleTransitions(_ controllers: [UIViewController]) async throws {
|
||||||
|
try await Task.sleep(for: .milliseconds(20))
|
||||||
|
try await waitUntil { controllers.allSatisfy { $0.transitionCoordinator == nil && !$0.isBeingPresented && !$0.isBeingDismissed } }
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitUntil(_ condition: @MainActor () async -> Bool) async throws {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||||
|
while !(await condition()), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||||
|
let reached = await condition()
|
||||||
|
try #require(reached)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,340 @@
|
|||||||
|
import Foundation
|
||||||
|
import Testing
|
||||||
|
import UIKit
|
||||||
|
@testable import suixinkan
|
||||||
|
|
||||||
|
/// 可控挂起成绩或解析请求,验证通用 Loading 覆盖真实等待区间。
|
||||||
|
private actor TrainingResultLoadingGate {
|
||||||
|
private var continuations: [CheckedContinuation<Void, Never>] = []
|
||||||
|
private var released = false
|
||||||
|
private(set) var requestCount = 0
|
||||||
|
|
||||||
|
/// 记录实际请求次数,不用固定网络延时冒充在途状态。
|
||||||
|
func wait() async {
|
||||||
|
requestCount += 1
|
||||||
|
if released { return }
|
||||||
|
await withCheckedContinuation { continuations.append($0) }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 测试完成和异常退出均释放所有挂起请求。
|
||||||
|
func release() {
|
||||||
|
released = true
|
||||||
|
let pending = continuations
|
||||||
|
continuations = []
|
||||||
|
pending.forEach { $0.resume() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 只操作内存替身和独立窗口,验证成绩请求 Loading、缓存及重试。
|
||||||
|
@Suite("培训成绩请求 Loading", .serialized)
|
||||||
|
@MainActor
|
||||||
|
struct TrainingResultRequestLoadingTests {
|
||||||
|
@Test("成绩重载合并请求,等待期间展示通用 Loading 且按钮外观不变")
|
||||||
|
func reloadOwnsOneLoadingTokenAndKeepsButtonEnabled() async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let gate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.attemptHandler = { _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingRemoteFixtures.result()
|
||||||
|
} }
|
||||||
|
let controller = makeController(source: source)
|
||||||
|
controller.loadViewIfNeeded()
|
||||||
|
let action = try #require(button("training.result.action", in: controller.view))
|
||||||
|
let background = action.configuration?.baseBackgroundColor
|
||||||
|
let foreground = action.configuration?.baseForegroundColor
|
||||||
|
let request = Task { @MainActor in await controller.reload() }
|
||||||
|
try await waitForGate(gate)
|
||||||
|
let scene = try TrainingResultLoadingWindow(controller)
|
||||||
|
defer { scene.close() }
|
||||||
|
let joined = Task { @MainActor in await controller.reload() }
|
||||||
|
action.sendActions(for: .touchUpInside)
|
||||||
|
await Task.yield()
|
||||||
|
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(action.isEnabled)
|
||||||
|
#expect(!action.isUserInteractionEnabled)
|
||||||
|
#expect(action.configuration?.baseBackgroundColor == background)
|
||||||
|
#expect(action.configuration?.baseForegroundColor == foreground)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempt" }.count == 1)
|
||||||
|
#expect(await gate.requestCount == 1)
|
||||||
|
|
||||||
|
await gate.release()
|
||||||
|
await request.value
|
||||||
|
await joined.value
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && action.isUserInteractionEnabled }
|
||||||
|
#expect(action.isEnabled)
|
||||||
|
#expect(hasLabel("100", in: controller.view))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("成绩请求失败或取消后释放 Loading,按钮重试仍持有 Loading", arguments: [false, true])
|
||||||
|
func summaryFailureCanRetryWithLoading(cancelled: Bool) async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.attemptHandler = { _ in
|
||||||
|
if cancelled { throw CancellationError() }
|
||||||
|
throw APIError.networkFailed("成绩查询离线")
|
||||||
|
} }
|
||||||
|
let controller = makeController(source: source)
|
||||||
|
let scene = try TrainingResultLoadingWindow(controller)
|
||||||
|
defer { scene.close() }
|
||||||
|
try await waitUntil { self.button("training.result.action", in: controller.view)?.configuration?.title == "重新加载" }
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
let gate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
await source.configure { $0.attemptHandler = { _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingRemoteFixtures.result()
|
||||||
|
} }
|
||||||
|
let retry = try #require(button("training.result.action", in: controller.view))
|
||||||
|
retry.sendActions(for: .touchUpInside)
|
||||||
|
retry.sendActions(for: .touchUpInside)
|
||||||
|
try await waitForGate(gate)
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(retry.isEnabled && !retry.isUserInteractionEnabled)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempt" }.count == 2)
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel("100", in: controller.view) }
|
||||||
|
#expect(retry.isUserInteractionEnabled)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("首次展开解析展示 Loading,交卷摘要和缓存展开收起均不请求或闪 Loading")
|
||||||
|
func firstReviewsShowLoadingAndCachedTogglesDoNot() async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let gate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.reviewsHandler = { _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false)
|
||||||
|
} }
|
||||||
|
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||||
|
let scene = try TrainingResultLoadingWindow(controller)
|
||||||
|
defer { scene.close() }
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(await source.calls.isEmpty)
|
||||||
|
let details = try #require(button("training.result.details", in: controller.view))
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
let waitingDetails = try #require(button("training.result.details", in: controller.view))
|
||||||
|
waitingDetails.sendActions(for: .touchUpInside)
|
||||||
|
try await waitForGate(gate)
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(waitingDetails.isEnabled)
|
||||||
|
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view) }
|
||||||
|
|
||||||
|
let collapse = try #require(button("training.result.details", in: controller.view))
|
||||||
|
collapse.sendActions(for: .touchUpInside)
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(!hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||||
|
let reopen = try #require(button("training.result.details", in: controller.view))
|
||||||
|
reopen.sendActions(for: .touchUpInside)
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||||
|
await Task.yield()
|
||||||
|
#expect(await source.calls.filter { $0.name == "reviews" }.count == 1)
|
||||||
|
#expect(await source.calls.filter { $0.name == "attempt" }.isEmpty)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("解析首次失败可重试,成绩保持显示且 Loading 按请求结束")
|
||||||
|
func firstReviewFailureRetriesWithLoading() async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.reviewsHandler = { _ in throw APIError.networkFailed("解析离线") } }
|
||||||
|
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||||
|
let scene = try TrainingResultLoadingWindow(controller)
|
||||||
|
defer { scene.close() }
|
||||||
|
let details = try #require(button("training.result.details", in: controller.view))
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { self.button("training.result.reviews.more", in: controller.view)?.configuration?.title == "重试加载解析" }
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(hasLabel("100", in: controller.view))
|
||||||
|
let gate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
await source.configure { $0.reviewsHandler = { cursor in
|
||||||
|
#expect(cursor == nil)
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: nil, hasMore: false)
|
||||||
|
} }
|
||||||
|
let retry = try #require(button("training.result.reviews.more", in: controller.view))
|
||||||
|
retry.sendActions(for: .touchUpInside)
|
||||||
|
retry.sendActions(for: .touchUpInside)
|
||||||
|
try await waitForGate(gate)
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
#expect(retry.isEnabled)
|
||||||
|
#expect(await source.calls.filter { $0.name == "reviews" }.count == 2)
|
||||||
|
await gate.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view) }
|
||||||
|
#expect(button("training.result.reviews.more", in: controller.view) == nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("解析下一页失败和重试使用同一游标,各请求分别释放 Loading")
|
||||||
|
func nextReviewPageFailureRetriesSameCursor() async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.reviewsHandler = { _ in
|
||||||
|
TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review()], nextCursor: "next", hasMore: true)
|
||||||
|
} }
|
||||||
|
let controller = makeController(source: source, initial: TrainingRemoteFixtures.result())
|
||||||
|
let scene = try TrainingResultLoadingWindow(controller)
|
||||||
|
defer { scene.close() }
|
||||||
|
let details = try #require(button("training.result.details", in: controller.view))
|
||||||
|
details.sendActions(for: .touchUpInside)
|
||||||
|
try await waitUntil { self.button("training.result.reviews.more", in: controller.view) != nil && !GlobalLoadingManager.shared.isShowing }
|
||||||
|
let failureGate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await failureGate.release() } }
|
||||||
|
await source.configure { $0.reviewsHandler = { cursor in
|
||||||
|
#expect(cursor == "next")
|
||||||
|
await failureGate.wait()
|
||||||
|
throw APIError.networkFailed("下一页离线")
|
||||||
|
} }
|
||||||
|
let more = try #require(button("training.result.reviews.more", in: controller.view))
|
||||||
|
more.sendActions(for: .touchUpInside)
|
||||||
|
try await waitForGate(failureGate)
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await failureGate.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.button("training.result.reviews.more", in: controller.view)?.configuration?.title == "重试加载解析" }
|
||||||
|
#expect(hasLabel(TrainingRemoteFixtures.review().stem, in: controller.view))
|
||||||
|
let retryGate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await retryGate.release() } }
|
||||||
|
await source.configure { $0.reviewsHandler = { cursor in
|
||||||
|
#expect(cursor == "next")
|
||||||
|
await retryGate.wait()
|
||||||
|
return TrainingReviewPage(attemptID: "attempt_1", items: [TrainingRemoteFixtures.review(2)], nextCursor: nil, hasMore: false)
|
||||||
|
} }
|
||||||
|
let retry = try #require(button("training.result.reviews.more", in: controller.view))
|
||||||
|
retry.sendActions(for: .touchUpInside)
|
||||||
|
try await waitForGate(retryGate)
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
await retryGate.release()
|
||||||
|
try await waitUntil { !GlobalLoadingManager.shared.isShowing && self.hasLabel(TrainingRemoteFixtures.review(2).stem, in: controller.view) }
|
||||||
|
let calls = await source.calls.filter { $0.name == "reviews" }
|
||||||
|
#expect(calls.map(\.cursor) == [nil, "next", "next"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test("离开成绩页或 hideAll 后,旧请求结束不关闭其它请求 Loading", arguments: [false, true])
|
||||||
|
func leavingOrResettingLoadingCannotHideNewRequest(resetAll: Bool) async throws {
|
||||||
|
GlobalLoadingManager.shared.hideAll()
|
||||||
|
defer { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
let gate = TrainingResultLoadingGate()
|
||||||
|
defer { Task { await gate.release() } }
|
||||||
|
let source = TrainingDataStub()
|
||||||
|
await source.configure { $0.attemptHandler = { _ in
|
||||||
|
await gate.wait()
|
||||||
|
return TrainingRemoteFixtures.result()
|
||||||
|
} }
|
||||||
|
let controller = makeController(source: source)
|
||||||
|
let root = TrainingResultLoadingAppearanceController()
|
||||||
|
let navigation = TrainingResultLoadingNavigationController(rootViewController: root)
|
||||||
|
navigation.setViewControllers([root, controller], animated: false)
|
||||||
|
let scene = try TrainingResultLoadingWindow(navigation: navigation)
|
||||||
|
defer { scene.close() }
|
||||||
|
try await waitForGate(gate)
|
||||||
|
try await waitUntil {
|
||||||
|
navigation.didAppear && navigation.topViewController === controller
|
||||||
|
&& navigation.transitionCoordinator == nil
|
||||||
|
}
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing)
|
||||||
|
if resetAll { GlobalLoadingManager.shared.hideAll() }
|
||||||
|
else {
|
||||||
|
navigation.popViewController(animated: false)
|
||||||
|
try await waitUntil {
|
||||||
|
root.didAppear && navigation.topViewController === root
|
||||||
|
&& navigation.transitionCoordinator == nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
let newer = GlobalLoadingManager.shared.beginRequest()
|
||||||
|
defer { GlobalLoadingManager.shared.endRequest(newer) }
|
||||||
|
await gate.release()
|
||||||
|
await controller.reload()
|
||||||
|
#expect(GlobalLoadingManager.shared.isShowing, "旧结束回调只能归还原票据")
|
||||||
|
GlobalLoadingManager.shared.endRequest(newer)
|
||||||
|
#expect(!GlobalLoadingManager.shared.isShowing)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func makeController(source: any TrainingDataServing, initial: TrainingAttemptDetail? = nil) -> TrainingResultViewController {
|
||||||
|
TrainingResultViewController(taskID: "task_1", attemptID: "attempt_1", service: source, initialDetail: initial)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitForGate(_ gate: TrainingResultLoadingGate) async throws {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||||
|
while await gate.requestCount == 0, ContinuousClock.now < deadline {
|
||||||
|
try await Task.sleep(for: .milliseconds(10))
|
||||||
|
}
|
||||||
|
let count = await gate.requestCount
|
||||||
|
try #require(count > 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func waitUntil(_ condition: () -> Bool) async throws {
|
||||||
|
let deadline = ContinuousClock.now.advanced(by: .seconds(3))
|
||||||
|
while !condition(), ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(10)) }
|
||||||
|
try #require(condition())
|
||||||
|
}
|
||||||
|
|
||||||
|
private func allViews(_ view: UIView) -> [UIView] { [view] + view.subviews.flatMap(allViews) }
|
||||||
|
private func button(_ identifier: String, in view: UIView) -> UIButton? {
|
||||||
|
allViews(view).compactMap { $0 as? UIButton }.first { $0.accessibilityIdentifier == identifier }
|
||||||
|
}
|
||||||
|
private func hasLabel(_ text: String, in view: UIView) -> Bool {
|
||||||
|
allViews(view).compactMap { $0 as? UILabel }.contains { $0.text == text }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 记录首次窗口展示已经完成,避免在导航仍进行 appearance 时立即移除请求页面。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingResultLoadingNavigationController: UINavigationController {
|
||||||
|
private(set) var didAppear = false
|
||||||
|
|
||||||
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
|
super.viewDidAppear(animated)
|
||||||
|
didAppear = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 用真实目标页面的 appearance 确认 pop 已结束,再检查离页释放的 Loading。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingResultLoadingAppearanceController: UIViewController {
|
||||||
|
private(set) var didAppear = false
|
||||||
|
|
||||||
|
override func viewDidAppear(_ animated: Bool) {
|
||||||
|
super.viewDidAppear(animated)
|
||||||
|
didAppear = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 保留上一键窗口,关闭测试窗口时恢复,避免影响其它页面的 Loading 归属。
|
||||||
|
@MainActor
|
||||||
|
private final class TrainingResultLoadingWindow {
|
||||||
|
let window: UIWindow
|
||||||
|
private weak var previousKeyWindow: UIWindow?
|
||||||
|
|
||||||
|
convenience init(_ controller: UIViewController) throws {
|
||||||
|
try self.init(navigation: UINavigationController(rootViewController: controller))
|
||||||
|
}
|
||||||
|
|
||||||
|
init(navigation: UINavigationController) throws {
|
||||||
|
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
|
||||||
|
let scene = try #require(scenes.first { $0.activationState == .foregroundActive } ?? scenes.first)
|
||||||
|
previousKeyWindow = scene.windows.first { $0.isKeyWindow }
|
||||||
|
window = UIWindow(windowScene: scene)
|
||||||
|
window.frame = CGRect(x: 0, y: 0, width: 390, height: 844)
|
||||||
|
window.rootViewController = navigation
|
||||||
|
window.makeKeyAndVisible()
|
||||||
|
navigation.view.layoutIfNeeded()
|
||||||
|
}
|
||||||
|
|
||||||
|
func close() {
|
||||||
|
window.endEditing(true)
|
||||||
|
window.isHidden = true
|
||||||
|
window.rootViewController = nil
|
||||||
|
previousKeyWindow?.makeKeyAndVisible()
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user