1565686273
It would be great if we can dynamically import the language when needed. All sounds good in theory. Let's see if it also works in practice.
This article was written while I was trying to get the imports working. I have not censored the errors I ran into in the hope that it will help someone who runs into the same issues.
At the end, I have a link to example code on GitHub.
We want to remove the imports of locales:
import { registerLocaleData } from '@angular/common'; import localeNorwegian from '@angular/common/locales/nb'; import localeSwedish from '@angular/common/locales/sv';
And we want to replace the switch statement that registers the locale data with the dynamic import.
switch (culture) { case 'nb-NO': { registerLocaleData(localeNorwegian); break; } case 'sv-SE': { registerLocaleData(localeSwedish); break; } }
Before we start, we need to open tsconfig.ts
and change module type to esNext since dynamic imports are not in the official ES spec yet. Otherwise, we will get this error:
Dynamic import is only supported when ‘ — module’ flag is ‘commonjs’ or ‘esNext’
esNext
is a place holder for features that are on the standard track but is not in an official ES spec yet. e.g.import.meta
andimport()
expressions. As TC39 adds these features to a versioned spec, new--module ES20**
will be added to reflect that.
The Dynamic Imports allow us to load our code on demand asynchronously.
So now let's follow the article where it says:
import('xlsx').then(xlsx => { // JUST USE THE LIBRARY });
And change our code to:
import('@angular/common/locales/nb').then(lang => registerLocaleData(lang));
But we get an error:
Uncaught (in promise): TypeError: Cannot read property ‘toLowerCase’ of undefined at Object.registerLocaleData
It seems we need to use the default property.
import('@angular/common/locales/nb').then(lang => registerLocaleData(lang.default) );
No errors! But I wonder why we don't get the default by default?
If you have some code right after the import that updates the values that use you might get this error:
Missing locale data for the locale "nb-NO".
This is because your module did not import before the pipe tried to use it.
Since fetching an ECMAScript module on demand is an asynchronous operation, an import()
expression always returns a promise.
So, we have to wait until the import is done. To make the code clearer let's move the importing to a function.
And now we can use that method with some callback code:
this.localeInitializer().then(() => { // Update values here });
Callbacks added with then() will be called after the success or failure of the asynchronous operation.
If we build this code we can see that we are getting a new chunk:
So we can see that we are now getting that language we added in the dynamic import in our build.
So this is great and all but we do not want to hard-code all the languages that we import. Instead, let's use the characters before the hyphen from our culture string to get our localeId
.
const localeId = culture.substring(0, culture.indexOf('-'));
And then let's refactor localeInitializer()
so we can pass it that id.
Now we get a ton of these warnings:
We are trying to import too many files, some of which break the build. If we look in the folder node_modules\\@angular\\common\\locales
we see that every language has one JavaScript file and one TypeScript definition file. Since we only need the .js files, we can change our code to reflect it:
import(`@angular/common]/locales/${localeId}.js`);
I'm using a Template Literal, and now the build works again.
We get lots of chunks now.
It's bundling all the language files in the locale folder to individual chunks. This way we can lazy load the language we need.
In my case, I only have two languages so bundling all of them seems like overkill. Since we are using the CLI, I thought that perhaps there is no way actually to define which languages we want to bundle.
But there is some magic we can do!
And they are called webpack magic comments. By utilizing this magic comment we can send in the languages we want to bundle to webpack:
/* webpackInclude: /(nb|sv)\.js$/ */
With this code, our function is complete and looks like this:
localeInitializer(localeId: string): Promise<any> { return import( /* webpackInclude: /(nb|sv)\.js$/ */ `@angular/common/locales/${localeId}.js` ).then(module => registerLocaleData(module.default) ); }
You can also exclude files if that is more convenient:
/* webpackExclude: /(languages|here)\.js$/ */
And now when we recompile we only get the extra chunks we want.
For more options you can check the documentation.
We have our language chunks bundled and ready but let's see if they are lazy loaded by using the network tab in the developer tools.
Yes, we can see that when we start the application that no language chunks are loaded. And when we press the buttons for Norway or Sweden, the chunk for the corresponding country is downloaded.
That's great! So with research, grit and occasional magic, we were able to do what we set out to do. I was not sure that this article would end happily, but I'm glad it did.
You can download the code from GitHub if you want to try it out.
Thanks for reading. If you liked this post, share it with all of your programming buddies!
Further reading
☞ Angular 8 (formerly Angular 2) - The Complete Guide
☞ Angular & NodeJS - The MEAN Stack Guide
☞ The Complete Node.js Developer Course (3rd Edition)
☞ Best 50 Angular Interview Questions for Frontend Developers in 2019
☞ How to build a CRUD Web App with Angular 8.0
☞ React vs Angular: An In-depth Comparison
☞ React vs Angular vs Vue.js by Example
#angular #angular-js #javascript #typescript #web-development
1675797780
A debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
LLDebugTool is a debugging tool for developers and testers that can help you analyze and manipulate data in non-xcode situations.
LLDebugToolSwift is the extension of LLDebugTool, it provide swift interface for LLDebugTool, LLDebugToolSwift will release with LLDebugTool at same time.
If your project is a Objective-C project, you can use LLDebugTool
, if your project is a Swift project or contains swift files, you can use LLDebugToolSwift
.
Choose LLDebugTool for your next project, or migrate over your existing projects—you'll be happy you did! 🎊🎊🎊
cocoadocs.org
cause cocoadocs.org
to disable the access to LLDebugTool
, so this function is removed.Always check the network request or view log information for certain events without having to run under XCode. This is useful in solving the testers' problems.
Easier filtering and filtering of useful information.
Easier analysis of occasional problems.
Easier analysis of the cause of the crash.
Easier sharing, previewing, or removing sandbox files, which can be very useful in the development stage.
Easier observe app's memory, CPU, FPS and other information.
Take screenshots, tag and share.
More intuitive view of view structure and dynamic modify properties.
Determine UI elements and colors in your App more accurately.
Easy access to and comparison of point information.
Easy access to element borders and frames.
Quick entry for html.
Mock location at anytime.
CocoaPods is the recommended way to add LLDebugTool
to your project.
Objective - C
- Add a pod entry for LLDebugTool to your Podfile
pod 'LLDebugTool' , '~> 1.0'
.- If only you want to use it only in Debug mode, Add a pod entry for LLDebugTool to your Podfile
pod 'LLDebugTool' , '~> 1.0' ,:configurations => ['Debug']
, Details also see Wiki/Use in Debug environment. If you want to specify the version, use aspod 'LLDebugTool' , '1.3.8.1' ,:configurations => ['Debug']
.- The recommended approach is to use multiple targets and only add
pod 'LLDebugTool', '~> 1.0'
to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if:configurations => ['Debug']
, it can only run through XCode. It is not possible to Archive as an App).- Install the pod(s) by running
pod install
. If you can't searchLLDebugTool
or you can't find the newest release version, runningpod repo update
beforepod install
.- Include LLDebugTool wherever you need it with
#import "LLDebug.h"
or you can write#import "LLDebug.h"
in your .pch in your .pch file.
Swift
- Add a pod entry for LLDebugToolSwift to your Podfile
pod 'LLDebugToolSwift' , '~> 1.0'
.- If only you want to use it only in Debug mode, Add a pod entry for LLDebugToolSwift to your Podfile
pod 'LLDebugToolSwift' , '~> 1.0' ,:configurations => ['Debug']
, Details also see Wiki/Use in Debug environment. If you want to specify the version, use aspod 'LLDebugToolSwift' , '1.3.8.1' ,:configurations => ['Debug']
.- The recommended approach is to use multiple targets and only add
pod 'LLDebugToolSwift', '~> 1.0'
to Debug Target. This has the advantage of not contamiling the code in the Product environment and can be integrated into the App in the Archive Debug environment (if:configurations => ['Debug']
, it can only run through XCode. It is not possible to Archive as an App).- Must be added in the Podfile
use_frameworks!
.- Install the pod(s) by running
pod install
. If you can't searchLLDebugToolSwift
or you can't find the newest release version, runningpod repo update
beforepod install
.- Include LLDebugTool wherever you need it with
import "LLDebugToolSwift
.
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.
Objective - C
To integrate LLDebugTool into your Xcode project using Carthage, specify it in your
Cartfile
:
github "LLDebugTool"
Run
carthage
to build the framework and drag the builtLLDebugTool.framework
into your Xcode project.
Swift
To integrate LLDebugToolSwift into your Xcode project using Carthage, specify it in your
Cartfile
:
github "LLDebugToolSwift"
Run
carthage
to build the framework and drag the builtLLDebugToolSwift.framework
into your Xcode project.
Alternatively you can directly add the source folder named LLDebugTool. to your project.
Objective - C
- Download the latest code version or add the repository as a git submodule to your git-tracked project.
- Open your project in Xcode, then drag and drop the source folder named
LLDebugTool
. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed".- Integrated FMDB to your project,FMDB is an Objective-C wrapper around SQLite.
- Integrated Masonry to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version.
- Include LLDebugTool wherever you need it with
#import "LLDebug.h"
or you can write#import "LLDebug.h"
in your .pch in your .pch file.
Swift
- Download the LLDebugTool latest code version or add the repository as a git submodule to your git-tracked project.
- Download the LLDebugToolSwift latest code version or add the repository as a git submodule to your git-tracked project.
- Open your project in Xcode, then drag and drop the source folder named
LLDebugTool
andLLDebugToolSwift
. When you are prompted to "Choose options for adding these files", be sure to check the "Copy items if needed".- Integrated FMDB to your project,FMDB is an Objective-C wrapper around SQLite.
- Integrated Masonry to your project, Masonry is an Objective-C constraint library. There are no specific version requirements, but it is recommended that you use the latest version.
- Include LLDebugTool wherever you need it with
import LLDebugToolSwift"
.
You need to start LLDebugTool at "application:(UIApplication * )application didFinishLaunchingWithOptions:(NSDictionary * )launchOptions", Otherwise you will lose some information.
If you want to configure some parameters, must configure before "startWorking". More config details see LLConfig.h.
Quick Start
In Objective-C
#import "AppDelegate.h"
#import "LLDebug.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// The default color configuration is green background and white text color.
// Start working.
[[LLDebugTool sharedTool] startWorking];
// Write your project code here.
return YES;
}
In Swift
import LLDebugToolSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// ####################### Start LLDebugTool #######################//
// Use this line to start working.
LLDebugTool.shared().startWorking()
// Write your project code here.
return true
}
Start With Custom Config
In Objective-C
#import "AppDelegate.h"
#import "LLDebug.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Start working with config.
[[LLDebugTool sharedTool] startWorkingWithConfigBlock:^(LLConfig * _Nonnull config) {
//####################### Color Style #######################//
// Uncomment one of the following lines to change the color configuration.
// config.colorStyle = LLConfigColorStyleSystem;
// [config configBackgroundColor:[UIColor orangeColor] primaryColor:[UIColor whiteColor] statusBarStyle:UIStatusBarStyleDefault];
//####################### User Identity #######################//
// Use this line to tag user. More config please see "LLConfig.h".
config.userIdentity = @"Miss L";
//####################### Window Style #######################//
// Uncomment one of the following lines to change the window style.
// config.entryWindowStyle = LLConfigEntryWindowStyleNetBar;
}];
return YES;
}
In Swift
import LLDebugToolSwift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Start working with config.
LLDebugTool.shared().startWorking { (config) in
//####################### Color Style #######################//
// Uncomment one of the following lines to change the color configuration.
// config.colorStyle = .system
// config.configBackgroundColor(.orange, textColor: .white, statusBarStyle: .default)
//####################### User Identity #######################//
// Use this line to tag user. More config please see "LLConfig.h".
config.userIdentity = "Miss L";
//####################### Window Style #######################//
// Uncomment one of the following lines to change the window style.
// config.windowStyle = .netBar
//####################### Features #######################//
// Uncomment this line to change the available features.
// config.availables = .noneAppInfo
}
return true
}
You don't need to do anything, just call the "startWorking" will monitoring most of network requests, including the use of NSURLSession, NSURLConnection and AFNetworking. If you find that you can't be monitored in some cases, please open an issue and tell me.
Print and save a log. More log macros details see LLDebugToolMacros.h.
Save Log
In Objective-C
#import "LLDebug.h"
- (void)testNormalLog {
// Insert an LLog where you want to print.
LLog(@"Message you want to save or print.");
}
In Swift
import LLDebugToolSwift
func testNormalLog() {
// Insert an LLog where you want to print.
LLog.log(message: "Message you want to save or print.")
}
Save Log with event and level
In Objective-C
#import "LLDebug.h"
- (void)testEventErrorLog {
// Insert an LLog_Error_Event where you want to print an event and level log.
LLog_Error_Event(@"The event that you want to mark. such as bugA, taskB or processC.",@"Message you want to save or print.");
}
In Swift
import LLDebugToolSwift
func testEventErrorLog() {
// Insert an LLog_Error_Event where you want to print an event and level log.
LLog.errorLog(message: "Message you want to save or print.", event: "The event that you want to mark. such as bugA, taskB or processC.")
}
You don't need to do anything, just call the "startWorking" to intercept the crash, store crash information, cause and stack informations, and also store the network requests and log informations at the this time.
LLDebugTool monitors the app's CPU, memory, and FPS. At the same time, you can also quickly check the various information of the app.
LLDebugTool provides a quick way to view and manipulate sandbox, you can easily delete the files/folders inside the sandbox, or you can share files/folders by airdrop elsewhere. As long as apple supports this file format, you can preview the files directly in LLDebugTool.
LLDebugTool provides a screenshot and allows for simple painting and marking that can be easily recorded during testing or while the UI designers debugs the App.
LLDebugTool provides a view structure tool for viewing or modify elements' properties and information in non-debug mode.
LLDebugTool provides a magnify tool for magnifying local uis and viewing color values at specified pixel.
LLDebugTool provides a convenient tools to display touch point information.
LLDebugTool provides a function to display element border, convenient to see the view's frame.
LLDebugTool can debug HTML pages through WKWebView
, UIWebView
or your customized ViewController
in your app at any time.
LLDebugTool provides a function to mock location at anytime.
LLDebugTool works on iOS 8+ and requires ARC to build. It depends on the following Apple frameworks, which should already be included with most Xcode templates:
UIKit
Foundation
SystemConfiguration
Photos
QuickLook
CoreTelephony
CoreLocation
MapKit
AVKit
LLDebug.h
Public header file. You can refer it to the pch file.
DebugTool
LLDebugTool
Used to start and stop LLDebugTool, you need to look at it.
LLConfig
Used for the custom color , size , identification and other information. If you want to configure anything, you need to focus on this file.
LLDebugToolMacros.h
Quick macro definition file.
Components
Network
Used to monitoring network request.Log
Used to quick print and save log.Crash
Used to collect crash information when an App crashes.AppInfo
Use to monitoring app's properties.Sandbox
Used to view and operate sandbox files.Screenshot
Used to process and display screenshots.Hierarchy
Used to process and present the view structure.Magnifier
Used for magnifying glass function.Ruler
Used to ruler function.Widget Border
User to widget border function.Function
Used to show functions.Html
Used to dynamic test web view.Location
Used to mock location.Setting
Used to dynamically set configs.A brief summary of each LLDebugTool release can be found in the CHANGELOG.
Author: HDB-Li
Source Code: https://github.com/HDB-Li/LLDebugTool
License: View license
1656979200
Aujourd'hui, je continue à partager mon expérience avec le module natif et C++.
Comme nous verrons beaucoup de bibliothèques C/C++ écrire pour les plates-formes mobiles, nous devons les implémenter dans notre application iOS ou React Native. C'est pourquoi je souhaite écrire un article sur la façon d'exporter une fonction de C++ vers React Native, ce qui est facile à comprendre et fait gagner du temps aux débutants. Je vais commencer avec une nouvelle application native réactive
npx react-native init NativeModules
Créez un nouveau fichier C++ et nommez-leCpp_to_RN.cpp
Lorsque nous créons un nouveau fichier C++, Xcode créera un fichier d'en-tête Cpp_to_RN.hpp
pour nous
Tout d'abord, ouvrez le fichier " Cpp_to_RN.hpp
" et créez une classe qui inclut une fonction sans le corps.
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
Ouvrez ensuite le Cpp_to_RN.cpp
fichier et écrivez une fonction simple " sayHello()
"
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Pour envelopper les fichiers C++ et les exporter vers le côté IOS (swift)
un. Créez un fichier Objective C et nommez-leCpp_to_RN.m
Renommez le Cpp_to_RN.m
en Cpp_to_RN.mm
b. Ouvrez le WrapCpp_to_RN.mm
fichier et écrivez le contenu du corps qui encapsulera la fonction sayHello
à partir du fichier C++.
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c. Créez un fichier d'en-tête et nommez-leWrapCpp_to_RN.h
Exporter la wrapSayHello
fonction vers le fichier Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Pour exporter la fonction C++ vers React Native
un. Créez un fichier Swift et nommez-leSendCpp_to_RN.swift
Remarque : Xcode nous demandera de créer un NativeModules-Bridging-Header.h
fichier pour nous.
Créez une classe SendCpp_to_RN
et déclarez-la commeNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Écrire une fonction requiresMainQueueSetup()
pour empêcher l'avertissement lorsque nous exécutons l'application
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Ecrire une fonction pour envelopper le WrapCpp_to_RN()
fromWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b. Exporter une fonction wrap dans un fichier Swift vers React Native
Créez un fichier Objective C pour exporter la classe Swift et sa fonction à l'aide deCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c. Connectez Swift à React Native, ouvrez le NativeModules-Bridging-Header.h
fichier
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Appelez la classe Swift et ses fonctions
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
Et nous avons terminé, il suffit de lancer l'application
react-native run-ios
Ou cliquez simplement sur le bouton "exécuter" sur Xcode et voyez ce que nous avons fait.
J'espère que mon article vous sera utile, merci pour le temps de lecture.
1656981060
今日も、ネイティブモジュールとC++での経験を共有し続けています。
多くのC/C ++ライブラリがモバイルプラットフォーム用に作成されているので、それらをiOSまたはReactNativeアプリケーションに実装する必要があります。そのため、関数をC++からReactNativeにエクスポートする方法についての記事を書きたいと思います。これは、理解しやすく、初心者の時間を節約できます。新しいreactネイティブアプリケーションから始めます
npx react-native init NativeModules
新しいC++ファイルを作成し、名前を付けますCpp_to_RN.cpp
新しいC++ファイルを作成すると、XcodeはヘッダーファイルCpp_to_RN.hpp
を作成します
まず、「Cpp_to_RN.hpp
」ファイルを開き、本体のない関数を含むクラスを作成します。
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
次に、ファイルを開いてCpp_to_RN.cpp
、単純な関数「sayHello()
」を記述します。
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
C ++ファイルをラップしてIOS(swift)側にエクスポートするには
a。ObjectiveCファイルを作成して名前を付けますCpp_to_RN.m
名前をに変更Cpp_to_RN.m
します Cpp_to_RN.mm
b。ファイルを開き、C++ファイルからWrapCpp_to_RN.mm
関数をラップする本文のコンテンツを記述します。sayHello
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c。ヘッダーファイルを作成し、名前を付けますWrapCpp_to_RN.h
wrapSayHello
関数をSwiftファイルにエクスポートします
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
C++関数をReactNativeにエクスポートするには
a。Swiftファイルを作成し、名前を付けますSendCpp_to_RN.swift
注:Xcodeは、NativeModules-Bridging-Header.h
ファイルを作成するように要求します。
クラスSendCpp_to_RN
を作成し、次のように宣言しますNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
requiresMainQueueSetup()
アプリケーション実行時の警告を防ぐ関数を作成する
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
WrapCpp_to_RN()
fromをラップする関数を記述しますWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b。Swiftファイルのラップ関数をReactNativeにエクスポートします
を使用してSwiftクラスとその関数をエクスポートするObjectiveCファイルを作成しますCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c。SwiftをReactNativeに接続し、NativeModules-Bridging-Header.h
ファイルを開きます
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Swiftクラスとその関数を呼び出す
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
これで完了です。アプリケーションを実行するだけです。
react-native run-ios
または、Xcodeの「実行」ボタンをクリックして、実行内容を確認してください。
私の記事がお役に立てば幸いです。お読みいただきありがとうございます。
1656984600
今天,我继续分享我在 Native Module 和 C++ 方面的经验。
由于我们将看到很多为移动平台编写的 C/C++ 库,因此我们需要将它们实现到我们的 iOS 或 React Native 应用程序中。这就是为什么我想写一篇关于如何将一个函数从 C++ 导出到 React Native 的文章,它易于理解并且为初学者节省了时间。我将从一个新的 react native 应用程序开始
npx react-native init NativeModules
创建一个新的 C++ 文件并命名Cpp_to_RN.cpp
当我们创建一个新的 C++ 文件时,Xcode 会Cpp_to_RN.hpp
为我们创建一个头文件
首先,打开“ Cpp_to_RN.hpp
”文件,并创建一个包含没有主体的函数的类。
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
然后打开Cpp_to_RN.cpp
文件,写一个简单的函数“ sayHello()
”
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
包装 C++ 文件并将它们导出到 IOS (swift) 端
一个。创建一个Objective C文件并命名Cpp_to_RN.m
重命名Cpp_to_RN.m
为 Cpp_to_RN.mm
湾。打开WrapCpp_to_RN.mm
文件并编写将包装sayHello
C++ 文件中的函数的正文内容。
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
C。创建头文件并命名WrapCpp_to_RN.h
将函数导出wrapSayHello
到 Swift 文件
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
将 C++ 函数导出到 React Native
一个。创建一个 Swift 文件并命名SendCpp_to_RN.swift
注意:Xcode 会要求我们为我们创建一个NativeModules-Bridging-Header.h
文件。
创建一个类SendCpp_to_RN
并将其声明为NSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
编写一个函数requiresMainQueueSetup()
来防止我们运行应用程序时出现警告
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
编写一个函数来包装WrapCpp_to_RN()
fromWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
湾。将 Swift 文件中的包装函数导出到 React Native
创建一个 Objective C 文件以导出 Swift 类及其函数,使用Callback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
C。将 Swift 连接到 React Native,打开NativeModules-Bridging-Header.h
文件
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
调用 Swift 类及其函数
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
我们完成了,只需运行应用程序
react-native run-ios
或者只需单击 Xcode 上的“运行”按钮,看看我们做了什么。
希望我的文章对您有所帮助,感谢您的阅读时间。
1656981000
Hôm nay, tôi tiếp tục chia sẻ kinh nghiệm của mình với Native Module và C ++.
Vì chúng ta sẽ thấy rất nhiều thư viện C / C ++ viết cho nền tảng di động, chúng ta cần triển khai chúng cho ứng dụng iOS hoặc React Native của mình. Đó là lý do mình muốn viết một bài hướng dẫn cách export một hàm từ C ++ sang React Native dễ hiểu và tiết kiệm thời gian cho người mới bắt đầu. Tôi sẽ bắt đầu với một ứng dụng gốc phản ứng mới
npx react-native init NativeModules
Tạo một tệp C ++ mới và đặt tên cho nóCpp_to_RN.cpp
Khi chúng tôi tạo tệp C ++ mới, Xcode sẽ tạo tệp tiêu đề Cpp_to_RN.hpp
cho chúng tôi
Đầu tiên, mở tệp Cpp_to_RN.hpp
“” và tạo một lớp bao gồm một hàm không có phần thân.
#ifndef Cpp_to_RN_hpp
#define Cpp_to_RN_hpp#include <stdio.h>
#include <string>class Cpp_to_RN {
public:
std::string sayHello();
};#endif /* Cpp_to_RN_hpp */
Sau đó, mở Cpp_to_RN.cpp
tệp và viết một hàm đơn giản “ sayHello()
”
#include "Cpp_to_RN.hpp"
std::string Cpp_to_RN::sayHello(){
return "Hello from CPP";
}
Để bọc các tệp C ++ và xuất chúng sang phía IOS (nhanh chóng)
một. Tạo một tệp Objective C và đặt tên cho nóCpp_to_RN.m
Đổi tên Cpp_to_RN.m
thành Cpp_to_RN.mm
b. Mở WrapCpp_to_RN.mm
tệp và viết nội dung phần nội dung sẽ bọc hàm sayHello
từ tệp C ++.
#import <Foundation/Foundation.h>
#import "WrapCpp_to_RN.h"
#import "Cpp_to_RN.hpp"@implementation WrapCpp_to_RN- (NSString *) sayHello {
Cpp_to_RN fromCPP;
std::string helloWorldMessage = fromCPP.sayHello();
return [NSString
stringWithCString:helloWorldMessage.c_str()
encoding:NSUTF8StringEncoding];
}
@end
c. Tạo một tệp tiêu đề và đặt tên cho nóWrapCpp_to_RN.h
Xuất wrapSayHello
hàm sang tệp Swift
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Để xuất hàm C ++ sang React Native
một. Tạo một tệp Swift và đặt tên cho nóSendCpp_to_RN.swift
Lưu ý: Xcode sẽ yêu cầu chúng tôi tạo một NativeModules-Bridging-Header.h
tệp cho chúng tôi.
Tạo một lớp SendCpp_to_RN
và khai báo nó làNSObject
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Viết một hàm requiresMainQueueSetup()
để ngăn cảnh báo khi chúng tôi chạy ứng dụng
#import <Foundation/Foundation.h>
@interface WrapCpp_to_RN : NSObject
- (NSString *) wrapSayHello;
@end
Viết một hàm để bọc WrapCpp_to_RN()
từWrapCpp_to_RN.mm
import Foundation@objc(SendCpp_to_RN)
class SendCpp_to_RN : NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return false
}
@objc func fromCpp(_ successCallback: RCTResponseSenderBlock) -> Void {
successCallback([NSNull(), WrapCpp_to_RN().wrapSayHello() as Any])
}}
b. Xuất một hàm bọc trong tệp Swift sang React Native
Tạo một tệp Objective C để xuất lớp Swift và chức năng của nó bằng cách sử dụngCallback
#import <React/RCTBridgeModule.h>
#import <Foundation/Foundation.h>
#import "UIKit/UIKit.h"
@interface RCT_EXTERN_MODULE(SendCpp_to_RN, NSObject)RCT_EXTERN_METHOD(fromCpp:(RCTResponseSenderBlock)successCallback)@end
c. Kết nối Swift với React Native, mở NativeModules-Bridging-Header.h
tệp
#import <React/RCTBridgeModule.h>#import <React/RCTViewManager.h>#import "WrapCpp_to_RN.h"
Gọi lớp Swift và các chức năng của nó
import React from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';const App = () => {
const onPress = () => {
const {SendCpp_to_RN} = NativeModules;
SendCpp_to_RN.fromCpp((_err, res) => console.log(res));
};
return (
<View style={styles.container}>
<Text> Practice !</Text>
<Button title="C++ to React Native" color="#841584" onPress={onPress} />
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
});
export default App;
Và chúng tôi đã hoàn tất, chỉ cần chạy ứng dụng
react-native run-ios
Hoặc chỉ cần nhấp vào nút “chạy” trên Xcode và xem những gì chúng tôi đã làm.
Tôi hy vọng bài viết của tôi hữu ích cho bạn, cảm ơn bạn đã dành thời gian đọc.