Global Variable / Constant in React Native - android

is there a way in React Native that I can define on a global variable all the strings that I will be using like in Android Development there is a String.xml where you can put all of your strings.

What' I've done is create a globals module...
// File: Globals.js
module.exports = {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
Then I just require it at the top...
const GLOBAL = require('../Globals');
And access them like so...
GLOBAL.COLOR.ORANGE
_____________________
UPDATE on Feb 10, 2018
This seems to be a pretty popular and useful answer, so I thought I should update it with the more current syntax. The above still works in CommonJS module systems, but now days you're just as likely to run into ES6 and importmodules rather than require them.
ECMAScript Modules (ESM) Syntax
// File: Globals.js
export default {
STORE_KEY: 'a56z0fzrNpl^2',
BASE_URL: 'http://someurl.com',
COLOR: {
ORANGE: '#C50',
DARKBLUE: '#0F3274',
LIGHTBLUE: '#6EA8DA',
DARKGRAY: '#999',
},
};
// to use...
import GLOBALS from '../Globals'; // the variable name is arbitrary since it's exported as default
// and access them the same way as before
GLOBALS.COLOR.ORANGE

global in react native is like the window in web development.
// declare a global varible
global.primaryColor = '***';
//now you can use this variable anywhere
console.log(primaryColor);

I too made a module like in Chris Geirman's answer, but was not able to reference it with the require. Instead I got it to work with import * as GLOBAL from '../Globals';

If you want to switch between languages depening on platform localisation.
fetch node_module via npm
npm i react-native-localization --save
Define variables in class:
// Localisation.js
let LocalizedStrings = require ('react-native-localization');
let strings = new LocalizedStrings ({
en: {
loginTitle: "Login",
},
de: {
loginTitle: "Anmelden",
}
})
When you need the strings:
var STRINGS = require ('./Localization');
<Text>{STRINGS.loginTitle}</Text>

Related

How to add 'Google Consent 'to flutter app

In my application I use native ads from:
firebase_admob, native_admob_controller, flutter_native_admob.
child: NativeAdmob(
// Your ad unit id
adUnitID: adsAndroidID,
controller: _nativeAdController,
// Don't show loading widget when in loading state
),
How can I now add to it the information described under this link https://developers.google.com/admob/ump/android/quick-start ?
I trying run with https://pub.dev/packages/gdpr_dialog but this is only in english language.
Main
pubspec.yaml
dependencies:
admob_consent: '1.0.0' #if you will change the text
admob_consent: ^1.0.0+1 #if you will use main
initialization
import 'package:flutter/material.dart';
import 'package:admob_consent/admob_consent.dart';
final AdmobConsent _admobConsent = AdmobConsent();
_admobConsent.show(publisherId: "REPLACE_WITH_YOUR_PUBLISHER_ID", privacyURL: "URL_TO_YOUR_PRIVACY_POLICY");
Listener
You can listen to the onConsentFormLoaded, onConsentFormOpened, onConsentFormClosed and onConsentFormError streams.
_admobConsent.onConsentFormClosed.listen((bool status) {
// Status true if personalized
// Handle it, ie. set targetingInfo
});
To use in Polish
When you want to use the plugin in polish, without creating a Google Founding Choices account, you need to use this version of the Plugin
Version: '1.0.0' (not the newest)
README.md from this commit here
Here you can edit the language files
(External Libraries/Flutter Plugins/admob_consent-1.0.0/android/src.main/assets)
There are a couple html files, these represent the consent query. You can either copy and revise one of these, but then you have to make sure that you also integrate them.
Therefore, if the target group is only Polish, I would recommend working on one, for example English, and calling it up.
(The code snippet you are looking for is at the ground of the files.)

How to import CreateDataBinding into Xamarin

I am new to MVVMCross concept and Hybride development.
In my project I have a .xml file with a UI-Component that has a listener attribute "o'clock" for example.
I want to bind the o'clock to the ViewModel. I check some posts in the internet and I found the one shown below.
The question is, how can I import or have access to:
CreateBindingSet and DelayBind
into the project because I do not have access to it.
code:
this.DelayBind(() => {
var set = this.CreateBindingSet<KittenCollectionCell,
Kitten>();
set.Bind(NameLabel).To(kitten => kitten.Name);
set.Bind (PriceLabel).To (kitten => kitten.Price);
set.Bind (_loader).To (kitten => kitten.ImageUrl);
set.Bind(MyAwesomeButton).To(vm => vm.MyAwesomeCommand);
set.Apply();
});
Both CreateBindingSet and DelayBind are extension methods living in namespace MvvmCross.Binding.BindingContext.
In order to use them, add a using statement like so on top of you file:
using MvvmCross.Binding.BindingContext;

Display data on the basis of development and production environment in Ionic 3

I am trying to display a conditional ion-select on my page which will be visible only when apk is develop for development purpose. I don't want to show that ion-select in my apk which is develop for production purpose. This select will change the overall Url for our Api's. I have tried different solutions which are not working. Some of them are as follow:
http://roblouie.com/article/296/ionic-2-environment-variables-the-best-way/
https://medium.com/#hin556/managing-environment-variables-in-ionic-2-43506f49acfb
https://masimplo.com/using-environment-config-in-ionic2/index.html
https://artyomsokolov.com/tag/typescript/
I have tried all of the above solutions and many more but they are returning same data for production as returning for development. How can i achieve my ultimate goal. Your help will be appreciated. Thanks in advance.
One way to do this is to add in a configuration file of your own, let's say config.ts, the value for your environment:
export const CONFIG: any = {
prodEnv: false,
apiUrl: null,
devApiUrl: 'http://localhost/app_dev.php/api/',
prodApiUrl: 'https://api.test.com/api/'
};
Somewhere in your AppComponent in the constructor, you should define the default value for your CONFIG.apiUrl.
In your page where you want the select to be displayed, in the ts file add the following:
get isProd() {
return CONFIG.prodEnv;
}
setProd(event) {
CONFIG.prodEnv = event;
CONFIG.apiUrl = event ? CONFIG.prodApiUrl : CONFIG.devApiUrl;
}
And in the HTML:
<ion-select *ngIf="!isProd" name="environment" (ionChange)="setProd($event)">
<ion-option [value]="true">Production</ion-option>
<ion-option [value]="false" [selected]="!isProd">Development</ion-option>
</ion-select>

react native custom fonts

This question has been already here and here, but the answer is not satisfactory there. The fonts are not working on android but on iOS do. Maybe I made some mistake during the linking.
How did I added fonts:
Created folder assets/fonts/ inside root folder.
Added
"rnpm": { "assets": ["./assets/fonts"] }
react-native link
Console output was it successfully added assets to iOS and Android
Added fontFamily: 'MyCustomFontFamily' into styles.
Run on iOS, everything worked fine.
Run on Android, no typeface.
Checked the android project directory and the assets folder was present
I tried adding (Platform.OS === 'ios') ? 'MyCustomFontFamily' : 'fonts/my_custom_font_family' to go with the file name but this did not work wither.
Tried same variation as 9 without path or with extension but no luck
Read here to use weight, tried it, no luck.
I had the same issue, which had to do with the fact that, as you already know, Android will read from the filename whilst iOS will read from the full name property. And, indeed, I had mixed up my fonts' references.
The first thing I did to solve this was to double-check that my fonts were properly located in android/app/src/main/assets/fonts/.
Then I ended up renaming my fonts to the exact same name as the one used by iOS and using that name as a reference. Here is what I mean:
export const sansSerifLight = 'Aileron-Light'; // Filename is 'Aileron-Light.otf'
export const sansSerifRegular = 'Aileron-Regular'; // Filename is 'Aileron-Regular.otf'
export const sansSerifBold = 'Aileron-Bold'; // Filename is 'Aileron-Bold.otf'
export const serifRegular = 'LibreBaskerville-Regular'; // Filename is 'LibreBaskerville-Regular.ttf'
export const serifBold = 'LibreBaskerville-Bold'; // Filename is 'LibreBaskerville-Bold.ttf'
export const serifItalic = 'LibreBaskerville-Italic'; // Filename is 'LibreBaskerville-Italic.ttf'
export const sansSerifTitle = 'ADAM.CG PRO'; // Filename is 'ADAM.CG PRO.otf'
export const serifTitle = 'Oranienbaum'; // Filename is 'Oranienbaum.ttf
And then :
<MyComponent style={{ fontFamily: serifTitle }} />
This really made things way less error-prone and easier to maintain for me.

Is any function in swift similar to R.java in Android?

I am a beginner in iOS and swift.
I used to write Android and I think the R.java is a good idea to manage ids, drawables, strings and other resources.
So I'm surprised that iOS does't provide a good function to access resources.
If I want to get a Image from assets, I call UIImage(named: "img_name"), but I don't think this is the best way to access img_name, I may use a wrong name and I can't get the image.
I found some open source project like Shark and SwiftGen, but Shark only support images and SwiftGen it seems need to run a command not automatically.
Do you have any better solution? Thank you!
I have a open source project R.swift-plugin it provides features as you mentioned. You just need to install the Xcode Plugin via Alcatraz and search R.swift
The plugin will automatically generate a resource file to manage your images, localizable strings and colors, and you can access them like using R.java
Usage:
Sincerely recommend you to try it. And feel free to give me any suggestion to improve it :)
If you are using InterfaceBuilder (also called Storyboard, xib), there is no need to define id for each view. You can bind outlets in code.
If you want to retrieve views using their ids (like R.java as you asked), you can set tag to each view and manipulate them in code.
Unlike AndroidStudio, Xcode will not generate any file.
func viewDidLoad() {
let labelView = self.view.viewWithTag(0) as? UILabel
}
There is no such function in Xcode itself, but there is an open source project that does just this: R.swift
It automatically updates the generated file and supports a lot of different resource types such as images, fonts, segues and more.
You can have similar functionality by using extensions and enums.
Using enums allows you to avoid typos and benefit from Xcode's autosuggest/autocomplete.
Example for UIImage:
extension UIImage {
enum ImageId: String {
// These are your images NAMES,
// as in "SpriteMonster.jpg"
case SpriteMonster, SpriteHero, BaseLandscape
}
convenience init!(id: ImageId) {
self.init(named: id.rawValue)
}
}
Usage:
let monster = UIImage(id: .SpriteMonster) // the "SpriteMonster.jpg" image
For this example I'm force-unwrapping the convenience init, so be careful to actually have the image with the correct name in your bundle.
For String:
extension String {
enum StringId: String {
case Welcome = "Welcome to the game!"
case GameOver = "You loose! Game over!"
}
init(id: StringId) {
self = id.rawValue
}
}
Usage:
let label = String(id: .Welcome) // "Welcome to the game!"
For fonts:
extension UIFont {
enum FontId {
case HelveticaNeueLarge
case HelveticaNeueMedium
case HelveticaNeueSmall
func font() -> UIFont {
switch self {
case .HelveticaNeueLarge:
return UIFont(name: "HelveticaNeue", size: 18)!
case .HelveticaNeueSmall:
return UIFont(name: "HelveticaNeue", size: 12)!
default:
return UIFont(name: "HelveticaNeue", size: 14)!
}
}
}
class func get(id: FontId) -> UIFont {
return id.font()
}
}
Usage:
let font = UIFont.get(.HelveticaNeueLarge) // <UICTFont: 0x7ffd38f09180> font-family: "Helvetica Neue"; font-weight: normal; font-style: normal; font-size: 18.00pt
These are only examples to demonstrate the concept, you can go much further with this.
If you use Tuist is has SwiftGen inside. It allows to use it out of the box without adding third-party solutions. The disadvantage is that you have to run it every time when you change resource

Categories

Resources