How do you hide the warnings in React Native iOS simulator? - ios

I just upgraded my React Native and now the iOS simulator has a bunch of warnings. Besides fixing them, how do I hide these warnings so that I can see what's underneath?

According to React Native Documentation, you can hide warning messages by setting disableYellowBox to true like this:
console.disableYellowBox = true;
Update: React Native 0.63+
console.disableYellowBox is removed and now you can use:
import { LogBox } from 'react-native';
LogBox.ignoreLogs(['Warning: ...']); // Ignore log notification by message
LogBox.ignoreAllLogs();//Ignore all log notifications
to ignore all log notifications

A better way to selectively hide certain warnings (that indefinitely show up after an upgrade to the latest and greatest RN version) is to set console.ignoredYellowBox in a common JS file in your project. For example, after upgrading my project today to RN 0.25.1 I was seeing a lot of...
Warning: ReactNative.createElement is deprecated...
I still want to be able to see helpful warnings and error messages from React-Native, but I want to squash this particular warning because it's coming from an external npm library that hasn't yet incorporated the breaking changes in RN 0.25. So in my App.js I add this line...
// RN >= 0.63
import { LogBox } from 'react-native';
LogBox.ignoreLogs(['Warning: ...']);
// RN >= 0.52
import {YellowBox} from 'react-native';
YellowBox.ignoreWarnings(['Warning: ReactNative.createElement']);
// RN < 0.52
console.ignoredYellowBox = ['Warning: ReactNative.createElement'];
This way I still get other errors and warning helpful for my dev environment, but I no longer see that particular one.

To disable the yellow box place
console.disableYellowBox = true;
anywhere in your application. Typically in the root file so it will apply to both iOS and Android.
For example
export default class App extends React.Component {
render() {
console.disableYellowBox = true;
return (<View></View>);
}
}

add this line in your app main screen.
console.disableYellowBox = true;
for example:- in index.js file
import { AppRegistry } from 'react-native';
import './src/utils';
import App from './App';
import { name as appName } from './app.json';
AppRegistry.registerComponent(appName, () => App);
console.disableYellowBox = true;

In your app.js file under any component's lifecycle method.like in componentDidmount()
you have to add both of these,excluding any will not work.
console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];
console.disableYellowBox = true;

For me below lines worked currently I am using react native 0.64
import { LogBox } from 'react-native';
LogBox.ignoreLogs(['Warning: ...']); //Hide warnings
LogBox.ignoreAllLogs();//Hide all warning notifications on front-end
When adding your warning to specify exactly which warning to suppress, you need to exactly add the warning message, like so (random example)
LogBox.ignoreLogs([
'Warning: Failed prop type: Invalid props.style key `tintColor` supplied to `Text`.',
]);
Using single quotes instead of backticks around tintColor or Text, for example, will not work.

Add the following code in your index.js file
console.disableYellowBox = true;
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
console.disableYellowBox = true;
AppRegistry.registerComponent(appName, () => App);

If You're Trying to Quickly Demo the App.
If you want to hide them in a particular build because you're doing a demo or something, you can edit your Xcode scheme to make it a release build and these yellow warnings will not show up. Additionally, your app will run much faster.
You can edit the Scheme for your simulator and real device by doing the following:
In Project in XCode.
Product > Scheme > Edit Scheme...
Change Build Configuration from Debug to Release.

For those coming this way trying to disable red warnings from the console, that give absolutely useless information, as of feb/17, you can add this line of code somewhere
console.error = (error) => error.apply;
Disables all console.error

RN >= 0.62
import {LogBox} from 'react-native'
under the import, add
LogBox.ignoreLogs(['...']);
instead of '...',
you can write the warnings you want to hide.
For instance,
I had the warning VirtualizedLists should never be ....
then I can write as
LogBox.ignoreLogs(['VirtualizedLists']);
if you want to add another error, you can write as
LogBox.ignoreLogs(['VirtualizedLists','Warning:...']);

console.disableYellowBox = true;
this worked for application level Put it anywhere in index.js file

I found that even when I disabled specific warnings (yellow-box messages) using the above mentioned methods, the warnings were disabled on my mobile device, but they were still being logged to my console, which was very annoying and distracting.
To prevent warnings from being logged to your console, you can simply override the warn method on the console object.
// This will prevent all warnings from being logged
console.warn = () => {};
It is even possible to disable only specific warnings by testing the provided message:
// Hold a reference to the original function so that it can be called later
const originalWarn = console.warn;
console.warn = (message, ...optionalParams) => {
// Insure that we don't try to perform any string-only operations on
// a non-string type:
if (typeof message === 'string') {
// Check if the message contains the blacklisted substring
if (/Your blacklisted substring goes here/g.test(message))
{
// Don't log the value
return;
}
}
// Otherwise delegate to the original 'console.warn' function
originalWarn(message, ...optionalParams);
};
If you can't (or don't want to) use a Regular Expression to test the string, the indexOf method will work just as well:
// An index of -1 will be returned if the blacklisted substring was NOT found
if (message.indexOf('Your blacklisted substring goes here') > -1) {
// Don't log the message
return;
}
Be aware that this technique will filter all messages that go through the warn function regardless of where they originated from.
Because of this, be careful that you do not specify an overly generous blacklist that will suppress other meaningful errors that may originate from somewhere other than React Native.
Also, I believe that React Native uses the console.error method to log errors (red-box messages), so I'm assuming that this technique could be used to filter out specific errors as well.

Add in app.js
import LogBox from React Native
import {LogBox} from 'react-native';
and then..
LogBox.ignoreAllLogs()

To disable the yellow box place console.disableYellowBox = true; anywhere in your application. Typically in the root file so it will apply to both iOS and Android.
For get more details please check official document

console.disableYellowBox = true;

console.ignoredYellowBox = ['Warning: Each', 'Warning: Failed'];

In your AppDelegate.m file you can change this line :
jsCodeLocation = [NSURL URLWithString:#"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
and replace dev=true by dev=false at the end.

Related: Suppress Xcode warnings from React Native library
(but not for your own code)
why: when initialising a new RN-app, the Xcode project contains closer to 100 warnings that is distracting noise (but probably harmless otherwise)
solution: set inhibit all warnings to yes under Build Settings for the relevant targets.
Disable warnings in Xcode from frameworks
https://github.com/facebook/react-native/issues/11736

I like to put the console.disableYellowBox = true on the file root, like App.
But this just when im on the development phase.

console.error = (error) => error.apply; // in the index.js
Some times rn 0.66 does not works Logbox. especially for VirtualizedLists should never be nested inside plain ScrollViews.
And also ignore red warnings.

Related

ReactNative [iOS] inquiry -> adding compassViewPosition in MapboxGL.MapView prop terminates the app, thoughts please?

I'm currently experiencing this issue https://github.com/rnmapbox/maps/issues/2514
wherein inside my code mapbox component, if compassViewPosition is added, it terminates the app without even throwing an error. anyone else encountered something related to this (read, passed through or dreamt about); feel free to comment out. Happy to get enlightened here.
import React from 'react';
import MapboxGL from '#rnmapbox/maps';
class BugReportExample extends React.Component {
render() {
return (
<MapboxGL.MapView
compassViewPosition={3} // adding this line terminates the app (not tested in android yet, and no error from try catch)
/>
);
}
}
I'm in "react-native": "~0.66.5" and I'm using "#rnmapbox/maps": "rnmapbox/maps#main",
Previous package I'm using was "#react-native-mapbox-gl/maps": "^8.5.0" and it works fine here. I'm trying to upgrade to the newer package (I know it's not on stable release yet but wanna know if I'm the only one experiencing this).

Disable RealityKit/ARKit when building in xcode Simulator

Is it possible to disable RealityKit/ARKit/AR when building for xcode Simulator? So that I can style/change non-ar related pages.
I want to change my home page, adding different sections and styling. The home page has nothing to do with ARKit/Reality Kit, but I don't have the physical device with me.
The errors say that various RealityKit/ARKit functions are undefined or don't exist. Like ARView has no member .occlusion.
The home page has no need for AR at all, is it possible to build and run the simulator, or even preview without a physical (AR Enabled) device?
You can use a Conditional Compilation Block, as explained in the Swift Programming Manual:
class SubclassedARView : ARView {
var configuration: ARWorldTrackingConfiguration()
var runOptions: ARSession.RunOptions()
init() {
#if !targetEnvironment(simulator)
// Code here is only compiled when building to a real or generic device.
// This is the place where you should add your RealityKit specific
// code, or at least the code that gives build-time errors in Xcode.
// An example of a problematic method:
session.run(configuration, options: runOptions)
#endif
}
}

Native UI Component throws Invariant Violation: tried to register two views with the same name FridgeCameraView

Trying to learn React Native custom Native UI Components.
// FridgeCameraViewManager.swift
import UIKit
#objc(FridgeCameraViewManager)
class FridgeCameraViewManager: RCTViewManager {
override func view() -> UIView! {
let label = UILabel()
label.text = "Swift Component"
label.textAlignment = .center
return label
}
#objc static override func requiresMainQueueSetup() -> Bool {
return false
}
}
.
// FridgeCameraViewManager.h
#import <Foundation/Foundation.h>
#import "React/RCTViewManager.h"
#interface RCT_EXTERN_MODULE(FridgeCameraViewManager, RCTViewManager)
#end
.
// FridgeCameraView.js
import {requireNativeComponent} from 'react-native';
const FridgeCameraView = requireNativeComponent('FridgeCameraView', null);
export default FridgeCameraView;
When I try to use FridgeCameraView component somewhere in App.js, it works only If I build & run the project using Xcode. Otherwise, using hot reload when changing something, I get "Invariant Violation: tried to register two views with the same name FridgeCameraView".
Somehow, the error went away when I installed react-router-native. I think there was a package conflict or something that I was missing. Hopefully, this will be a fix for the ones who encounter this error in the future. I'm still waiting for explanations if somebody knows what's behind this weird error.
(Not a solution, but still want to contribute)
TL;DR:
Just press R in terminal to refresh app
Auto hot-reload will register FridgeCameraView twice, reason unknown
For those of you who are wondering what's going on, we're learning the React Native - iOS Native Component and following the tutorial:
Swift in React Native - The Ultimate Guide Part 1: Modules
Swift in React Native - The Ultimate Guide Part 2: UI Components
And this is part 2 UI Components that went wrong. As React / React Native are changing fast, this scared resource on native component soon became outdated.
I accidentally need to reinstall my macOS & node_module, no luck in getting rid of the error. Installing another package doesn't solve the issue either.
I suspect that during React Native bridging in Swift -> Objective C -> React-JS, React Native will register our customized module FridgeCameraView twice; but will need expect in Objective C to dig deeper on this issue. Any contribution is welcomed!

How do you check if SwiftUI is in preview mode?

Is there a way to check if a SwiftUI app is in preview mode? For example, you can check if your app is in development or production mode using #if DEBUG. Can you do something similar to check if you're previewing or not?
You can detect this using ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"]. The value will be "1" at runtime when running in the canvas.
If you like me were looking for an environment variable to use in build scripts which xcode sets when building for SwiftUI previews, it turned out to be ENABLE_PREVIEWS.
SwiftUI were pausing preview when my script updated Info.plist file. To fix that I exit the script at certain point if we are in preview build.
if [ "${ENABLE_PREVIEWS}" = "YES" ]; then
exit 0;
fi
Though there is no compilation flag currently available for checking if the active build is intended for the Previews Canvas, I would still recommend using a compiler directive over a runtime check, if it can meet your needs.
For example, this check resolves to true for both the simulator and Previews:
#if targetEnvironment(simulator)
// Execute code only intended for the simulator or Previews
#endif
Negate the condition if you want your code to only execute on physical devices (such as camera-related operations that are otherwise guaranteed to fail).
The runtime check for whether your code is executing for Previews (as given in the accepted answer) probably does not add significant performance overhead, but it still feels a little gross to ship that code IMO. So it's worth at least considering first if your situation requires that level of specificity. If it does, I'd recommend wrapping that code in a compiler check to remove it from release builds.
If you don't want to rely on the ProccessInfo value you can always design your own environment variable in SwiftUI.
import SwiftUI
private struct IsPreviewKey: EnvironmentKey {
static let defaultValue = false
}
extension EnvironmentValues {
var isPreview: Bool {
get { self[IsPreviewKey.self] }
set { self[IsPreviewKey.self] = newValue }
}
}
Then when you create your preview inject the variable
MyView().environment(\.isPreview, true)
and you can use it in your view like this:
struct MyView: View {
#Environment(\.isPreview) var isPreview
}
I usually have a method that generates all the various versions for a preview (light mode, dark mode, iPad, iPhone, …) so I inject it there to all of the previews.

How can I set the default device to emulate in Ionic?

I'm using Ionic to build an iOS app. Right now I'm testing how it behaves in an iPad 2, but doing this requires me to constantly need to write:
ionic emulate ios --target="iPad-2"
Is there a way to hard-code this somewhere in the ionic.project file or somewhere else so I can stop manually doing this? Thanks
I was going through the same issue and even though this question is a year old but it was the first thing I got through google and couldn't find the answer anywhere else. Here's what I did just because I don't want to use --target="iPhone-7" everytime.
To be clear for anyone who lands here wanting to just run on a specific ios device use the following:
ionic run ios --target="iXXX-X"
The iXXX-X would be one of the names you get from running
ios-sim showdevicetypes
for example:
ionic run ios --target="iPhone-7"
I wanted to have a solution to make iPhone-7 my default, so running the following would target iPhone-7 (My original default target is iPhone-SE):
ionic run ios
It seems like the default is hardcoded and so must be changed in the code.
I found this file: /platforms/ios/cordova/lib/run.js
In there you'll find a function called deployToSim, I changed it as follows:
function deployToSim(appPath, target) {
// Select target device for emulator. Default is 'iPhone-6'
if (!target) {
return require('./list-emulator-images').run()
.then(function(emulators) {
if (emulators.length > 0) {
target = emulators[0];
}
emulators.forEach(function(emulator) {
// this is the original condition
// if (emulator.indexOf('iPhone') === 0)
// change "iPhone" to the specific model you want, in my case it's iPhone-7
// Notice the comma in iPhone7, without comma it will take iPhone-7-plus instead
if (emulator.indexOf('iPhone-7,') === 0) {
target = emulator;
}
});
events.emit('log', 'No target specified for emulator. Deploying to ' + target + ' simulator');
return startSim(appPath, target);
});
} else {
return startSim(appPath, target);
}
}

Resources