-
Swift를 사용해서 Cordova Custom Plugin 만들기 (2)iOS 2023. 5. 25. 17:39
Swift를 사용해서 Cordova Custom Plugin 만들기 (1)에 이어서 clobbers 요소에 대해서 알아보고, iOS 플랫폼의 native view를 띄워보겠습니다.
플러그인 프로젝트의 Swift 코드
@objc(presentModalView:) func presentModalView(_ command: CDVInvokedUrlCommand) { print("presentModalView: called.") let viewController = UIViewController() let label = UILabel() label.translatesAutoresizingMaskIntoConstraints = false label.text = "Hello world!" label.font = .boldSystemFont(ofSize: 25) viewController.view.addSubview(label) NSLayoutConstraint.activate([ label.centerXAnchor.constraint(equalTo: viewController.view.centerXAnchor), label.centerYAnchor.constraint(equalTo: viewController.view.centerYAnchor) ]) viewController.view.backgroundColor = .systemPink viewController.modalPresentationStyle = .popover self.viewController.present(viewController, animated: true) { [weak self] in let result = CDVPluginResult(status: CDVCommandStatus_OK, messageAs: "ModalView came up.") self?.commandDelegate.send(result, callbackId: command.callbackId) } }
이전과 똑같이 cordova.exec() 인터페이스를 사용해서 네이티브 메서드를 호출해도 되지만, 이번에는 clobbers라는 요소를 사용해서 호출해보겠습니다. clobbers를 사용하면 Javascript 인터페이스를 Cordova 애플리케이션 전역에 제공할 수 있을 뿐만 아니라 기존의 API를 덮어쓸 수 있습니다.
다음은 Plugin 프로젝트의 plugin.xml 파일의 <js-module> 항목입니다. 기존의 clobbers는 길어서 그대로 사용하면 Javascript 코드에서 사용할 때 불편하고 가독성이 좋지 않습니다. 아래와 같이 바꿔보겠습니다.
<js-module name="CordovaSamplePluginSwift" src="www/CordovaSamplePluginSwift.js"> <!-- 기존 --> <!-- <clobbers target="cordova.plugins.CordovaSamplePluginSwift" /> --> <!-- 변경 --> <clobbers target="sample" /> </js-module>
www/CordovaSamplePluginSwift.js
var exec = require('cordova/exec'); exports.greet = function(success, error) { exec(success, error, "CordovaSamplePluginSwift", "greet"); }; exports.presentModalView = function(success, error) { exec(success, error, "CordovaSamplePluginSwift", "presentModalView"); };
브리지 역할을 하는 Javascript module을 위와 같이 작성하면, 아래와 같이 호출할 수 있습니다.
Cordova 프로젝트의 index.js에서 호출하는 코드
customButton.addEventListener("click", function() { // clobbers의 target == "sample" sample.greet( function(winParam) { navigator.notification.alert(winParam, null, "Received message", "OK"); }, function(error) { navigator.notification.alert("Error occured!: " + error); } ); }); modalButton.addEventListener("click", function() { // clobbers의 target == "sample" sample.presentModalView( function(winParam) { navigator.notification.alert(winParam, null, "Received message", "OK"); }, function(error) { navigator.notification.alert("Error occured!: " + error); } ); });
파라미터가 줄어서 표현이 간결하고 모듈화를 통해서 유지보수가 쉬워졌습니다.
Simulator Recording
Native Modal View
코드
Custom sample plugin github
'iOS' 카테고리의 다른 글
Apple Certificates (0) 2024.02.14 CLI 없이 Xcode Workspace에 Cordova Custom Plugin 추가하기 (0) 2023.06.23 Swift를 사용해서 Cordova Custom Plugin 만들기 (1) (0) 2023.05.25 Swift Package에 GitHub Actions 사용하기 (0) 2023.05.05 Class와 Performance in Swift (0) 2023.02.02