Posted in

How to use Yarn with Objective-C?

Hey there! I’m a supplier of Yarn, and I often get asked about how to use Yarn with Objective – C. In this blog, I’ll share some insights and tips on this topic. Yarn

First off, let’s understand what Yarn is. Yarn is a fast, reliable, and secure dependency management tool for JavaScript projects. It was developed by Facebook, Google, Exponent, and Tilde to address some of the issues with npm, such as inconsistent installation times and security vulnerabilities. But you might be wondering, "What does Yarn have to do with Objective – C?" Well, in modern development, especially in mobile app development, we often have projects that mix different technologies. For example, you might have an Objective – C iOS app that uses some JavaScript libraries for certain features, like in – app web views or interactive components.

Why Use Yarn with Objective – C?

There are a few good reasons to use Yarn in an Objective – C project. One of the main benefits is that it allows you to manage your JavaScript dependencies more efficiently. With Yarn, you can ensure that all the JavaScript libraries your app depends on are installed correctly and consistently across different development environments. This is crucial because inconsistent installations can lead to bugs and compatibility issues.

Another advantage is that Yarn has a lock file called yarn.lock. This file records the exact version of each dependency that was installed, which means that when you share your project with other developers or deploy it to different environments, everyone will get the same versions of the dependencies. This helps in maintaining the stability of your app.

Setting Up Yarn in an Objective – C Project

The first step is to make sure you have Yarn installed on your system. You can install it using Homebrew if you’re on a Mac. Just open your terminal and run the following command:

brew install yarn

If you’re on a different operating system, you can follow the official Yarn installation guide.

Once Yarn is installed, you need to create a package.json file in your Objective – C project. This file is like a manifest for your JavaScript dependencies. You can create it by running the following command in your project’s root directory:

yarn init -y

The -y flag tells Yarn to use the default values for all the questions it asks during the initialization process.

Adding JavaScript Dependencies

Now that you have a package.json file, you can start adding JavaScript dependencies to your project. Let’s say you want to use a popular JavaScript library like React in your Objective – C app. You can add it to your project by running the following command:

yarn add react react - dom

This command will download the react and react - dom libraries and add them to your package.json file. Yarn will also create or update the yarn.lock file to record the exact versions of these libraries.

Integrating JavaScript Code in Objective – C

Once you have your JavaScript dependencies installed, you need to integrate the JavaScript code into your Objective – C app. One common way to do this is by using a web view. In an iOS app, you can use the WKWebView class to display web content, including JavaScript – based components.

Here’s a simple example of how you can load a JavaScript file in a WKWebView:

#import <WebKit/WebKit.h>

@interface ViewController () <WKUIDelegate, WKNavigationDelegate>

@property (nonatomic, strong) WKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.uiDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
}

@end

In this example, we’re loading an HTML file that might contain references to our JavaScript libraries. The HTML file could look something like this:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF - 8">
    <title>My App</title>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react - dom/umd/react - dom.development.js"></script>
</head>

<body>
    <div id="root"></div>
    <script>
        const element = React.createElement('h1', null, 'Hello, world!');
        ReactDOM.render(element, document.getElementById('root'));
    </script>
</body>

</html>

Handling Communication between Objective – C and JavaScript

In many cases, you’ll need to communicate between your Objective – C code and your JavaScript code. For example, you might want to pass data from your Objective – C app to a JavaScript function or vice versa.

You can use the WKWebView‘s evaluateJavaScript: method to execute JavaScript code from your Objective – C code. Here’s an example:

[self.webView evaluateJavaScript:@"myJavaScriptFunction('Hello from Objective - C!')" completionHandler:^(id result, NSError *error) {
    if (error) {
        NSLog(@"Error executing JavaScript: %@", error.localizedDescription);
    } else {
        NSLog(@"JavaScript function executed successfully");
    }
}];

To receive messages from JavaScript in your Objective – C code, you can use the WKScriptMessageHandler protocol. Here’s how you can implement it:

@interface ViewController () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKUserContentController *userContentController = [[WKUserContentController alloc] init];
    [userContentController addScriptMessageHandler:self name:@"messageFromJavaScript"];
    config.userContentController = userContentController;

    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    self.webView.uiDelegate = self;
    self.webView.navigationDelegate = self;
    [self.view addSubview:self.webView];

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSURL *fileURL = [NSURL fileURLWithPath:filePath];
    [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"messageFromJavaScript"]) {
        NSLog(@"Received message from JavaScript: %@", message.body);
    }
}

@end

In your JavaScript code, you can send a message to Objective – C like this:

window.webkit.messageHandlers.messageFromJavaScript.postMessage('Hello from JavaScript!');

Keeping Your Dependencies Up – to – Date

It’s important to keep your JavaScript dependencies up – to – date to ensure the security and performance of your app. You can use the following command to check for updates:

yarn outdated

This command will show you which of your dependencies have newer versions available. To update a specific dependency, you can use the yarn upgrade command:

yarn upgrade react

If you want to update all your dependencies, you can run:

yarn upgrade

Conclusion

Using Yarn with Objective – C can be a great way to manage your JavaScript dependencies and integrate JavaScript code into your iOS app. By following the steps outlined in this blog, you can set up Yarn in your project, add dependencies, integrate JavaScript code, handle communication between Objective – C and JavaScript, and keep your dependencies up – to – date.

Canvas If you’re interested in learning more about Yarn or need high – quality Yarn for your projects, feel free to reach out for a procurement discussion. I’m here to help you find the best solutions for your development needs.

References

  • Yarn official documentation
  • Apple’s documentation on WKWebView
  • React official documentation

Shandong Shengrun Textile Co., Ltd.
With over 15 years of experience, Shandong Shengrun Textile Co., Ltd. is one of the most professional yarn manufacturers and suppliers in China. Please rest assured to buy or wholesale durable yarn in stock here from our factory.
Address: 9th Floor, Hui Ji Business Tower, Ren Cheng District, Ji Ning, Shan Dong, China
E-mail: liang@shengrungroup.com
WebSite: https://www.shengruntextile.com/