Skip to content

Instantly share code, notes, and snippets.

@diegolmello
Last active March 19, 2024 14:46
Show Gist options
  • Save diegolmello/505b4a82bdbb5906064e060249d8d620 to your computer and use it in GitHub Desktop.
Save diegolmello/505b4a82bdbb5906064e060249d8d620 to your computer and use it in GitHub Desktop.
Embedding Rocket.Chat on iframe in Swift

Docs

Make sure to read https://developer.rocket.chat/rocket.chat/iframe-integration/adding-a-rocket.chat-chat-room-to-your-web-app

There are two important settings there:

  • Administration > Settings > General > Restrict access to any iframe needs to be disabled
  • Administration > Settings > General > iframe Integration > Enable Receive needs to be enabled
  • Keep Receive Origins as *

Xcode

  • Open Xcode and create a new iOS project.
  • Choose the "App" template and click "Next."
  • Enter your project details and make sure Swift is selected as the language.
  • Go to ViewController.swift and overwrite it with the code below
  • Make sure to a valid user token on YOUR_TOKEN_HERE

Env

Xcode 15.3
Macbook Pro M1 Pro
//
// ViewController.swift
// WKWebViewExample
//
// Created by Diego Mello on 3/19/24.
//
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let myURL = URL(string: "https://mobile.rocket.chat/channel/general?layout=embedded")
let myRequest = URLRequest(url: myURL!)
webView.load(myRequest)
}
override func loadView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: .zero, configuration: webConfiguration)
webView.navigationDelegate = self
view = webView
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
// JavaScript code to post a message
let js = "window.postMessage({ externalCommand:'login-with-token', token: 'YOUR_TOKEN_HERE' });"
// Delay the JavaScript injection by 300 milliseconds
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
webView.evaluateJavaScript(js) { (result, error) in
if let error = error {
print("JavaScript injection error: \(error)")
} else {
print("JavaScript injected successfully")
}
}
}
}
}
@diegolmello
Copy link
Author

Simulator.Screen.Recording.-.iPhone.15.Pro.-.2024-03-19.at.11.41.08.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment