Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> ระบบ >> Android

สร้าง Cross-Platform Bridges แบบปลอดภัย: iOS ↔ Android Messaging อย่างง่าย

ผมทำโปรเจกต์ที่งาน ต้องเชื่อมหลาย Components ผ่าน Messages แต่ละตัวมี Logic และ Code Language ต่างกัน ทำให้อยากเข้าใจทุกวิธีที่ Platforms ต่างๆ ใช้ Communication

บทความนี้อธิบาย Cross-Origin Communication Bridges พร้อมตัวอย่าง Simple แต่ Informative

จะมี Bridge Puns เยอะ 😄

คุณได้รับคำเตือนแล้ว

ถ้าอยากเขียนโค้ดทันที มี Links GitHub Repositories ท้ายบทความ

ปกติ JavaScript รันใน Browser บน iOS เป็น UIWebView หรือ WKWebView บน Android เป็น WebView

iOS ซับซ้อนกว่า จะอธิบาย Bridge ที่นี่ก่อน

London Bridge is Falling Down (iOS)

iOS 8 ขึ้นไป Apple แนะนำ WKWebView แทน UIWebView บทความนี้ครอบคลุมแค่ WKWebView

สำหรับ UIWebView Reference ดู ที่นี่

ส่ง Messages จาก WKWebView ไป JavaScript ใช้ Method:

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^)(id, NSError *error))completionHandler;

รับ Messages จาก JavaScript ใน WKWebView ต้อง:

  1. สร้าง Instance ของ WKWebViewConfiguration
  2. สร้าง Instance ของ WKUserContentController
  3. Add Script Message Handler ไป Configuration (ส่วนนี้ Bridge Gap) Action นี้ Register Message Handler บน Window Object Path: window.webkit.messageHandlers.MSG_HANDLER_NAME
  4. ทำให้ Class Implement Message Handler Protocol เพิ่ม <WKScriptMessageHandler> บนสุดไฟล์
  5. Implement userContentController:didReceiveScriptMessage (Handle Receive Messages จาก JavaScript)

Building Bridges

สมมติมี HTML Page:

<html> 
<head> 
<title>Javascript-iOS Communication</title> 
</head> 
<body> 
<script> 
window.webkit.messageHandlers.myOwnJSHandler.postMessage("Hello World!"); 
</script> 
</body> 
</html>

Native Code Implement ขั้นตอนข้างต้น:

#import <UIKit/UIKit.h> 
#import <WebKit/WebKit.h> 
// 4 
@interface ViewController : UIViewController <WKScriptMessageHandler> 
@property(nonatomic, strong) WKWebView *webview; 

Violà! มี Full JavaScript - iOS Communication แล้ว!

สร้าง Cross-Platform Bridges แบบปลอดภัย: iOS ↔ Android Messaging อย่างง่าย
Photo by Todd Diemer on Unsplash

Crossing The Bridge (Android)

Android ง่ายและ Friendly มาก Steps เพียงเล็กน้อย:

  1. สร้าง Instance ของ WebView Object
  2. Enable JavaScript ใน WebView (setJavaScriptEnabled)
  3. Set Custom JavaScript Interface (Hold Methods ที่ Visible ไป JavaScript)
  4. Method ที่ต้องการ Expose ให้ JavaScript ต้องมี Annotation @JavascriptInterface ก่อน Declaration

สมมติ HTML File และ Android App เรียบร้อยแล้ว

ไปแล้ว! คุณเป็น Native Communication Ninja แล้ว! 🥷

Repository Links:

AndroidtoJS RepositoryiOStoJS Repository

⚠️ Important Note Regarding iOS ⚠️

ตอน Destroy WKWebView จำเป็น ต้อง Remove Script Message Handler หากไม่ทำ Script Message Handler จะ Hold Reference ไป WKWebView Memory Leaks จะเกิดเมื่อสร้าง WKWebViews ใหม่