WebViewController.m 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. //
  2. // WebViewController.m
  3. // AIIM
  4. //
  5. // Created by on 2025/10/23.
  6. //
  7. #import "WebViewController.h"
  8. #import <WebKit/WebKit.h>
  9. @interface WebViewController () <WKNavigationDelegate, WKUIDelegate>
  10. @property (nonatomic, strong) WKWebView *webView;
  11. @property (nonatomic, strong) UIProgressView *progressView;
  12. @property (nonatomic, strong) UIButton *backButton;
  13. @property (nonatomic, strong) UILabel *titleLabel;
  14. @end
  15. @implementation WebViewController
  16. #pragma mark - Lifecycle
  17. - (instancetype)initWithURL:(NSURL *)url {
  18. return [self initWithURL:url title:nil];
  19. }
  20. - (instancetype)initWithURL:(NSURL *)url title:(NSString *)title {
  21. self = [super init];
  22. if (self) {
  23. _url = url;
  24. self.title = title;
  25. self.hidesBottomBarWhenPushed = YES;
  26. }
  27. return self;
  28. }
  29. - (void)viewDidLoad {
  30. [super viewDidLoad];
  31. [self setupUI];
  32. [self setupNavigationBar];
  33. [self setupWebView];
  34. if (self.url) {
  35. [self loadURL:self.url];
  36. }
  37. }
  38. - (void)dealloc {
  39. [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
  40. [self.webView removeObserver:self forKeyPath:@"title"];
  41. [self.webView removeObserver:self forKeyPath:@"canGoBack"];
  42. [self.webView removeObserver:self forKeyPath:@"canGoForward"];
  43. }
  44. #pragma mark - UI Setup
  45. - (void)setupUI {
  46. self.view.backgroundColor = [UIColor blackColor];
  47. }
  48. - (void)setupWebView {
  49. // 配置 WKWebView
  50. WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
  51. configuration.allowsInlineMediaPlayback = YES;
  52. configuration.mediaTypesRequiringUserActionForPlayback = WKAudiovisualMediaTypeNone;
  53. // 创建 WKWebView
  54. self.webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
  55. self.webView.navigationDelegate = self;
  56. self.webView.UIDelegate = self;
  57. self.webView.allowsBackForwardNavigationGestures = YES;
  58. [self.view addSubview:self.webView];
  59. [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
  60. make.left.right.bottom.equalTo(self.view);
  61. make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(0);
  62. }];
  63. // 添加 KVO 监听
  64. [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
  65. [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
  66. [self.webView addObserver:self forKeyPath:@"canGoBack" options:NSKeyValueObservingOptionNew context:nil];
  67. [self.webView addObserver:self forKeyPath:@"canGoForward" options:NSKeyValueObservingOptionNew context:nil];
  68. }
  69. - (void)setupNavigationBar {
  70. self.titleLabel = [UILabel new];
  71. self.titleLabel.text = self.title;
  72. self.titleLabel.textColor = [UIColor whiteColor];
  73. self.titleLabel.font = SYSBFONT(18);
  74. [self.view addSubview:self.titleLabel];
  75. [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
  76. make.centerX.equalTo(self.view);
  77. make.width.mas_lessThanOrEqualTo(200);
  78. make.top.equalTo(self.view).mas_offset(STATUS_Height);
  79. make.height.mas_equalTo(44);
  80. }];
  81. self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
  82. [self.backButton setImage:kImageMake(@"fanhui") forState:UIControlStateNormal];
  83. [self.backButton addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
  84. [self.view addSubview:self.backButton];
  85. [self.backButton mas_makeConstraints:^(MASConstraintMaker *make) {
  86. make.left.equalTo(self.view).mas_offset(10);
  87. make.centerY.equalTo(self.titleLabel);
  88. make.size.mas_equalTo(CGSizeMake(32, 32));
  89. }];
  90. // 进度条
  91. self.progressView = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
  92. self.progressView.progressTintColor = globalColor(GCTypeGreen);
  93. self.progressView.trackTintColor = [UIColor clearColor];
  94. self.progressView.translatesAutoresizingMaskIntoConstraints = NO;
  95. [self.view addSubview:self.progressView];
  96. [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
  97. make.left.right.equalTo(self.view);
  98. make.top.equalTo(self.titleLabel.mas_bottom).mas_offset(0);
  99. make.height.mas_equalTo(2);
  100. }];
  101. }
  102. #pragma mark - Actions
  103. - (void)closeButtonTapped {
  104. [self dismissViewControllerAnimated:YES completion:nil];
  105. }
  106. - (void)goBack {
  107. if ([self.webView canGoBack]) {
  108. [self.webView goBack];
  109. } else {
  110. [self.navigationController popViewControllerAnimated:YES];
  111. }
  112. }
  113. #pragma mark - Private Methods
  114. - (void)loadURL:(NSURL *)url {
  115. NSURLRequest *request = [NSURLRequest requestWithURL:url];
  116. [self.webView loadRequest:request];
  117. }
  118. #pragma mark - KVO
  119. - (void)observeValueForKeyPath:(NSString *)keyPath
  120. ofObject:(id)object
  121. change:(NSDictionary<NSKeyValueChangeKey,id> *)change
  122. context:(void *)context {
  123. if ([keyPath isEqualToString:@"estimatedProgress"]) {
  124. // 更新进度条
  125. float progress = [[change objectForKey:NSKeyValueChangeNewKey] floatValue];
  126. [self.progressView setProgress:progress animated:YES];
  127. // 进度完成时隐藏进度条
  128. if (progress >= 1.0) {
  129. dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
  130. self.progressView.hidden = YES;
  131. });
  132. } else {
  133. self.progressView.hidden = NO;
  134. }
  135. }
  136. else if ([keyPath isEqualToString:@"title"]) {
  137. NSString *title = [change objectForKey:NSKeyValueChangeNewKey];
  138. self.title = title.length > 0 ? title : @"网页";
  139. self.titleLabel.text = self.title;
  140. }
  141. else if ([keyPath isEqualToString:@"canGoBack"] || [keyPath isEqualToString:@"canGoForward"]) {
  142. // 更新导航按钮状态
  143. }
  144. }
  145. #pragma mark - WKNavigationDelegate
  146. - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
  147. self.progressView.hidden = NO;
  148. }
  149. - (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
  150. }
  151. - (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
  152. if (error.code != NSURLErrorCancelled) {
  153. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"加载失败"
  154. message:error.localizedDescription
  155. preferredStyle:UIAlertControllerStyleAlert];
  156. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定"
  157. style:UIAlertActionStyleDefault
  158. handler:nil];
  159. [alert addAction:okAction];
  160. [self presentViewController:alert animated:YES completion:nil];
  161. }
  162. }
  163. - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
  164. NSURL *url = navigationAction.request.URL;
  165. // 处理特殊 URL scheme
  166. if (![url.scheme isEqualToString:@"http"] && ![url.scheme isEqualToString:@"https"]) {
  167. // 尝试打开外部应用
  168. if ([[UIApplication sharedApplication] canOpenURL:url]) {
  169. [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
  170. }
  171. decisionHandler(WKNavigationActionPolicyCancel);
  172. return;
  173. }
  174. decisionHandler(WKNavigationActionPolicyAllow);
  175. }
  176. @end