index.uts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import { URL } from "Foundation";
  2. import { UIApplication } from "UIKit";
  3. /**
  4. * 在iOS设备上打开指定的网页URL
  5. * @param url 要打开的网页地址,支持http、https、tel、mailto等协议
  6. * @returns 返回操作结果,true表示成功,false表示失败
  7. */
  8. export function openWeb(url: string): boolean {
  9. // 参数验证:检查URL是否为空或无效
  10. if (url == null || url.trim() == "") {
  11. console.error("openWeb: URL参数不能为空");
  12. return false;
  13. }
  14. try {
  15. // 创建URL对象,用于验证URL格式的有效性
  16. let href = new URL((string = url.trim()));
  17. // 检查URL对象是否创建成功
  18. if (href == null) {
  19. console.error("openWeb: 无效的URL格式 -", url);
  20. return false;
  21. }
  22. // 检查系统版本,iOS 16.0及以上版本使用新的API
  23. if (UTSiOS.available("iOS 16.0, *")) {
  24. // iOS 16.0+ 使用 open(_:options:completionHandler:) 方法
  25. // 先检查系统是否支持打开该URL
  26. if (UIApplication.shared.canOpenURL(href!)) {
  27. // 使用新API打开URL,传入空的options和completionHandler
  28. UIApplication.shared.open(href!, (options = new Map()), (completionHandler = nil));
  29. console.log("openWeb: 成功使用新API打开URL -", url);
  30. return true;
  31. } else {
  32. console.warn("openWeb: 系统不支持打开该URL协议 -", url);
  33. return false;
  34. }
  35. } else {
  36. // iOS 16.0以下版本使用已弃用但仍可用的 openURL 方法
  37. // 先检查系统是否支持打开该URL
  38. if (UIApplication.shared.canOpenURL(href!)) {
  39. // 使用传统API打开URL
  40. UIApplication.shared.openURL(href!);
  41. console.log("openWeb: 成功使用传统API打开URL -", url);
  42. return true;
  43. } else {
  44. console.warn("openWeb: 系统不支持打开该URL协议 -", url);
  45. return false;
  46. }
  47. }
  48. } catch (e) {
  49. // 捕获可能的异常,如URL格式错误等
  50. console.error("openWeb: 打开URL时发生错误 -", e);
  51. return false;
  52. }
  53. }