Link non-font assets using rnpm - react-native

There are plenty of tutorials on including font assets using rnpm. These are the steps:
Put fonts in, say, ./assets/fonts
Add the following snippet to package.json:
"rnpm": {
"assets": [
"./assets/fonts",
]
}
run react-native link.
Works well for font assets, but what about other types? I need to include a text file, but repeating the above steps for text file assets does not seem to have any effect. What am I missing? There are no mentions on the internet, so I'm not even sure this is possible at all with rnpm.
EDIT: To be more specific, I added a file.txt to the ./assets/raw directory and added ./assets/raw next to ./assets/fonts in the rnpm config in package.json. After running react-native link I expected file.txt to appear in the Android project assets directory (/android/app/src/main/assets), and in the "Copy Bundle Resources" build phase in iOS project, but it didn't happen. react-native link ran normally and produced no errors.
My ultimate goal is to include a text file in the app bundle and have it accessible at runtime. Another option would be to wrap the text in JSON, but that way it ends up in JS bundle increasing its size by ~25%, which is probably not good. Some also recommend react-native-fs to read the file, but I'm not sure where to put it so that it's available for both Android and iOS. rnpm knows where to put assets for Android and iOS (and how to copy them to bundle), so using it seems to be the way to go, but I can't make it work with text assets.
Any thoughts or suggestions?

After digging around in the React Native CLI I found out that react-native link, handles only fonts. Here's the relevant piece of code from /node_modules/react-native/local-cli/link/android/copyAssets.js:
/**
* Copies each file from an array of assets provided to targetPath directory
*
* For now, the only types of files that are handled are:
* - Fonts (otf, ttf) - copied to targetPath/fonts under original name
*/
module.exports = function copyAssetsAndroid(files, targetPath) {
const assets = groupFilesByType(files);
(assets.font || []).forEach(asset =>
fs.copySync(asset, path.join(targetPath, 'fonts', path.basename(asset)))
);
};
As you can see, groupFilesByType groups all files by their MIME type (font, text, etc.), but then only fonts are actually copied to the project.
Others ran into this issue before. There was a pull request adding support for video assets, but it was not merged. Apparently the way to go is to use packager.

Related

Needed to delete and relink fonts. Now iOS won't relink the fonts

I have a React Native app that I added custom fonts to, and I messed up naming, so I had to delete them. I deleted them from the info.plist and the build phases portion of Xcode, and from what I read online you just re-add the fonts and run npx react-native link again to get them back. However, I cannot get the fonts to be recognized any more. They don't show up in XCode any more either. How do I 'reset' the custom fonts in my folder?
To be clear - The first time I did it they showed up and worked, but I needed to change the naming so I deleted them (per a post I saw online). So the process does work - It just doesn't any more.
Structure /app/src/assets/fonts/[fonts here]
react-native.config.js:
module.exports = {
assets: [
'./src/assets/fonts'
]
}
In xcode, check the resources folder and delete everything in there.

Why is react-native-svg-icons giving me the error that there are some duplicates for ttf files?

Long story short
I have sunk about 12 hours in my iPhone react-native app. Since yesterday it's not building anymore (out of nowhere). After 5 hours! of debugging I found what may caused the issue but not how to solve it.
I use these packages containing .ttf files / for icons and stuff:
"#fortawesome/fontawesome-svg-core"
"#fortawesome/free-solid-svg-icons"
"#fortawesome/react-native-fontawesome"
"#react-native-community/cli-platform-ios"
"react-native-vector-icons"
And I think there is the problem. Since react-native-vector-icons seems to use also the same .ttf file that one of these packages bring in I get the error:
Multiple Commands produce...
So when I uninstall react-native-vector-icons it works again. But then when I get to the screen where i use this package:
"react-native-elements" (which in the docs it says it needs react-native-vector-icons)
It's complaining that it can't find Fontawesome Icons (the Checkbox Component from elements)
So how can I fix this? I need the app to build obviously and also need the Checkbox Component from react-native-elements. But react-native-elements requires react-native-svg-icons. But when I install it it doesn't even build with the above error that there are multiple .ttf files of the same icon.
I could not figure it out but it has something to do with react-native-elements since they also link the icons that also come with react-native-vector-icons
I solved it by getting rid of react-native-elements and created my own custom Checkbox component.
I had a similar issue associated with the fonts included in the react-native-vector-icons library. I solved it with the following.
I created assets/fonts dir in my project. I added another some fonts that iOS didn't have linked ("Nunito" font in my case), but I didn't include fonts of react-native-vector-icons
I created a new file named react-native.config.js in the root of my project with the following:
module.exports = {
project: {
ios: {},
android: {}
},
assets: ['./src/assets/fonts/'],
};
Then I ran react-native link
Then I went to ios dir (cd ios) and ran pod update
Finally, I ran react-native run-ios and the magic happened
I bassed it on Alex Biddle's post: https://medium.com/better-programming/how-to-add-custom-fonts-to-your-react-native-project-c64305281b9

lack of files after generating APK

I am building an app , my app contains a folder called content that folder contains a menu.html file that is calling some js, css files
content (size 5 MG)
menu.html
css
js
images
my problem is that after having generated my apk , installed it on my mobile
it displays first screen , when i click to move to next screen (the screen that is calling menu.html) here it sucks , i get a simple empty screen !
my question should I import manually this content folder to my android assets folder ? should I remove the 2 existing files in assets index.android.bundle and index.android.bundle.meta ?
You could try linking it. Since rnpm is part of RN you don't need to install anything, just add an entry in your package.json
"rnpm": {
"assets": [
"./path/to/file.html"
]
}
and then run react-native link
If you're already using rnpm you can add another path separated by a comma to that assets array. I don't know for certain but I would imagine the react-native is going to by default ignore HTML files unless they are explicitly linked.
You could also manually store the file in your Android assets folder and require it from there, but this won't work for iOS so if you're going cross platform I would try to get it to work via link.
Also as a side note, WebView kind of sucks. For a better user experience I would suggest rewriting the contents of that file in a way that react-native can render them.

React-Native: How to open locally bundled binary file

I'm writing a react-native app, and I want it to deploy with a zip file that contains a device firmware update.
Before letting the user send the update, I need my code to open the zip and do some validation of its contents.
I've found lots of zip-handling NPM packages, so all I need to do is load the file contents so I can feed it to one of these.
require('./firmware/fw.zip'); <-- packager doesn't include .zip by default
require('./firmware/fw.pdf'); <-- [gross hack] packager includes pdfs, but the actual result of the require() call is a number: 5. I don't know what I can do with this number to get file contents, but I'm pretty sure this require() system is designed for loading images, not binary data.
ReactNativeFs.openFile('./firmware/fw.zip'); <-- fails with ENOENT
ReactNativeFs.openFile(${ReactNativeFs.MainBundlePath}/firmware/fw.zip); <-- MainBundlePath is undefined on android.
This seems like a really basic question, so I'm sure I've missed a piece of documentation somewhere, but I'm heading into my third hour trying to load the contents of this file with no luck.
I'm pretty sure I could manually put the zip file into the appropriate android and ios resource directories, but that seems like a step down a hard-to-maintain road.
I encountered this problem again a couple months later (I'm apparently the only guy that needs to package .zips in react-native), and the above answer didn't work out for iOS. So I encoded the .zips as base64, put them in .js files, then used import to get the data from those .js files. This actually seems like a somewhat hacky but also flexible long-term solution, without having to mess around with platform-dependent file locations.
See whole answer at my new question: React-native packager configuration - How to include .zip file in bundle?
Partial solution:
Modify android/app/build.gradle, and add
task copyData(type: Copy) {
from '../../firmware/fw.zip'
into 'src/main/assets/raw/firmware'
}
preBuild.dependsOn copyData
This will at least ensure that the file gets copied each time you build, and is then available with ReactNativeFs.readFileAssets('raw/firmware/fw.zip', 'base64'). I'm not entirely thrilled because I still have to have iOS/android dependent code when loading the file, but at least it's loading now.
Tip: watch out for your syntax in gradle. into src/main/assets/myFirmware.zip will create a DIRECTORY called myFirmware.zip, and put your zip file underneath it. Then readFileAssets will still fail because it's finding a directory at your path, not a file.

Unrecognized font family on iOS simulator with React Native

I've added Linux Biolinum fonts (http://www.dafont.com/linux-biolinum.font, LinBiolinum_R.ttf, LinBiolinum_RB.ttf) to my React Native project. Android version is OK. But on iOS I always see error "Unrecognized font family LinBiolinum_R".
My style is:
customFontRegular: {
fontFamily: 'LinBiolinum_R',
},
I've tryied to rename font file and font family to "MyFont", but the error appears again on iOS.
Any ideas?
On Android it takes the name of the file and you are done. On iOS however it is a bit more complex.
There are a few steps you should take:
Double check the font files are included in the Target in XCode
Make sure they are included in the step "Copy Bundle Resources" (add files, not folders)
Include them in the Info.plist of the app
Find the name of the Font through FontBook or with some log statements in your AppDelegate
Explained in more detail here:
http://codewithchris.com/common-mistakes-with-adding-custom-fonts-to-your-ios-app/
Implement the following code in your appdelegate file
for (NSString* family in [UIFont familyNames])
{
NSLog(#"%#", family);
for (NSString* name in [UIFont fontNamesForFamilyName: family])
{
NSLog(#"Family name: %#", name);
}
}
You should use FONT FAMILY NAME instead of your font file name like the following
fontFamily: "FuturaBT-Book"
Easy/Working solution 2021. React Native 0.64. XCode 12+
Add these lines in ios/<ProjectName>/Info.plist. Rebuild ios app. that's it!
<key>UIAppFonts</key>
<array>
<string>AntDesign.ttf</string>
<string>Entypo.ttf</string>
<string>EvilIcons.ttf</string>
<string>Feather.ttf</string>
<string>FontAwesome.ttf</string>
<string>FontAwesome5_Brands.ttf</string>
<string>FontAwesome5_Regular.ttf</string>
<string>FontAwesome5_Solid.ttf</string>
<string>Fontisto.ttf</string>
<string>Foundation.ttf</string>
<string>Ionicons.ttf</string>
<string>MaterialIcons.ttf</string>
<string>MaterialCommunityIcons.ttf</string>
<string>SimpleLineIcons.ttf</string>
<string>Octicons.ttf</string>
<string>Zocial.ttf</string>
</array>
For people who have tried everything and are still facing this issue, this is a problem with the font's file naming,
You need to rename all of the fonts file name to its postscript name.
On mac I can open the font using fontbook and find this out.
Once I renamed all the fonts name to their postscript name the error was gone and I was also able to use the font-weight css property to set the font weight.
For me, changing the name of the file to the name of the Font (displayed as I open the file) did it.
Add this to your package.json
"rnpm":{
"assets":[
"./assests/fonts/"
]
}
and then run react-native link in command line
If you have custom fonts that you downloaded from internet, place them, e.g in
src/assets/fonts folder.
Create a file that is called react-native.config.js in the root folder and write the following in it:
module.exports = { assets: ['./src/assets/fonts'], };
Link your fonts assets by running npx react-native link in the terminal
Just do these 5 steps. It saves my life. ^.^
Add folder fonts include your fonts (path: src/assets/fonts)
Paste this code in file package.json => "rnpm": {
"assets": [
"./assets/fonts/"
]
}
Run cmd react-native link
Open Xcode select Target -> Build Phases tab -> Copy Bundle Resources and add your font
Rebuild app Open Xcode build or run cmd react-native run-ios
For IOS,
Make sure you add fonts to resource Copy Bundle Resources
Make sure you have folder Resources in Xcode, somehow it was deleted and you must create, import fonts to that folder manually
Make sure using name of Family in Font book
I fix by changing font file name into Futura-Medium, if I use FuturaMedium it will error like above
if there is no assets and font directories create them !
add your fonts to assets/font/ which you created
add your root directory react-native.config.js file
change react-native.config.js file to this;
module.exports = {
assets: ['./assets/fonts']
}
Link your fonts and assets to react-native so run this command
npx react-native link
Use your fonts where you want so change your stylesheet like;
fontFamily: 'texgyreadventor-regular'
be carefull ! if your font have not bold version than remove
fontWeight: 'bold'
from your stylesheet class
remove your app in simulator or in your physical device. Than re-build it. Because you have to re-build your app not refreshing it to see new fonts !
Easy solution. Stop worrying
Add it in to your project, Then add it your Bundle resources
I had the same issue and although the responses here are correct, I figured I'd try to give my own version for those who are still confused after reading the posts above :)
I followed this article to add my custom fonts to the XCode project :
You don't actually have to open XCode to add fonts for iOS. I used VSCode for example.
Here are the steps:
Go to node_modules>react-native-vector-icons>Fonts
You will have to search for it, modules aren't ordered alphabetically
Copy all the fonts available
Go to your ios folder and create a new folder called "Fonts"
Watch out ! The naming is case-sensitive, make sure you use a capital "F" (I didn't and spent too much time figuring out where I went wrong)
Paste de fonts you copied before in your Fonts folder
Next open your info.plist file (It's located in ios>Your_Project_Name>info.plist)
For each new font you added in the Fonts folder, add a line such as the one below, under the key UIAppFonts
The final result should look something like this:
<key>UIAppFonts</key>
<array>
<string>font1.ttf</string>
<string>font1.ttf</string>
<string>[Add your font names here]</string>
</array>
Finally close the iOS simulator, run pod install in the ios folder and run npm install in your root (for good measure) and then you can run react-native run-ios again.
If you're using a recent version of React-Native do not use react-native link command as you will encounter duplicate errors
2021 answer with
"react-native": "0.65.1",
"react-native-vector-icons": "8.1.0"
Running react native often doesn't work.
it create a duplicate resource declaration and you need to delete the extra lines.
Plus, when you run react-native link manually, it will fix your android but when you run your ios, the build will say you need to unlink it, we will fix this as well.
run:
react-native link react-native-vector-icons
go to your ios->Podfile
delete this line (fix the unlink issue):
pod 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons'
go to ios->YOUR_PROJECT.xcodeproj->project.pbxproj
and delete these lines in the "PBXResourcesBuildPhase" section:
939BE13DDBD94B1FA64AA9EC /* AntDesign.ttf in Resources */,
E863EAC557374C78B1C1A44F /* Entypo.ttf in Resources */,
AA1DC0C0FC504FF98744B883 /* EvilIcons.ttf in Resources */,
76E382E015E1470A9FDE5E08 /* Feather.ttf in Resources */,
99E9B4823AAE456C89BF6DAF /* FontAwesome.ttf in Resources */,
BCE22C5804AD4EC988CB4AD6 /* FontAwesome5_Brands.ttf in Resources */,
FE4AA6C0F54D4A26A2088CDA /* FontAwesome5_Regular.ttf in Resources */,
096B6D92BD5F4B59A1D262BE /* FontAwesome5_Solid.ttf in Resources */,
1031EC31F55B40378CAD9D3D /* Fontisto.ttf in Resources */,
2815970EABC94327BA107658 /* Foundation.ttf in Resources */,
3CB0C5395AE44CEAB966AE51 /* Ionicons.ttf in Resources */,
76E538C39D604AC4A0EAE522 /* MaterialCommunityIcons.ttf in Resources */,
AC62C33B70D04559AC57B231 /* MaterialIcons.ttf in Resources */,
49299510939246209A803546 /* Octicons.ttf in Resources */,
6AF5C757975E45839F276B17 /* SimpleLineIcons.ttf in Resources */,
45F326492D5E453E99A6EEAA /* Zocial.ttf in Resources */,
I had the same error about Inter-Regular font not being recognised.
The first thing I did was downloading the google fonts https://fonts.google.com/specimen/Inter and find the ttf file for the font missing.
Then drag the font file to the src/assets/fonts.
Open xcode, click projects name and under build phases you have to locate the font file under Copy Bundle Resource (click the + below the existing list).
Add Inter-Regular.ttf under UIAppFonts on your infor.plist file.
rm -rf node_modules; watchman watch-del-all; rm -rf /tmp/metro-*; yarn install; npx pod-install || cd ios && pod install; cd ..; react-native start --reset-cache, 4. re-run simulator
Add the Font in "Copy Bundle Resources" under "Build Phases"
Add the Font in Info.plist file
If you have added the name of the font AvenirMedium, it wont work, you need to use Avenir-Medium then it will work in iOS.
Clean previous build and start a fresh one.
You probably need to link your fonts.
In the root of the project, create a file: react-native.config.js
Considering that your fonts are placed at PROJECT_NAME/assets/fonts add this to the new config file:
module.exports = {
project: {
ios:{},
android:{}
},
assets:['./assets/fonts/'],
}
Now just link them:
npx react-native link
or for react-native + 0.69
npx react-native-asset
After this, your fonts should be already added in the android/app/src/main/assets/fonts directory and in Info.plist for IOS.
Credits to this blog post.
In my case the name of the ttf file was wrong.
I had to edit ios/MyApp/Info.plist and change manually the filename of the font.
From:
...
<array>
<string>Roboto_medium.ttf</string>
...
To:
...
<array>
<string>Roboto-Medium.ttf</string>
...
You can also try this, specify your fonts this way, map them into three styles:
For instance Gilroy-SemiBoldItalic
// iOS
{
fontFamily: 'Gilroy',
fontWeight: '600',
fontStyle: 'italic'
}
// Android
{
fontFamily: 'Gilroy-SemiBoldItalic'
}
You can also create a function to generate styles for a font with given weight and style.
Hope this helps
In my case, it worked fine in Android but not in iOS. The font file name was PlayfairDisplay-VariableFont_wght.ttf. But when I opened that file I saw the name as:
.
So, I changed the file name to PlayfairDisplay-Regular.ttf and it worked pretty well!
For me the fix was that I forgot to add the target for the font. If you don't add target for the font it won't work.
Put the following code in didFinishLaunchingWithOptions in AppDelegate.m in your iOS folder.
NSArray *fontFamilyNames = [UIFont familyNames];
for (NSString *familyName in fontFamilyNames) {
NSLog(#"Font Family Name = %#", familyName);
NSArray *names = [UIFont fontNamesForFamilyName:familyName];
NSLog(#"Font Names = %#", names);
}
It's going to list out all the Font-families available in your iOS app.
After that just search for your font-family in your case LinBiolinum_R.
After that copy the name and make a condition in your font file like this
Platform.OS === "ios" ? "Listed in Console" : "Normal Font family"
Remove the script from AppDelegate.m afterwards.
I renamed the font files and re-ran react-native link and ended up in this state.
I resolved it by ensuring the old fonts were removed from the Resources folder and Info.plist and then ran the build again.
If you are running react-native ios simulator, you should include fonts in the xcode project directory.
react-native link react-native-vector-icons doing so ,
will add the fonts to Resources folder in xcode project and also add fonts to pinfo list.
I had the same problem. I checked if I've added the fonts correctly to the xcode project. Then I checked the info.plist.
Turned out I spelled the name wrong. Instead of FontAwesome5_Solid.ttf, I had written FontAwesoem5_Solid.ttf. So I fixed it. That solved the problem for me.
To sum up - be very careful when typing the names and when checking them.
I followed all pieces of advise, but the problem was that I wrote
'./assets/fonts'
instead of
'./src/assets/fonts'.
Don't forget rebuild your app after 'yarn react-native link'. Good luck!
Follow these steps to solve this issue on the ios build:
1- First install the Font on your Mac.
2- Check "My Fonts" in FontBook to make sure the Font is installed.
3- Now Press CMD+I to see the Font Postscript name. This should be the
name of your Font file in your Project.
For example: I was using a font named "Nazegul" and I was getting the
same error because I had saved the font file name in my project with
"Nazegul-Regular.ttf" but when I checked this font Postscript name it
was "NazegulRegular" and after changing the font name to Postscript
name, the error was gone.
I had the same issue and fixed it by just opening the project in Xcode and under Resources folder in Project Navigator, there were duplicate fonts and just removing them from Resources folder and Info.plist both, the issue got resolved. Just run the app in Xcode after deletion then you may verify in your other tools as well without reinstalling npm. Just run 'react-native run-ios', cheers :)