Implementing Native modules for IOS: React-Native

React native is a powerful tool because it lets us use native code(Swift/Obj-C in ios and Java/Kotlin in android) and bridge them to access native methods in our react-native JavaScript files.

This feature can really come in handy when you are building something which is not yet supported by react-native or you have some old native code that you don’t want to re-write in JavaScript.

I encountered one such case where I wanted to clear all cookies for WebView and there wasn’t any way to achieve this in react-native. The examples in ios Native Module were all in Objective-C and I wanted to implement this using Swift.

Start with opening your ios project for react-native under YourReactNativeProject/ios/YourReactNativeProject.xcodeproj or YourReactNativeProject/ios/YourReactNativeProject.xcworkspace if you have made a previous pod install. First create a new swift file and name it CookieManager under your project directory

When you create a Swift file you should be prompted to create a bridging header. Inside the bridging header add an import statment

#import "RCTBridgeModule.h"

Inside your CookieManager.swift file

import Foundation
@objc(CookieManager)
class CookieManager: NSObject {

@objc func clearCookies() -> Void {
// Remove all cache
URLCache.shared.removeAllCachedResponses()

// Delete any associated cookies
if let cookies = HTTPCookieStorage.shared.cookies {
for cookie in cookies {
HTTPCookieStorage.shared.deleteCookie(cookie)
}
}
}
}

Unfortunately, we have to provide an Objective-C file that exposes our Swift to the React Native Objective-C framework. Create a new Objective-C file and call it CookieManagerBridge

Inside the CookieManagerBridge.m file you can expose your CookieManager class and clearCookies method

#import <Foundation/Foundation.h>
#import "RCTBridgeModule.h"
#import "RCTBridge.h"
#import "RCTEventDispatcher.h"

@interface RCT_EXTERN_MODULE(CookieManager, NSObject)

RCT_EXTERN_METHOD(clearCookies)

@end

Other Use-cases:

If you are creating a method which requires you to pass parameters to the method, you can do so by modifying your .m and .swift files to one shown below

If you want a list of all supported argument types, you can find them here


Now that all the native part is done, you can import this is your react-native JavaScript file with

Now if you run the project you can find it working perfectly.