เอกสารอธิบายการผสานรวมพื้นที่ทำงานบน iOS
เอกสารอธิบายการผสานรวมพื้นที่ทำงานบน iOS
คู่มือนี้อธิบายรายละเอียดเกี่ยวกับวิธีการผสานรวมพื้นที่ทำงาน GPTBots ในแอปพลิเคชัน iOS รวมถึงการขอสิทธิ์ การโต้ตอบระหว่างเนทีฟกับ H5 และการกำหนดค่าอื่น ๆ ที่เกี่ยวข้อง
GPTBots ยังมีโปรเจกต์ DEMO ของพื้นที่ทำงานให้ด้วย เพื่อช่วยให้คุณเริ่มต้นได้อย่างรวดเร็ว โปรเจกต์ DEMO บน iOS: ios-webview-bridge
ข้อกำหนดการกำหนดค่าพื้นฐาน
- iOS 13.0 หรือเวอร์ชันที่สูงกว่า
- Xcode 12.0 หรือเวอร์ชันที่สูงกว่า
- Swift 5.0 หรือเวอร์ชันที่สูงกว่า
เพิ่มเฟรมเวิร์กที่จำเป็น
โปรเจกต์ต้องการเฟรมเวิร์กต่อไปนี้:
- WebKit
- AVFoundation (สำหรับการเข้าถึงไมโครโฟน)
- Photos (สำหรับการเข้าถึงคลังภาพ)
- MobileCoreServices (สำหรับการเลือกไฟล์)
ใน iOS 14 ขึ้นไป ยังสามารถใช้:
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
#if canImport(UniformTypeIdentifiers)
import UniformTypeIdentifiers
#endif
บล็อกโค้ดนี้ในหน้าต่างลอย
กำหนดค่า Info.plist
เพิ่มการกำหนดค่าต่อไปนี้ใน Info.plist:
<!-- 允许HTTP请求 -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>gptbots-auto.qa.jpushoa.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
<!-- 允许HTTP请求 -->
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
<key>NSExceptionDomains</key>
<dict>
<key>gptbots-auto.qa.jpushoa.com</key>
<dict>
<key>NSExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSExceptionMinimumTLSVersion</key>
<string>TLSv1.0</string>
<key>NSIncludesSubdomains</key>
<true/>
</dict>
</dict>
</dict>
บล็อกโค้ดนี้ในหน้าต่างลอย
การกำหนดค่าสิทธิ์
แอปพลิเคชันต้องการสิทธิ์ต่อไปนี้:
สิทธิ์กล้อง
<key>NSCameraUsageDescription</key>
<string>This app needs to use the camera to support photo capture features in web pages</string>
<key>NSCameraUsageDescription</key>
<string>This app needs to use the camera to support photo capture features in web pages</string>
บล็อกโค้ดนี้ในหน้าต่างลอย
สิทธิ์ไมโครโฟน
<key>NSMicrophoneUsageDescription</key>
<string>This app needs to use the microphone to support audio recording features in web pages</string>
<key>NSMicrophoneUsageDescription</key>
<string>This app needs to use the microphone to support audio recording features in web pages</string>
บล็อกโค้ดนี้ในหน้าต่างลอย
สิทธิ์คลังภาพ
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs to access your photo library to select images and video files</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>This app needs to access your photo library to select images and video files</string>
บล็อกโค้ดนี้ในหน้าต่างลอย
สิทธิ์การเข้าถึงเอกสาร
<key>NSDocumentUsageDescription</key>
<string>This app needs to access documents to support file upload features in web pages</string>
<key>NSDocumentUsageDescription</key>
<string>This app needs to access documents to support file upload features in web pages</string>
บล็อกโค้ดนี้ในหน้าต่างลอย
การโต้ตอบระหว่างเนทีฟกับ WebView
สร้างคอนโทรลเลอร์ WebView
สร้างคอนโทรลเลอร์ที่ใช้สำหรับแสดง WebView โดยเฉพาะ:
class WebViewController: UIViewController {
private var webView: WKWebView!
private var webViewBridge: WebViewBridge!
var urlString: String = ""
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
setupWebViewBridge()
loadURL()
}
private func setupWebView() {
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
configuration.applicationNameForUserAgent = "WebViewApp/1.0"
webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
view.addSubview(webView)
}
private func loadURL() {
guard !urlString.isEmpty, let url = URL(string: urlString) else {
return
}
let request = URLRequest(url: url)
webView.load(request)
}
}
class WebViewController: UIViewController {
private var webView: WKWebView!
private var webViewBridge: WebViewBridge!
var urlString: String = ""
override func viewDidLoad() {
super.viewDidLoad()
setupWebView()
setupWebViewBridge()
loadURL()
}
private func setupWebView() {
let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
configuration.applicationNameForUserAgent = "WebViewApp/1.0"
webView = WKWebView(frame: view.bounds, configuration: configuration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
webView.navigationDelegate = self
webView.uiDelegate = self
view.addSubview(webView)
}
private func loadURL() {
guard !urlString.isEmpty, let url = URL(string: urlString) else {
return
}
let request = URLRequest(url: url)
webView.load(request)
}
}
บล็อกโค้ดนี้ในหน้าต่างลอย
สร้างบริดจ์ JavaScript
สร้างคลาสบริดจ์สำหรับการสื่อสารระหว่างโค้ดเนทีฟกับ JavaScript:
class WebViewBridge: NSObject {
static let EVENT_CLICK = "click"
static let EVENT_MESSAGE = "message"
private weak var webView: WKWebView?
weak var delegate: WebViewBridgeDelegate?
init(webView: WKWebView, viewController: UIViewController) {
self.webView = webView
super.init()
}
func registerJSInterface() {
webView?.configuration.userContentController.add(self, name: "agentWebBridge")
}
func callH5(eventType: String, data: [String: Any]) {
let message: [String: Any] = [
"eventType": eventType,
"data": data
]
if let jsonData = try? JSONSerialization.data(withJSONObject: message),
let jsonString = String(data: jsonData, encoding: .utf8) {
let escapedJson = jsonString
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "'", with: "\\'")
.replacingOccurrences(of: "\"", with: "\\\"")
let jsCode = "window.onCallH5Message('\(escapedJson)')"
webView?.evaluateJavaScript(jsCode)
}
}
}
class WebViewBridge: NSObject {
static let EVENT_CLICK = "click"
static let EVENT_MESSAGE = "message"
private weak var webView: WKWebView?
weak var delegate: WebViewBridgeDelegate?
init(webView: WKWebView, viewController: UIViewController) {
self.webView = webView
super.init()
}
func registerJSInterface() {
webView?.configuration.userContentController.add(self, name: "agentWebBridge")
}
func callH5(eventType: String, data: [String: Any]) {
let message: [String: Any] = [
"eventType": eventType,
"data": data
]
if let jsonData = try? JSONSerialization.data(withJSONObject: message),
let jsonString = String(data: jsonData, encoding: .utf8) {
let escapedJson = jsonString
.replacingOccurrences(of: "\\", with: "\\\\")
.replacingOccurrences(of: "'", with: "\\'")
.replacingOccurrences(of: "\"", with: "\\\"")
let jsCode = "window.onCallH5Message('\(escapedJson)')"
webView?.evaluateJavaScript(jsCode)
}
}
}
บล็อกโค้ดนี้ในหน้าต่างลอย
ใช้งานเมธอด delegate ของ WebView
ใช้งานเมธอด delegate ของ WebView ที่จำเป็น เพื่อจัดการการเลือกไฟล์ การขอสิทธิ์ ฯลฯ:
extension WebViewController: WKUIDelegate {
// 处理文件上传
@available(iOS 18.4, *)
func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters,
initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) {
let alert = UIAlertController(title: "Select File", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Select from Photos", style: .default) { _ in
self.presentImagePicker(completionHandler: completionHandler)
})
alert.addAction(UIAlertAction(title: "Select from Files", style: .default) { _ in
self.presentDocumentPicker(completionHandler: completionHandler)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionHandler(nil)
})
present(alert, animated: true)
}
// 处理媒体权限请求
@available(iOS 15.0, *)
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin,
initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType,
decisionHandler: @escaping (WKPermissionDecision) -> Void) {
switch type {
case .microphone:
// 检查麦克风权限
switch AVAudioSession.sharedInstance().recordPermission {
case .granted:
decisionHandler(.grant)
case .denied:
decisionHandler(.deny)
case .undetermined:
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
if granted {
decisionHandler(.grant)
} else {
decisionHandler(.deny)
}
}
}
@unknown default:
decisionHandler(.deny)
}
case .camera, .cameraAndMicrophone:
decisionHandler(.grant)
@unknown default:
decisionHandler(.deny)
}
}
}
extension WebViewController: WKUIDelegate {
// 处理文件上传
@available(iOS 18.4, *)
func webView(_ webView: WKWebView, runOpenPanelWith parameters: WKOpenPanelParameters,
initiatedByFrame frame: WKFrameInfo, completionHandler: @escaping ([URL]?) -> Void) {
let alert = UIAlertController(title: "Select File", message: nil, preferredStyle: .actionSheet)
alert.addAction(UIAlertAction(title: "Select from Photos", style: .default) { _ in
self.presentImagePicker(completionHandler: completionHandler)
})
alert.addAction(UIAlertAction(title: "Select from Files", style: .default) { _ in
self.presentDocumentPicker(completionHandler: completionHandler)
})
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel) { _ in
completionHandler(nil)
})
present(alert, animated: true)
}
// 处理媒体权限请求
@available(iOS 15.0, *)
func webView(_ webView: WKWebView, requestMediaCapturePermissionFor origin: WKSecurityOrigin,
initiatedByFrame frame: WKFrameInfo, type: WKMediaCaptureType,
decisionHandler: @escaping (WKPermissionDecision) -> Void) {
switch type {
case .microphone:
// 检查麦克风权限
switch AVAudioSession.sharedInstance().recordPermission {
case .granted:
decisionHandler(.grant)
case .denied:
decisionHandler(.deny)
case .undetermined:
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async {
if granted {
decisionHandler(.grant)
} else {
decisionHandler(.deny)
}
}
}
@unknown default:
decisionHandler(.deny)
}
case .camera, .cameraAndMicrophone:
decisionHandler(.grant)
@unknown default:
decisionHandler(.deny)
}
}
}
บล็อกโค้ดนี้ในหน้าต่างลอย
ใช้งานฟังก์ชันการเลือกไฟล์
extension WebViewController {
private func presentImagePicker(completionHandler: @escaping ([URL]?) -> Void) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.mediaTypes = ["public.image", "public.movie"]
fileUploadCallback = { url in
if let url = url {
completionHandler([url])
} else {
completionHandler(nil)
}
}
present(picker, animated: true)
}
private func presentDocumentPicker(completionHandler: @escaping ([URL]?) -> Void) {
let picker: UIDocumentPickerViewController
if #available(iOS 14.0, *) {
picker = UIDocumentPickerViewController(forOpeningContentTypes: [.data, .text, .image, .movie, .audio])
} else {
picker = UIDocumentPickerViewController(documentTypes: [
"public.data",
"public.text",
"public.image",
"public.movie",
"public.audio"
], in: .import)
}
picker.delegate = self
picker.allowsMultipleSelection = false
fileUploadCallback = { url in
if let url = url {
completionHandler([url])
} else {
completionHandler(nil)
}
}
present(picker, animated: true)
}
}
extension WebViewController {
private func presentImagePicker(completionHandler: @escaping ([URL]?) -> Void) {
let picker = UIImagePickerController()
picker.delegate = self
picker.sourceType = .photoLibrary
picker.mediaTypes = ["public.image", "public.movie"]
fileUploadCallback = { url in
if let url = url {
completionHandler([url])
} else {
completionHandler(nil)
}
}
present(picker, animated: true)
}
private func presentDocumentPicker(completionHandler: @escaping ([URL]?) -> Void) {
let picker: UIDocumentPickerViewController
if #available(iOS 14.0, *) {
picker = UIDocumentPickerViewController(forOpeningContentTypes: [.data, .text, .image, .movie, .audio])
} else {
picker = UIDocumentPickerViewController(documentTypes: [
"public.data",
"public.text",
"public.image",
"public.movie",
"public.audio"
], in: .import)
}
picker.delegate = self
picker.allowsMultipleSelection = false
fileUploadCallback = { url in
if let url = url {
completionHandler([url])
} else {
completionHandler(nil)
}
}
present(picker, animated: true)
}
}
บล็อกโค้ดนี้ในหน้าต่างลอย
จัดการข้อความจาก WebView
extension WebViewBridge: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard message.name == "agentWebBridge",
let messageBody = message.body as? String else {
return
}
do {
guard let data = messageBody.data(using: .utf8),
let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let eventType = jsonObject["eventType"] as? String else {
return
}
let eventData = jsonObject["data"] as? [String: Any] ?? [:]
// 根据事件类型分发处理
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
switch eventType {
case WebViewBridge.EVENT_CLICK:
self.delegate?.onClickEvent(data: eventData)
case WebViewBridge.EVENT_MESSAGE:
self.delegate?.onMessageEvent(data: eventData)
default:
self.delegate?.onUnhandledEvent(eventType: eventType, data: eventData)
}
}
} catch {
print("Error parsing H5 message: \(error.localizedDescription)")
}
}
}
extension WebViewBridge: WKScriptMessageHandler {
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
guard message.name == "agentWebBridge",
let messageBody = message.body as? String else {
return
}
do {
guard let data = messageBody.data(using: .utf8),
let jsonObject = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any],
let eventType = jsonObject["eventType"] as? String else {
return
}
let eventData = jsonObject["data"] as? [String: Any] ?? [:]
// 根据事件类型分发处理
DispatchQueue.main.async { [weak self] in
guard let self = self else { return }
switch eventType {
case WebViewBridge.EVENT_CLICK:
self.delegate?.onClickEvent(data: eventData)
case WebViewBridge.EVENT_MESSAGE:
self.delegate?.onMessageEvent(data: eventData)
default:
self.delegate?.onUnhandledEvent(eventType: eventType, data: eventData)
}
}
} catch {
print("Error parsing H5 message: \(error.localizedDescription)")
}
}
}
บล็อกโค้ดนี้ในหน้าต่างลอย
คำถามที่พบบ่อย
1. WebView ไม่สามารถโหลดหน้าเว็บได้
- ตรวจสอบการเชื่อมต่อเครือข่าย
- ยืนยันว่าการกำหนดค่า NSAppTransportSecurity ใน Info.plist ถูกต้อง
- ตรวจสอบว่ารูปแบบ URL ถูกต้องหรือไม่
2. คำขอสิทธิ์ถูกปฏิเสธ
- ตรวจสอบให้แน่ใจว่าได้เพิ่มคำอธิบายสิทธิ์ที่จำเป็นทั้งหมดใน Info.plist แล้ว
- แนะนำให้ผู้ใช้เปิดสิทธิ์ด้วยตนเองในการตั้งค่าของอุปกรณ์
3. การโต้ตอบกับ JavaScript ล้มเหลว
- ตรวจสอบให้แน่ใจว่า WebViewBridge ลงทะเบียนอินเทอร์เฟซ JavaScript อย่างถูกต้อง
- ตรวจสอบว่ารูปแบบข้อความ JavaScript เป็นไปตามที่คาดหวังหรือไม่
- ใช้เครื่องมือสำหรับนักพัฒนาของ Safari เพื่อดีบักข้อผิดพลาด JavaScript ใน WebView
4. ปัญหาการอัปโหลดไฟล์
- สำหรับเวอร์ชันต่ำกว่า iOS 14 ตรวจสอบให้แน่ใจว่าใช้ตัวระบุประเภทเอกสารที่ถูกต้อง
- ตรวจสอบให้แน่ใจว่าแอปพลิเคชันมีสิทธิ์เพียงพอในการเข้าถึงคลังภาพและระบบไฟล์
- จัดการวงจรชีวิตของ URL ไฟล์ เพื่อให้แน่ใจว่า URL ยังคงใช้งานได้ในขณะที่ใช้งาน
