feat(training): 支持课程附件预览与整页阅读

This commit is contained in:
2026-10-20 13:36:58 +08:00
parent 091d17ff21
commit b149295e66
53 changed files with 4233 additions and 632 deletions
@@ -1,19 +1,26 @@
import SafariServices
import SnapKit
import UIKit
import WebKit
/// 正式课程按需阅读:正文分页、附件授权与服务端确认的前台读时。
/// 原生课程信息与附件文件预览,并上报服务端确认的有效前台读时。
@MainActor
final class TrainingCourseViewController: TrainingBaseViewController {
private let service: any TrainingDataServing
private let viewModel: TrainingRemoteReadingViewModel
private let webView: WKWebView
private let headerStack = UIStackView()
private let toolbar = UIStackView()
private let validateIdentity: @MainActor @Sendable () -> Bool
private let documentLoader: any TrainingDocumentLoading
private let scrollView = UIScrollView()
private let contentStack = UIStackView()
private let metadataStack = UIStackView()
private let taskTitleLabel = TrainingUI.text(size: 17, weight: .semibold)
private let courseNameLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let examInfoLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let introductionLabel = TrainingUI.text(size: 12.5, color: TrainingUI.muted)
private let attachmentButton = TrainingUI.button("", plain: true)
private let previewView = TrainingDocumentPreviewView()
private var previewHeightConstraint: Constraint?
private var localDocument: TrainingLocalDocument?
private let stepView = TrainingStepView(currentStep: .learning)
private let sectionsButton = TrainingUI.button("章节目录", secondary: true)
private let attachmentsButton = TrainingUI.button("课程附件", secondary: true)
private let bottomStack = UIStackView()
private let noticeLabel = TrainingUI.label(style: .footnote, color: AppColor.textSecondary)
private let actionButton = TrainingUI.button("正在加载课程…")
@@ -22,9 +29,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private var readingTask: Task<Void, Never>?
private var closingTask: Task<Void, Never>?
private var closingGeneration = 0
private var contentNavigation: WKNavigation?
private var appIsActive = UIApplication.shared.applicationState == .active
private var isOpeningResource = false
private var isOpeningExternalLink = false
private var contentIsReady = false
private var contentLoadFailed = false
private var pageIsVisible = false
@@ -39,22 +45,22 @@ final class TrainingCourseViewController: TrainingBaseViewController {
/// 当前任务标识,成绩页可复用已有课程页面。
var taskID: String { viewModel.taskID }
/// 使用正式数据源读取课程,课程 HTML 禁用脚本执行。
init(taskID: String, service: any TrainingDataServing) {
/// 使用正式接口与独立文件下载器读取课程附件,支持测试注入本地文件。
init(taskID: String, service: any TrainingDataServing, documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
self.service = service
self.documentLoader = documentLoader
let session = AppStore.shared.session
let scope = session.accountCachePrefix
let scenicID = session.currentScenicId
let storeID = session.currentStoreId
let token = session.token
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: {
let validate: @MainActor @Sendable () -> Bool = {
let current = AppStore.shared.session
return current.accountCachePrefix == scope && current.currentScenicId == scenicID
&& current.currentStoreId == storeID && current.token == token
})
let configuration = WKWebViewConfiguration()
configuration.defaultWebpagePreferences.allowsContentJavaScript = false
webView = WKWebView(frame: .zero, configuration: configuration)
}
validateIdentity = validate
viewModel = TrainingRemoteReadingViewModel(taskID: taskID, service: service, validateIdentity: validate)
super.init(nibName: nil, bundle: nil)
}
@@ -65,16 +71,27 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func setupUI() {
view.backgroundColor = TrainingUI.background
webView.navigationDelegate = self
webView.backgroundColor = TrainingUI.background
webView.isOpaque = false
toolbar.spacing = 10
toolbar.distribution = .fillEqually
toolbar.addArrangedSubview(sectionsButton)
toolbar.addArrangedSubview(attachmentsButton)
headerStack.axis = .vertical
headerStack.spacing = 20
headerStack.addArrangedSubview(toolbar)
scrollView.delegate = self
scrollView.accessibilityIdentifier = "training.reading.scroll"
scrollView.alwaysBounceVertical = true
contentStack.axis = .vertical
contentStack.spacing = 14
metadataStack.axis = .vertical
metadataStack.spacing = 8
metadataStack.isHidden = true
[taskTitleLabel, courseNameLabel, examInfoLabel, introductionLabel].forEach(metadataStack.addArrangedSubview)
taskTitleLabel.accessibilityIdentifier = "training.reading.taskTitle"
courseNameLabel.accessibilityIdentifier = "training.reading.courseName"
examInfoLabel.accessibilityIdentifier = "training.reading.examInfo"
introductionLabel.accessibilityIdentifier = "training.reading.introduction"
attachmentButton.contentHorizontalAlignment = .leading
attachmentButton.accessibilityIdentifier = "training.reading.documentPicker"
attachmentButton.showsMenuAsPrimaryAction = true
attachmentButton.isHidden = true
contentStack.addArrangedSubview(metadataStack)
contentStack.addArrangedSubview(attachmentButton)
contentStack.addArrangedSubview(previewView)
stepView.isHidden = true
bottomStack.axis = .vertical
bottomStack.spacing = 8
bottomStack.layoutMargins = UIEdgeInsets(top: 10, left: 12, bottom: 10, right: 12)
@@ -83,31 +100,69 @@ final class TrainingCourseViewController: TrainingBaseViewController {
bottomStack.addArrangedSubview(noticeLabel)
bottomStack.addArrangedSubview(actionButton)
actionButton.accessibilityIdentifier = "training.reading.action"
sectionsButton.accessibilityIdentifier = "training.reading.sections"
attachmentsButton.accessibilityIdentifier = "training.reading.attachments"
view.addSubview(headerStack)
view.addSubview(webView)
view.addSubview(stepView)
view.addSubview(scrollView)
scrollView.addSubview(contentStack)
view.addSubview(bottomStack)
previewView.onReady = { [weak self] previewID in
guard let self else { return }
guard self.validateIdentity() else { self.identityChanged(); return }
guard let id = self.viewModel.currentAttachmentID,
self.viewModel.markAttachmentRendered(id: id, previewID: previewID) else { return }
self.contentIsReady = true
self.contentLoadFailed = false
self.applyState()
self.resumeReading()
}
previewView.onFailure = { [weak self] previewID, message in
guard let self, self.viewModel.attachmentPreviewID == previewID,
let id = self.viewModel.currentAttachmentID else { return }
self.viewModel.reportAttachmentFailure(id: id, previewID: previewID, message: message)
self.contentIsReady = false
self.contentLoadFailed = true
self.pauseReading()
self.applyState()
}
previewView.onOpenLink = { [weak self] url in self?.openExternalLink(url) }
previewView.onContentHeightChange = { [weak self] height in
guard let self else { return }
self.previewHeightConstraint?.update(offset: height)
self.view.layoutIfNeeded()
let minimum = -self.scrollView.adjustedContentInset.top
let maximum = max(minimum, self.scrollView.contentSize.height - self.scrollView.bounds.height
+ self.scrollView.adjustedContentInset.bottom)
if self.scrollView.contentOffset.y > maximum {
self.scrollView.setContentOffset(CGPoint(x: 0, y: maximum), animated: false)
}
self.previewView.notifyIfRenderedAndVisible()
if self.isContentVisible { self.resumeReading() }
}
previewView.onScrollToPosition = { [weak self] top in self?.scrollToDocumentPosition(top) }
applyState()
}
override func setupConstraints() {
headerStack.snp.makeConstraints {
stepView.snp.makeConstraints {
$0.top.equalTo(view.safeAreaLayoutGuide).offset(8)
$0.leading.trailing.equalToSuperview().inset(13)
}
webView.snp.makeConstraints {
$0.top.equalTo(headerStack.snp.bottom).offset(8)
scrollView.snp.makeConstraints {
$0.top.equalTo(stepView.snp.bottom).offset(8)
$0.leading.trailing.equalTo(view.safeAreaLayoutGuide)
$0.bottom.equalTo(bottomStack.snp.top)
}
contentStack.snp.makeConstraints {
$0.edges.equalTo(scrollView.contentLayoutGuide).inset(UIEdgeInsets(top: 14, left: 13, bottom: 14, right: 13))
$0.width.equalTo(scrollView.frameLayoutGuide).offset(-26)
}
previewView.snp.makeConstraints {
previewHeightConstraint = $0.height.equalTo(previewView.preferredContentHeight).constraint
}
bottomStack.snp.makeConstraints { $0.leading.trailing.bottom.equalTo(view.safeAreaLayoutGuide) }
}
override func bindActions() {
actionButton.addTarget(self, action: #selector(actionTapped), for: .touchUpInside)
sectionsButton.addTarget(self, action: #selector(sectionsTapped), for: .touchUpInside)
attachmentsButton.addTarget(self, action: #selector(attachmentsTapped), for: .touchUpInside)
NotificationCenter.default.addObserver(self, selector: #selector(appWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(appDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
for name in [NotificationName.accountDidSwitch, NotificationName.scenicDidChange, NotificationName.userDidLogout] {
@@ -125,9 +180,8 @@ final class TrainingCourseViewController: TrainingBaseViewController {
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 localDocument == nil, let id = viewModel.currentAttachmentID { selectAttachment(id) }
else {
if contentNavigation == nil { renderCurrentSection() }
await viewModel.refreshProgress()
applyState()
resumeReading()
@@ -145,78 +199,151 @@ final class TrainingCourseViewController: TrainingBaseViewController {
override func onSessionDidExpire() { identityChanged() }
private var isContentVisible: Bool {
pageIsVisible && contentIsReady && !contentLoadFailed && !isOpeningResource && presentedViewController == nil
let visibleFrame = previewView.convert(previewView.bounds, to: view).intersection(scrollView.frame)
return pageIsVisible && contentIsReady && viewModel.isAttachmentRendered && previewView.isReady
&& visibleFrame.height >= 40 && !contentLoadFailed && !isOpeningExternalLink && presentedViewController == nil
&& navigationController?.topViewController === self && appIsActive && UIApplication.shared.applicationState == .active
}
private func loadCourse() {
guard let request = beginUserRequest(showsLoading: true) else { return }
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.load() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
await performUserRequest(request) {
await self.viewModel.load()
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func selectSection(_ id: String) {
guard let request = beginUserRequest(showsLoading: !viewModel.isSectionCached(id: id)) else { return }
isOpeningResource = false
pauseReading()
contentIsReady = false
contentLoadFailed = false
contentNavigation = nil
private func selectAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
resetDocument()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.selectSection(id: id) }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
renderCurrentSection()
applyState()
await performUserRequest(request) {
await self.viewModel.selectAttachment(id: id)
await self.loadSelectedDocument()
}
self.applyMetadata()
self.applyState()
}
}
private func renderCurrentSection() {
guard !viewModel.isInvalidated, let task = viewModel.task?.summary,
let course = viewModel.course, let section = viewModel.currentSection else { return }
let metadata = task.mode == .exam
? "学习 + 考试 · \(course.sectionCount) 节 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格"
: "仅学习 · \(course.sectionCount) 节"
contentNavigation = webView.loadHTMLString("""
<!doctype html><html lang="zh-CN"><head><meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'">
<style>
*{box-sizing:border-box}body{font:15px -apple-system,BlinkMacSystemFont,sans-serif;color:#34435b;background:#f5f8fc;margin:0;padding:0 13px 14px;line-height:1.95;overflow-wrap:anywhere}
h1{font-size:17px;font-weight:600;line-height:1.6;color:#172033;margin:14px 0 6px}h2{font-size:15.5px;font-weight:600;color:#172033;margin:0 0 10px}img{max-width:100%;height:auto}table{max-width:100%;display:block;overflow:auto}a{color:#2379ff}
.muted{font-size:12.5px;color:#8491a6;line-height:1.65;margin:6px 0}.reading{background:white;border:1px solid #e3ebf5;border-radius:11px;padding:14px;margin-top:14px}
</style></head><body>
<h1>\(escape(task.title))</h1><p class='muted'>\(escape(course.title))</p><p class='muted'>\(metadata)</p><p class='muted'>\(escape(course.introduction))</p>
<p class='muted'>第 \(section.order) / \(course.sectionCount) 节</p><div class='reading'><h2>\(escape(section.title))</h2>\(section.contentHTML)</div></body></html>
""", baseURL: nil)
private func resetDocument() {
pauseReading()
contentIsReady = false
contentLoadFailed = false
previewView.showStatus("正在加载附件…")
localDocument?.removeTemporaryFile()
localDocument = nil
scrollView.setContentOffset(CGPoint(x: 0, y: -scrollView.adjustedContentInset.top), animated: false)
}
private func escape(_ text: String) -> String {
text.replacingOccurrences(of: "&", with: "&amp;").replacingOccurrences(of: "<", with: "&lt;")
.replacingOccurrences(of: ">", with: "&gt;").replacingOccurrences(of: "\"", with: "&quot;")
private func scrollToDocumentPosition(_ top: CGFloat) {
view.layoutIfNeeded()
let target = previewView.convert(CGPoint(x: 0, y: top), to: scrollView).y - scrollView.adjustedContentInset.top
let minimum = -scrollView.adjustedContentInset.top
let maximum = max(minimum, scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(CGPoint(x: 0, y: min(maximum, max(minimum, target))), animated: true)
}
private func loadSelectedDocument() async {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated else { return }
applyMetadata()
guard let attachment = viewModel.currentAttachment, let link = viewModel.currentAttachmentLink,
let previewID = viewModel.attachmentPreviewID else {
contentLoadFailed = viewModel.errorMessage != nil
previewView.showStatus(viewModel.errorMessage ?? "暂未上传课程附件")
return
}
do {
let document = try await documentLoader.load(attachment: attachment, link: link)
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { document.removeTemporaryFile(); return }
guard validateIdentity() else {
document.removeTemporaryFile()
identityChanged()
return
}
localDocument = document
previewView.show(document, requestID: previewID)
} catch {
guard !Task.isCancelled, pageIsVisible, !viewModel.isInvalidated,
viewModel.attachmentPreviewID == previewID else { return }
contentLoadFailed = true
viewModel.reportAttachmentFailure(id: attachment.id, previewID: previewID, message: error.localizedDescription)
previewView.showStatus(error.localizedDescription)
}
}
private func applyMetadata() {
guard let task = viewModel.task?.summary, let course = viewModel.course else { return }
metadataStack.isHidden = false
taskTitleLabel.text = task.title
courseNameLabel.text = course.title
courseNameLabel.isHidden = course.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
examInfoLabel.text = task.mode == .exam ? "学习 + 考试 · \(task.questionCount) 题 · \(task.passScore ?? 0) 分及格" : "仅学习"
introductionLabel.text = course.introduction
introductionLabel.isHidden = course.introduction.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
attachmentButton.isHidden = viewModel.currentAttachment == nil
var configuration = attachmentButton.configuration
configuration?.title = viewModel.currentAttachment?.name
let canSwitch = viewModel.attachments.count > 1 || viewModel.hasMoreAttachments
configuration?.image = canSwitch ? UIImage(systemName: "chevron.down") : nil
configuration?.imagePlacement = .trailing
configuration?.imagePadding = 8
configuration?.contentInsets = .zero
configuration?.titleLineBreakMode = .byWordWrapping
attachmentButton.configuration = configuration
attachmentButton.isUserInteractionEnabled = canSwitch && userRequestID == nil
var actions = viewModel.attachments.map { attachment in
UIAction(title: attachment.name, state: attachment.id == viewModel.currentAttachmentID ? .on : .off) { [weak self] _ in
guard attachment.id != self?.viewModel.currentAttachmentID else { return }
self?.selectAttachment(attachment.id)
}
}
if viewModel.hasMoreAttachments {
actions.append(UIAction(title: "加载更多附件") { [weak self] _ in self?.loadMoreAttachments() })
}
attachmentButton.menu = UIMenu(children: actions)
}
private func loadMoreAttachments() {
guard let request = beginUserRequest(showsLoading: true) else { return }
Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyMetadata()
if let message = viewModel.attachmentListErrorMessage { showToast(message) }
}
}
private func applyState() {
guard !viewModel.isInvalidated else { leaveUnavailableCourse(); return }
if let task = viewModel.task?.summary {
stepView.configure(mode: task.mode)
if stepView.superview == nil { headerStack.addArrangedSubview(stepView) }
stepView.isHidden = false
}
let canInteract = userRequestID == nil
sectionsButton.isUserInteractionEnabled = canInteract
attachmentsButton.isUserInteractionEnabled = canInteract
actionButton.isUserInteractionEnabled = canInteract
attachmentButton.isUserInteractionEnabled = canInteract && (viewModel.attachments.count > 1 || viewModel.hasMoreAttachments)
guard canInteract else { return }
sectionsButton.isEnabled = !viewModel.sections.isEmpty
attachmentsButton.isEnabled = (viewModel.course?.attachmentCount ?? 0) > 0
if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
noticeLabel.text = viewModel.errorMessage ?? "正在加载课程…"
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载附件" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
return
}
if viewModel.hasLoadedAttachments && viewModel.attachments.isEmpty {
noticeLabel.text = "暂未上传课程附件"
setActionTitle("返回培训中心")
actionButton.isEnabled = true
return
}
if let progress = viewModel.progress, progress.readingCompleted {
noticeLabel.text = viewModel.readingErrorMessage ?? "课程阅读已完成"
if viewModel.task?.summary.mode == .exam && progress.canStartExam { setActionTitle("开始考试") }
@@ -226,10 +353,10 @@ final class TrainingCourseViewController: TrainingBaseViewController {
readingTimer = nil
return
}
if contentLoadFailed || viewModel.currentSection == nil {
noticeLabel.text = viewModel.errorMessage ?? (contentLoadFailed ? "课程正文加载失败,请重试" : "正在加载课程…")
setActionTitle(contentLoadFailed || viewModel.errorMessage != nil ? "重新加载课程" : "正在加载课程…")
actionButton.isEnabled = !viewModel.isLoading && (contentLoadFailed || viewModel.errorMessage != nil)
if !contentIsReady {
noticeLabel.text = "正在打开课程附件…"
setActionTitle("正在加载附件…")
actionButton.isEnabled = false
return
}
if !viewModel.canStudy {
@@ -345,28 +472,36 @@ final class TrainingCourseViewController: TrainingBaseViewController {
contentTask?.cancel()
readingTask?.cancel()
closingTask?.cancel()
contentNavigation = nil
previewView.showStatus("")
localDocument?.removeTemporaryFile()
localDocument = nil
viewModel.invalidate()
leaveUnavailableCourse()
}
@objc private func actionTapped() {
guard userRequestID == nil else { return }
if let progress = viewModel.progress, progress.readingCompleted {
if contentLoadFailed || viewModel.attachmentErrorMessage != nil || viewModel.task == nil {
if let id = viewModel.currentAttachmentID { selectAttachment(id) }
else { loadCourse() }
} else if viewModel.attachments.isEmpty { returnToCenter() }
else if let progress = viewModel.progress, progress.readingCompleted {
pauseReading()
if viewModel.task?.summary.mode == .exam && progress.canStartExam {
navigationController?.pushViewController(TrainingExamViewController(taskID: taskID, service: service), animated: true)
} else { returnToCenter() }
} else if contentLoadFailed || viewModel.currentSection == nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
} else if !viewModel.canStudy { returnToCenter() }
else if viewModel.readingErrorMessage != nil {
resumeReading(retrying: true)
} else if viewModel.errorMessage != nil {
if let sectionID = viewModel.currentSectionID { selectSection(sectionID) }
else { loadCourse() }
}
else if viewModel.readingErrorMessage != nil { resumeReading(retrying: true) }
else if viewModel.errorMessage != nil { loadCourse() }
}
private func openExternalLink(_ url: URL) {
guard TrainingDocumentLoader.isAllowed(url), presentedViewController == nil else { return }
isOpeningExternalLink = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
}
private func returnToCenter() {
@@ -378,251 +513,34 @@ final class TrainingCourseViewController: TrainingBaseViewController {
private func leaveUnavailableCourse() {
readingTimer?.invalidate()
readingTimer = nil
contentNavigation = nil
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
previewView.showStatus("")
localDocument?.removeTemporaryFile()
localDocument = nil
if let presentedViewController {
presentedViewController.dismiss(animated: false) { [weak self] in self?.returnToCenter() }
} else { returnToCenter() }
}
@objc private func sectionsTapped() {
guard userRequestID == nil, !viewModel.sections.isEmpty else { return }
isOpeningResource = true
pauseReading()
let picker = TrainingCoursePickerViewController(title: "章节目录", rows: sectionRows(), hasMore: viewModel.hasMoreSections,
selectedID: viewModel.currentSectionID, select: { [weak self] id in self?.selectSection(id) },
loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreSections, let request = beginUserRequest(showsLoading: true) else {
return (sectionRows(), viewModel.hasMoreSections)
}
await performUserRequest(request) { await self.viewModel.loadMoreSections() }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (sectionRows(), viewModel.hasMoreSections)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
deinit { localDocument?.removeTemporaryFile() }
private func sectionRows() -> [TrainingCoursePickerRow] {
viewModel.sections.map { TrainingCoursePickerRow(id: $0.id, title: "\($0.order). \($0.title)") }
}
@objc private func attachmentsTapped() {
guard let request = beginUserRequest(showsLoading: !viewModel.hasLoadedAttachments) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
await performUserRequest(request) { await self.viewModel.loadAttachments() }
guard !Task.isCancelled, pageIsVisible, navigationController?.topViewController === self else { return }
if viewModel.isInvalidated { applyState(); return }
if let error = viewModel.errorMessage { isOpeningResource = false; showToast(error); applyState(); return }
let picker = TrainingCoursePickerViewController(title: "课程附件", rows: attachmentRows(), hasMore: viewModel.hasMoreAttachments,
select: { [weak self] id in self?.openAttachment(id) }, loadMore: { [weak self] in
guard let self else { return ([], false) }
guard viewModel.hasMoreAttachments, let request = beginUserRequest(showsLoading: true) else {
return (attachmentRows(), viewModel.hasMoreAttachments)
}
await performUserRequest(request) { await self.viewModel.loadAttachments(loadMore: true) }
applyState()
if let error = viewModel.errorMessage { showToast(error) }
return (attachmentRows(), viewModel.hasMoreAttachments)
}, close: { [weak self] in self?.finishResourcePresentation() })
presentPicker(picker)
}
}
private func attachmentRows() -> [TrainingCoursePickerRow] {
viewModel.attachments.map { TrainingCoursePickerRow(id: $0.id, title: $0.name) }
}
private func presentPicker(_ picker: TrainingCoursePickerViewController) {
let navigation = UINavigationController(rootViewController: picker)
navigation.modalPresentationStyle = .pageSheet
navigation.sheetPresentationController?.detents = [.medium(), .large()]
navigation.sheetPresentationController?.prefersGrabberVisible = true
navigation.presentationController?.delegate = picker
present(navigation, animated: true)
}
private func openAttachment(_ id: String) {
guard let request = beginUserRequest(showsLoading: true) else { return }
isOpeningResource = true
pauseReading()
contentTask = Task { @MainActor [weak self] in
guard let self else { return }
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
if let error = viewModel.errorMessage { showToast(error) }
applyState()
return
}
let controller = SFSafariViewController(url: link.url)
controller.delegate = self
present(controller, animated: true)
}
}
private func finishResourcePresentation() {
isOpeningResource = false
private func finishExternalLinkPresentation() {
isOpeningExternalLink = false
resumeReading()
}
}
extension TrainingCourseViewController: WKNavigationDelegate {
/// 当前正文渲染完成且页面可见后才开始有效阅读。
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = true
contentLoadFailed = false
applyState()
resumeReading()
}
/// 正文初始加载失败时停止计时,保留重试入口。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 正文导航失败时不把失败页面停留计入学习。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let contentNavigation, navigation === contentNavigation else { return }
contentIsReady = false
contentLoadFailed = true
pauseReading()
applyState()
}
/// 仅允许本机 HTML 初始加载;用户点击的 HTTPS 链接交给 Safari。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
if navigationAction.navigationType == .other, navigationAction.request.url?.absoluteString == "about:blank" {
decisionHandler(.allow)
return
}
decisionHandler(.cancel)
guard navigationAction.navigationType == .linkActivated,
let url = navigationAction.request.url, url.scheme?.lowercased() == "https", url.host != nil else { return }
isOpeningResource = true
pauseReading()
let controller = SFSafariViewController(url: url)
controller.delegate = self
present(controller, animated: true)
extension TrainingCourseViewController: UIScrollViewDelegate {
/// 原生课程信息滚动到覆盖整个预览区时暂停,文件再次可见时才恢复。
func scrollViewDidScroll(_ scrollView: UIScrollView) {
previewView.notifyIfRenderedAndVisible()
if isContentVisible { resumeReading() }
else if viewModel.isReading { pauseReading() }
}
}
extension TrainingCourseViewController: SFSafariViewControllerDelegate {
/// 关闭外部链接后,仅在正文重新可见时建立新的阅读片段。
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true) { [weak self] in self?.finishResourcePresentation() }
controller.dismiss(animated: true) { [weak self] in self?.finishExternalLinkPresentation() }
}
}
/// 目录或附件选择器的一行展示数据,不携带业务行为。
private struct TrainingCoursePickerRow: Hashable {
let id: String
let title: String
}
/// 原生可滚动资源选择器;用户按需加载更多,选中或关闭后明确通知课程页面。
@MainActor
private final class TrainingCoursePickerViewController: UIViewController, UITableViewDelegate, UIAdaptivePresentationControllerDelegate {
/// 差异化列表中的资源项与主动分页入口。
private enum Item: Hashable { case resource(String), more }
private var rows: [TrainingCoursePickerRow]
private var hasMore: Bool
private let selectedID: String?
private let select: (String) -> Void
private let loadMore: () async -> ([TrainingCoursePickerRow], Bool)
private let close: () -> Void
private let tableView = UITableView(frame: .zero, style: .insetGrouped)
private var dataSource: UITableViewDiffableDataSource<Int, Item>!
private var isLoadingMore = false
/// 使用页面提供的展示行、明确选择动作与分页动作构造选择器。
init(title: String, rows: [TrainingCoursePickerRow], hasMore: Bool, selectedID: String? = nil,
select: @escaping (String) -> Void, loadMore: @escaping () async -> ([TrainingCoursePickerRow], Bool), close: @escaping () -> Void) {
self.rows = rows
self.hasMore = hasMore
self.selectedID = selectedID
self.select = select
self.loadMore = loadMore
self.close = close
super.init(nibName: nil, bundle: nil)
self.title = title
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = TrainingUI.background
navigationItem.rightBarButtonItem = UIBarButtonItem(systemItem: .done, primaryAction: UIAction { [weak self] _ in
guard let self else { return }
dismiss(animated: true, completion: close)
})
tableView.delegate = self
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 52
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "resource")
view.addSubview(tableView)
tableView.snp.makeConstraints { $0.edges.equalTo(view.safeAreaLayoutGuide) }
dataSource = UITableViewDiffableDataSource<Int, Item>(tableView: tableView) { [weak self] table, indexPath, item in
guard let self else { return nil }
let cell = table.dequeueReusableCell(withIdentifier: "resource", for: indexPath)
var content = UIListContentConfiguration.cell()
switch item {
case .resource(let id):
content.text = rows.first(where: { $0.id == id })?.title
content.textProperties.numberOfLines = 0
cell.accessoryType = id == selectedID ? .checkmark : .none
case .more:
content.text = isLoadingMore ? "正在加载…" : "加载更多"
content.textProperties.color = TrainingUI.primary
cell.accessoryType = .none
}
cell.contentConfiguration = content
return cell
}
applyRows()
}
private func applyRows() {
var snapshot = NSDiffableDataSourceSnapshot<Int, Item>()
snapshot.appendSections([0])
snapshot.appendItems(rows.map { .resource($0.id) })
if hasMore { snapshot.appendItems([.more]) }
if hasMore, dataSource.snapshot().indexOfItem(.more) != nil { snapshot.reconfigureItems([.more]) }
dataSource.apply(snapshot, animatingDifferences: true)
}
/// 选择后等待模态页面完全关闭,再让课程加载正文或授权附件。
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard !isLoadingMore, let item = dataSource.itemIdentifier(for: indexPath) else { return }
switch item {
case .resource(let id): dismiss(animated: true) { [select] in select(id) }
case .more:
isLoadingMore = true
applyRows()
Task { @MainActor [weak self] in
guard let self else { return }
(rows, hasMore) = await loadMore()
isLoadingMore = false
applyRows()
}
}
}
/// 下拉关闭选择器时恢复正文可见性,由课程页面重新核验计时条件。
func presentationControllerDidDismiss(_ presentationController: UIPresentationController) { close() }
}
@@ -0,0 +1,335 @@
import PDFKit
import SnapKit
import UIKit
import WebKit
/// 白色卡片内的文件预览:PDF 使用 PDFKit,其他格式使用离线、受控的 WebView。
@MainActor
final class TrainingDocumentPreviewView: UIView {
/// 当前票据的文件已真正进入可阅读状态。
var onReady: ((UUID) -> Void)?
/// 当前票据的文件无法渲染,交由课程页面停止计时并展示重试。
var onFailure: ((UUID, String) -> Void)?
/// 用户明确点击文档外部链接。
var onOpenLink: ((URL) -> Void)?
/// 文档排版高度变化时通知课程页更新卡片高度,由外层页面统一滚动。
var onContentHeightChange: ((CGFloat) -> Void)?
/// 文档目录锚点的位置,由课程页在外层滚动区域中定位。
var onScrollToPosition: ((CGFloat) -> Void)?
/// 包含卡片边框的完整内容高度,加载和错误状态使用紧凑占位高度。
private(set) var preferredContentHeight: CGFloat = 160
/// 当前文件是否已渲染成功,供页面与布局测试查询。
private(set) var isReady = false
override var isHidden: Bool {
didSet { if !isHidden { pdfView.notifyIfRenderedAndVisible() } }
}
private let resourceHandler = TrainingDocumentResourceHandler()
private let messageProxy = TrainingDocumentMessageProxy()
private let pdfView = TrainingPDFDocumentView()
private let statusLabel = TrainingUI.text("正在加载附件…", size: 13, color: TrainingUI.muted)
private var currentID: UUID?
private var currentNavigation: WKNavigation?
private var renderWatchdog: Task<Void, Never>?
private lazy var webView: WKWebView = {
let configuration = WKWebViewConfiguration()
configuration.websiteDataStore = .nonPersistent()
configuration.setURLSchemeHandler(resourceHandler, forURLScheme: "training-document")
configuration.userContentController.add(messageProxy, name: "trainingDocument")
configuration.userContentController.addUserScript(WKUserScript(source: Self.pageLayoutScript,
injectionTime: .atDocumentStart, forMainFrameOnly: true))
let view = WKWebView(frame: .zero, configuration: configuration)
view.navigationDelegate = self
view.isOpaque = false
view.backgroundColor = .white
view.scrollView.backgroundColor = .white
view.scrollView.isScrollEnabled = false
view.scrollView.bounces = false
view.scrollView.contentInsetAdjustmentBehavior = .never
return view
}()
/// 创建独立文档沙箱,不共享登录 Cookie、业务脚本或 JS Bridge。
init() {
super.init(frame: .zero)
backgroundColor = .white
layer.cornerRadius = 11
layer.borderWidth = 1
layer.borderColor = TrainingUI.border.cgColor
clipsToBounds = true
accessibilityIdentifier = "training.reading.preview"
pdfView.backgroundColor = .white
pdfView.onContentHeightChange = { [weak self] height in
guard let self, self.currentID != nil else { return }
self.updateContentHeight(height)
}
pdfView.onOpenLink = { [weak self] url in
if TrainingDocumentLoader.isAllowed(url) { self?.onOpenLink?(url) }
}
statusLabel.textAlignment = .center
[pdfView, webView, statusLabel].forEach(addSubview)
pdfView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) }
webView.snp.makeConstraints { $0.edges.equalToSuperview().inset(1) }
statusLabel.snp.makeConstraints { $0.center.equalToSuperview(); $0.leading.trailing.equalToSuperview().inset(20) }
messageProxy.owner = self
showStatus("正在加载附件…")
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
/// 加载中、空态和失败态均停止显示旧文件。
func showStatus(_ message: String) {
renderWatchdog?.cancel()
renderWatchdog = nil
currentID = nil
currentNavigation = nil
isReady = false
setPreferredContentHeight(160)
webView.stopLoading()
resourceHandler.clear()
webView.isHidden = true
pdfView.isHidden = true
pdfView.onVisiblePageDrawn = nil
pdfView.document = nil
statusLabel.text = message
statusLabel.isHidden = false
}
/// 外层页面滚动后重新检查 PDF 已绘制页面是否真正进入阅读区域。
func notifyIfRenderedAndVisible() { pdfView.notifyIfRenderedAndVisible() }
/// 用唯一票据隔离同一附件重试时迟到的文档事件。
func show(_ document: TrainingLocalDocument, requestID: UUID) {
showStatus("正在打开附件…")
currentID = requestID
if document.kind == .pdf {
guard let pdf = PDFDocument(url: document.fileURL), !pdf.isLocked, pdf.pageCount > 0 else {
fail(requestID, message: TrainingDocumentError.invalidFile.localizedDescription)
return
}
pdfView.onVisiblePageDrawn = { [weak self, weak pdf] in
guard let self, let pdf, self.currentID == requestID,
self.pdfView.document === pdf, self.window != nil, !self.pdfView.isHidden else { return }
self.complete(requestID)
}
pdfView.document = pdf
pdfView.isHidden = false
layoutIfNeeded()
pdfView.layoutIfNeeded()
} else {
resourceHandler.configure(document: document, requestID: requestID)
webView.isHidden = false
let value = "training-document://preview/index.html?type=\(document.kind.rawValue)&requestId=\(requestID.uuidString)"
currentNavigation = webView.load(URLRequest(url: URL(string: value)!))
renderWatchdog = Task { @MainActor [weak self] in
do { try await Task.sleep(for: .seconds(40)) } catch { return }
self?.fail(requestID, message: "附件预览超时,请重试")
}
}
}
fileprivate func receive(_ message: WKScriptMessage) {
guard message.frameInfo.isMainFrame,
message.frameInfo.securityOrigin.protocol == "training-document",
message.frameInfo.securityOrigin.host == "preview",
let payload = message.body as? [String: Any], let rawID = payload["requestId"] as? String,
let id = UUID(uuidString: rawID), currentID == id else { return }
switch payload["type"] as? String {
case "ready":
if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) }
complete(id)
case "layout":
if let height = payload["height"] as? NSNumber { updateContentHeight(CGFloat(height.doubleValue)) }
case "scroll":
if isReady, let value = payload["top"] as? NSNumber {
let top = CGFloat(value.doubleValue)
if top.isFinite, top >= 0 { onScrollToPosition?(min(top + 1, preferredContentHeight)) }
}
case "error":
let message = (payload["message"] as? String).flatMap { $0.isEmpty || $0.count > 200 ? nil : $0 }
fail(id, message: message ?? "附件预览失败,文件可能已损坏或格式不受支持,请重试")
case "link":
if let value = payload["url"] as? String, let url = URL(string: value), TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) }
default: break
}
}
private func updateContentHeight(_ height: CGFloat) {
guard height.isFinite, height > 0 else { return }
setPreferredContentHeight(max(82, ceil(height) + 2))
}
private func setPreferredContentHeight(_ height: CGFloat) {
guard abs(height - preferredContentHeight) >= 1 else { return }
preferredContentHeight = height
onContentHeightChange?(height)
}
private func complete(_ id: UUID) {
guard currentID == id, !isReady else { return }
renderWatchdog?.cancel()
renderWatchdog = nil
isReady = true
statusLabel.isHidden = true
onReady?(id)
}
private func fail(_ id: UUID, message: String) {
guard currentID == id else { return }
currentID = nil
currentNavigation = nil
renderWatchdog?.cancel()
renderWatchdog = nil
webView.stopLoading()
resourceHandler.clear()
isReady = false
setPreferredContentHeight(160)
statusLabel.text = message
statusLabel.isHidden = false
webView.isHidden = true
pdfView.isHidden = true
onFailure?(id, message)
}
// 只注入 iOS 宿主:观察内容本身而非 WebView 视口,短文件才能正确缩回。
// 锚点交给外层 UIScrollView,避免 scrollIntoView 在禁用手势后仍改变内部偏移。
private static let pageLayoutScript = """
(function () {
'use strict';
var requestId = new URLSearchParams(window.location.search).get('requestId');
function post(type, fields) {
var message = Object.assign({ type: type, requestId: requestId }, fields);
window.webkit.messageHandlers.trainingDocument.postMessage(message);
}
document.addEventListener('click', function (event) {
var link = event.target instanceof Element ? event.target.closest('a') : null;
var href = link && link.getAttribute('href');
if (!href || href.charAt(0) !== '#') { return; }
event.preventDefault();
event.stopImmediatePropagation();
var identifier;
try { identifier = decodeURIComponent(href.slice(1)); } catch (_) { return; }
var target = document.getElementById(identifier);
if (target) { post('scroll', { top: Math.max(0, target.getBoundingClientRect().top + window.scrollY) }); }
}, true);
function observe() {
var content = document.getElementById('document');
if (!content) { return; }
var scheduled = false;
var previousHeight = 0;
function measure() {
scheduled = false;
if (content.hidden) { return; }
var height = Math.ceil(Math.max(content.scrollHeight, content.getBoundingClientRect().height));
if (height > 0 && height !== previousHeight) {
previousHeight = height;
post('layout', { height: height });
}
}
function schedule() {
if (scheduled) { return; }
scheduled = true;
requestAnimationFrame(measure);
}
new ResizeObserver(schedule).observe(content);
new MutationObserver(schedule).observe(content, { attributes: true, attributeFilter: ['hidden'] });
window.addEventListener('resize', schedule);
schedule();
}
if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', observe, { once: true }); }
else { observe(); }
}());
"""
}
extension TrainingDocumentPreviewView: WKNavigationDelegate {
/// WebView 只加载 App 提供的本地预览壳,文档不能直接导航到远端网页。
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction,
decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
let url = navigationAction.request.url
let local = url?.scheme == "training-document" && url?.host == "preview" && url?.path == "/index.html"
decisionHandler(local ? .allow : .cancel)
if navigationAction.navigationType == .linkActivated, let url, TrainingDocumentLoader.isAllowed(url) { onOpenLink?(url) }
}
/// 壳加载失败不会触发阅读成功事件。
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return }
if let id = currentID { fail(id, message: "附件预览加载失败,请重试") }
}
/// 当前壳已开始导航后失败,同样撤销预览状态。
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
guard let currentNavigation, navigation === currentNavigation, (error as NSError).code != NSURLErrorCancelled else { return }
if let id = currentID { fail(id, message: "附件预览加载失败,请重试") }
}
/// 文档渲染进程退出时立即撤销可阅读状态。
func webViewWebContentProcessDidTerminate(_ webView: WKWebView) {
if currentNavigation != nil, !webView.isHidden, let id = currentID { fail(id, message: "附件预览已中断,请重试") }
}
}
/// 弱引用消息转发,避免 WKUserContentController 长期持有预览视图。
@MainActor
private final class TrainingDocumentMessageProxy: NSObject, WKScriptMessageHandler {
weak var owner: TrainingDocumentPreviewView?
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { owner?.receive(message) }
}
/// 仅响应当前票据的私有文件和固定 App 资源,不代理任何远程地址。
@MainActor
private final class TrainingDocumentResourceHandler: NSObject, WKURLSchemeHandler {
private var document: TrainingLocalDocument?
private var requestID: UUID?
private var active: Set<ObjectIdentifier> = []
func configure(document: TrainingLocalDocument, requestID: UUID) { self.document = document; self.requestID = requestID }
func clear() { document = nil; requestID = nil; active.removeAll() }
func webView(_ webView: WKWebView, start urlSchemeTask: any WKURLSchemeTask) {
let token = ObjectIdentifier(urlSchemeTask)
guard let url = urlSchemeTask.request.url, url.scheme == "training-document", url.host == "preview" else {
urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return
}
let file: URL?
let mime: String
if let requestID, url.path == "/document/\(requestID.uuidString)/file", let document {
file = document.fileURL
mime = "application/octet-stream"
} else {
let path = url.path.dropFirst()
guard !path.contains(".."), !path.hasPrefix("/"), !path.isEmpty,
let root = Bundle.main.url(forResource: "TrainingDocumentPreview", withExtension: nil) else {
urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return
}
file = root.appendingPathComponent(String(path))
switch (String(path) as NSString).pathExtension {
case "html": mime = "text/html"
case "js": mime = "text/javascript"
case "css": mime = "text/css"
default: urlSchemeTask.didFailWithError(URLError(.unsupportedURL)); return
}
}
guard let file else { urlSchemeTask.didFailWithError(URLError(.fileDoesNotExist)); return }
active.insert(token)
Task { @MainActor [weak self] in
let result = await Task.detached(priority: .userInitiated) { Result { try Data(contentsOf: file) } }.value
guard let self, self.active.remove(token) != nil else { return }
switch result {
case .success(let data):
let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: [
"Content-Type": "\(mime); charset=utf-8", "Cache-Control": "no-store", "Access-Control-Allow-Origin": "*"
])!
urlSchemeTask.didReceive(response)
urlSchemeTask.didReceive(data)
urlSchemeTask.didFinish()
case .failure(let error): urlSchemeTask.didFailWithError(error)
}
}
}
func webView(_ webView: WKWebView, stop urlSchemeTask: any WKURLSchemeTask) { active.remove(ObjectIdentifier(urlSchemeTask)) }
}
@@ -0,0 +1,247 @@
import PDFKit
import UIKit
/// 将 PDF 按页面宽度展开为原生绘制视图,由课程页统一负责纵向滚动。
@MainActor
final class TrainingPDFDocumentView: UIView {
/// 当前附件;替换文档时清除旧页面和绘制状态。
var document: PDFDocument? {
didSet { rebuildPages() }
}
/// 至少一个实际完成绘制的页面进入课程页可见区域。
var onVisiblePageDrawn: (() -> Void)?
/// 用户点击 PDF 中的 URL 注解,由宿主校验并打开。
var onOpenLink: ((URL) -> Void)?
/// 按当前宽度排版后的全部页面高度,供宿主更新白色卡片约束。
var onContentHeightChange: ((CGFloat) -> Void)?
private var pageViews: [TrainingPDFPageDrawingView] = []
private var contentHeight: CGFloat = 0
private var lastLayoutWidth: CGFloat = 0
private let pageSpacing: CGFloat = 12
override var intrinsicContentSize: CGSize {
CGSize(width: UIView.noIntrinsicMetric, height: contentHeight)
}
override var isHidden: Bool {
didSet { if !isHidden { notifyIfRenderedAndVisible() } }
}
/// 创建不含内部滚动视图的 PDF 页面容器。
init() {
super.init(frame: .zero)
backgroundColor = .white
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
let width = bounds.width
guard width.isFinite, width > 0 else { return }
if abs(width - lastLayoutWidth) > 0.5 {
lastLayoutWidth = width
var offset: CGFloat = 0
for page in pageViews {
let height = ceil(width * page.heightToWidthRatio)
page.frame = CGRect(x: 0, y: offset, width: width, height: height)
offset += height + pageSpacing
}
let height = pageViews.isEmpty ? 0 : offset - pageSpacing
updateContentHeight(height)
}
notifyIfRenderedAndVisible()
}
override func didMoveToWindow() {
super.didMoveToWindow()
notifyIfRenderedAndVisible()
}
/// 外层滚动、隐藏恢复或布局更新后,确认已绘制内容确实与可见区域相交。
func notifyIfRenderedAndVisible() {
guard document != nil, pageViews.contains(where: { $0.hasVisibleDrawnTile() }) else { return }
onVisiblePageDrawn?()
}
private func rebuildPages() {
pageViews.forEach { $0.removeFromSuperview() }
pageViews.removeAll()
lastLayoutWidth = 0
let drawingLock = NSLock()
if let document {
for index in 0..<document.pageCount {
guard let page = document.page(at: index),
let pageView = TrainingPDFPageDrawingView(document: document, page: page, drawingLock: drawingLock) else { continue }
pageView.onDrawn = { [weak self] in self?.notifyIfRenderedAndVisible() }
pageView.onOpenLink = { [weak self] url in self?.onOpenLink?(url) }
pageViews.append(pageView)
addSubview(pageView)
}
}
if pageViews.isEmpty { updateContentHeight(0) }
setNeedsLayout()
}
private func updateContentHeight(_ height: CGFloat) {
guard height.isFinite, abs(contentHeight - height) > 0.5 else { return }
contentHeight = height
invalidateIntrinsicContentSize()
onContentHeightChange?(height)
}
}
/// 单页使用分块图层按需绘制,避免将长 PDF 的所有页面预先生成大图。
@MainActor
private final class TrainingPDFPageDrawingView: UIView {
let heightToWidthRatio: CGFloat
var onDrawn: (() -> Void)?
var onOpenLink: ((URL) -> Void)?
private let drawingState: TrainingPDFPageDrawingState
private var drawnTiles: [CGRect] = []
private var lastDrawingSize: CGSize = .zero
override class var layerClass: AnyClass { TrainingPDFPageTiledLayer.self }
init?(document: PDFDocument, page: PDFPage, drawingLock: NSLock) {
let transform = page.transform(for: .cropBox)
let displayBounds = page.bounds(for: .cropBox).applying(transform).standardized
guard displayBounds.width.isFinite, displayBounds.height.isFinite,
displayBounds.width > 0, displayBounds.height > 0 else { return nil }
heightToWidthRatio = displayBounds.height / displayBounds.width
drawingState = TrainingPDFPageDrawingState(document: document, page: page,
displayBounds: displayBounds, pageTransform: transform, drawingLock: drawingLock)
super.init(frame: .zero)
backgroundColor = .white
isOpaque = true
accessibilityLabel = page.label.map { "PDF 第 \($0) 页" } ?? "PDF 页面"
let tiledLayer = layer as! TrainingPDFPageTiledLayer
tiledLayer.contentsScale = UIScreen.main.scale
tiledLayer.tileSize = CGSize(width: 512, height: 512)
tiledLayer.levelsOfDetail = 1
tiledLayer.levelsOfDetailBias = 0
tiledLayer.needsDisplayOnBoundsChange = true
drawingState.onDraw = { [weak self] rect, size in
Task { @MainActor [weak self] in
guard let self, self.bounds.size == size else { return }
if !self.drawnTiles.contains(rect) { self.drawnTiles.append(rect) }
self.onDrawn?()
}
}
tiledLayer.configure(drawingState)
addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(openLink(_:))))
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override func layoutSubviews() {
super.layoutSubviews()
if bounds.size != lastDrawingSize {
lastDrawingSize = bounds.size
drawnTiles.removeAll()
layer.setNeedsDisplay()
}
}
func hasVisibleDrawnTile() -> Bool {
guard let window, !drawnTiles.isEmpty else { return false }
var visible = convert(bounds, to: window).intersection(window.bounds)
var ancestor: UIView? = self
while let view = ancestor {
guard !view.isHidden, view.alpha > 0.01 else { return false }
if view.clipsToBounds { visible = visible.intersection(view.convert(view.bounds, to: window)) }
guard !visible.isNull, !visible.isEmpty else { return false }
ancestor = view.superview
}
return drawnTiles.contains { !convert($0, to: window).intersection(visible).isEmpty }
}
@objc private func openLink(_ gesture: UITapGestureRecognizer) {
guard let url = drawingState.link(at: gesture.location(in: self), size: bounds.size) else { return }
onOpenLink?(url)
}
}
/// 持有不可变页数据,以文档级锁串行化后台绘制和主线程链接查询。
private final class TrainingPDFPageDrawingState: @unchecked Sendable {
private let document: PDFDocument
private let page: PDFPage
private let displayBounds: CGRect
private let pageTransform: CGAffineTransform
private let drawingLock: NSLock
var onDraw: (@Sendable (CGRect, CGSize) -> Void)?
init(document: PDFDocument, page: PDFPage, displayBounds: CGRect,
pageTransform: CGAffineTransform, drawingLock: NSLock) {
self.document = document
self.page = page
self.displayBounds = displayBounds
self.pageTransform = pageTransform
self.drawingLock = drawingLock
}
func draw(in context: CGContext, bounds: CGRect) {
guard bounds.width > 0, bounds.height > 0 else { return }
let tile = context.boundingBoxOfClipPath.intersection(bounds)
guard !tile.isNull, !tile.isEmpty else { return }
drawingLock.lock()
context.saveGState()
context.setFillColor(UIColor.white.cgColor)
context.fill(bounds)
let scale = bounds.width / displayBounds.width
context.translateBy(x: -displayBounds.minX * scale, y: bounds.height + displayBounds.minY * scale)
context.scaleBy(x: scale, y: -scale)
page.draw(with: .cropBox, to: context)
context.restoreGState()
drawingLock.unlock()
onDraw?(tile, bounds.size)
}
func link(at point: CGPoint, size: CGSize) -> URL? {
guard size.width > 0 else { return nil }
drawingLock.lock()
defer { drawingLock.unlock() }
let scale = size.width / displayBounds.width
let displayPoint = CGPoint(x: point.x / scale + displayBounds.minX,
y: (size.height - point.y) / scale + displayBounds.minY)
let pagePoint = displayPoint.applying(pageTransform.inverted())
return page.annotation(at: pagePoint)?.url
}
}
/// CATiledLayer 可在后台请求图块;状态快照受锁保护,回调仅返回已绘制的页内矩形。
private final class TrainingPDFPageTiledLayer: CATiledLayer {
private let stateLock = NSLock()
private var state: TrainingPDFPageDrawingState?
override class func fadeDuration() -> CFTimeInterval { 0 }
override init() { super.init() }
override init(layer: Any) {
super.init(layer: layer)
if let source = layer as? TrainingPDFPageTiledLayer { state = source.snapshot() }
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
func configure(_ state: TrainingPDFPageDrawingState) {
stateLock.lock()
self.state = state
stateLock.unlock()
setNeedsDisplay()
}
override func draw(in context: CGContext) { snapshot()?.draw(in: context, bounds: bounds) }
private func snapshot() -> TrainingPDFPageDrawingState? {
stateLock.lock()
defer { stateLock.unlock() }
return state
}
}
@@ -7,6 +7,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
private let taskID: String
private let attemptID: String
private let service: any TrainingDataServing
private let documentLoader: any TrainingDocumentLoading
private let viewModel: TrainingRemoteResultViewModel
private let validateIdentity: () -> Bool
private var loadFailed = false
@@ -21,10 +22,12 @@ final class TrainingResultViewController: TrainingBaseViewController {
private let actionButton = TrainingUI.button("完成,返回培训中心")
/// 使用记录 ID 读取最新本人任务,禁止通过后从旧失败记录继续重考。
init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil) {
init(taskID: String, attemptID: String, service: any TrainingDataServing, initialDetail: TrainingAttemptDetail? = nil,
documentLoader: any TrainingDocumentLoading = TrainingDocumentLoader()) {
self.taskID = taskID
self.attemptID = attemptID
self.service = service
self.documentLoader = documentLoader
let session = AppStore.shared.session
let scope = session.accountCachePrefix
let token = session.token
@@ -281,7 +284,7 @@ final class TrainingResultViewController: TrainingBaseViewController {
if let course = navigationController.viewControllers.last(where: { ($0 as? TrainingCourseViewController)?.taskID == taskID }) {
navigationController.popToViewController(course, animated: true)
} else {
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service), animated: true)
navigationController.pushViewController(TrainingCourseViewController(taskID: taskID, service: service, documentLoader: documentLoader), animated: true)
}
}