JS - Mobile - CL2 Flashcards
Native, Web, Hybrid Apps: advantages and disadvantages
Device features.
Although web apps can take advantage of some features, native apps (and the native components of the hybrid apps) have access to the full paraphernalia of device-specific features, including GPS, camera, gestures, and notifications.
Offline functioning.
A native app is best if your app must work when there is no connectivity. In-browser caching is available in HTML5, but it’s still more limited than what you can get when you go native.
Discoverability.
Web apps win the prize on discoverability. Content is a lot more discoverable on the web than in an app: When people have a question or an information need, they go to a search engine, type in their query, and choose a page from the search results. They do not go to the app store, search for an app, download it, and then try to find their answer within the app. Although there are app aficionados who may fish for apps in app stores, most users don’t like installing and maintaining apps (and also wasting space on their device), and will install an app only if they expect to use it often.
Speed.
Native apps win the speed competition. In 2012 Mark Zuckerberg declared that Facebook’s biggest mistake had been betting on the mobile web and not going native. Up to that point, the Facebook app had been a hybrid app with an HTML core; in 2012 it was replaced with a truly native app. Responsiveness is key to usability.
Installation.
Installing a native or hybrid app is a hassle for users: They need to be really motivated to justify the interaction cost. “Installing” a web app involves creating a bookmark on the home screen; this process, while arguably simpler than downloading a new app from an app store, is less familiar to users, as people don’t use bookmarks that much on mobile.
Maintenance.
Maintaining a native app can be complicated not only for users, but also for developers (especially if they have to deal with multiple versions of the same information on different platforms): Changes have to be packaged in a new version and placed in the app store. On the other hand, maintaining a web app or a hybrid app is as simple as maintaining a web page, and it can be done as often or as frequently as needed.
Platform independence.
While different browsers may support different versions of HTML5, if platform independence is important, you definitely have a better chance of achieving it with web apps and hybrid apps than with native apps. As discussed before, at least parts of the code can be reused when creating hybrid or web apps.
Content restrictions, approval process, and fees.
Dealing with a third party that imposes rules on your content and design can be taxing both in terms of time and money. Native and hybrid apps must pass approval processes and content restrictions imposed by app stores, whereas the web is free for all. Not surprisingly, the first web apps came from publications such as Playboy, who wanted to escape Apple’s prudish content censure. And buying a subscription within an iOS app means that 30% of that subscription cost goes to Apple, a big dent in the publishers’ budget.
Development cost.
It’s arguably cheaper to develop hybrid and web apps, as these require skills that build up on previous experience with the web. NN/g clients often find that going fully native is a lot more expensive, as it requires more specialized talent. But, on the other hand, HTML5 is fairly new, and good knowledge of it, as well as a good understanding of developing for the mobile web and hybrid apps are also fairly advanced skills.
User Interface.
Last but not least, if one of your priorities is providing a user experience that is consistent with the operating system and with the majority of the other apps available on that platform, then native apps are the way to go. That doesn’t mean that you cannot provide a good mobile user experience with a web app or a hybrid app — it just means that the graphics and the visuals will not be exactly the same as those with which users may be already accustomed, and that it will be harder to take advantage of the mobile strengths and mitigate the mobile limitations.
Mobile development flow:
- create new application
- build
- install to device(iPhone, android, winPhone)
Prerequisites
- We recommend Yarn to install and manage the npm packages.
- React Native is installed on your system.
- Have the Android SDK and paths set properly.
- An android emulator or real device to run the app.
- A google account for having Firebase Web configuration.
- Xcode installed to test the app on an iOS devices or simulator.
Step by steps instructions (less than 5 minutes to build your own app) - First clone the repository - Then install the dependencies - To link the react-native-vector-icons package to react native: react-native link - Then run the following command to run the app on the emulator. react-native run-android or if you have Xcode installed: react-native run-ios - To see the logs: react-native log-android or react-native log-ios
Mobile development: app debugging
Accessing the In-App Developer Menu
You can access the developer menu by shaking your device or by selecting “Shake Gesture” inside the Hardware menu in the iOS Simulator. You can also use the ⌘D keyboard shortcut when your app is running in the iOS Simulator, or ⌘M when running in an Android emulator on Mac OS and Ctrl+M on Windows and Linux. Alternatively for Android, you can run the command adb shell input keyevent 82 to open the dev menu (82 being the Menu key code).
Enabling Fast Refresh
Fast Refresh is a React Native feature that allows you to get near-instant feedback for changes in your React components. While debugging, it can help to have Fast Refresh enabled. Fast Refresh is enabled by default, and you can toggle “Enable Fast Refresh” in the React Native developer menu. When enabled, most of your edits should be visible within a second or two.
Errors
In-app errors are displayed in a full screen alert with a red background inside your app. This screen is known as a RedBox. You can use console.error() to manually trigger one.
Warnings
Warnings will be displayed on screen with a yellow background. These alerts are known as YellowBoxes. Click on the alerts to show more information or to dismiss them. As with a RedBox, you can use console.warn() to trigger a YellowBox.
YellowBoxes can be disabled during development by using console.disableYellowBox = true
In CI/Xcode, YellowBoxes can also be disabled by setting the IS_TESTING environment variable.
RedBoxes and YellowBoxes are automatically disabled in release (production) builds.
Chrome Developer Tools
To debug the JavaScript code in Chrome, select “Debug JS Remotely” from the Developer Menu. This will open a new tab at http://localhost:8081/debugger-ui.
Select Tools → Developer Tools from the Chrome Menu to open the Developer Tools. You may also access the DevTools using keyboard shortcuts (⌘⌥I on macOS, Ctrl Shift I on Windows). You may also want to enable Pause On Caught Exceptions for a better debugging experience.
Note: the React Developer Tools Chrome extension does not work with React Native, but you can use its standalone version instead. Read this section to learn how.
Debugging using a custom JavaScript debugger
To use a custom JavaScript debugger in place of Chrome Developer Tools, set the REACT_DEBUGGER environment variable to a command that will start your custom debugger. You can then select “Debug JS Remotely” from the Developer Menu to start debugging.
The debugger will receive a list of all project roots, separated by a space. For example, if you set REACT_DEBUGGER=”node /path/to/launchDebugger.js –port 2345 –type ReactNative”, then the command node /path/to/launchDebugger.js –port 2345 –type ReactNative /path/to/reactNative/app will be used to start your debugger.
Custom debugger commands executed this way should be short-lived processes, and they shouldn’t produce more than 200 kilobytes of output.
React Developer Tools
You can use the standalone version of React Developer Tools to debug the React component hierarchy. To use it, install the react-devtools package globally. It should connect to your simulator within a few seconds.
Integration with React Native Inspector
Open the in-app developer menu and choose “Toggle Inspector”. It will bring up an overlay that lets you tap on any UI element and see information about it.
However, when react-devtools is running, Inspector will enter a special collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools
Performance Monitor
You can enable a performance overlay to help you debug performance problems by selecting “Perf Monitor” in the Developer Menu.
Debugging in Ejected Apps
Accessing console logs
You can display the console logs for an iOS or Android app by using the following commands in a terminal while the app is running
You may also access these through Debug → Open System Log… in the iOS Simulator or by running adb logcat *:S ReactNative:V ReactNativeJS:V in a terminal while an Android app is running on a device or emulator.
If you’re using Create React Native App or Expo CLI, console logs already appear in the same terminal output as the packager.
Debugging native code
When working with native code, such as when writing native modules, you can launch the app from Android Studio or Xcode and take advantage of the native debugging features (setting up breakpoints, etc.) as you would in case of building a standard native app.
Using of camera
Cordova/PhoneGap
- Install camera plugin
- navigator.camera.getPicture( cameraSuccess, cameraError, [ cameraOptions ] ) - Takes a photo using the camera, or retrieves a photo from the device’s image gallery. The image is passed to the success callback as a base64-encoded String, or as the URI for the image file. The method itself returns a CameraPopoverHandle object that can be used to reposition the file selection popover.
Ionic
- Requires the Cordova plugin: cordova-plugin-camera
- Usage: this.camera.getPicture(options).then((imageData) => {})
React-Native CameraRoll
CameraRoll provides access to the local camera roll or photo library.
On iOS, the CameraRoll API requires the RCTCameraRoll library to be linked
Permissions
The user’s permission is required in order to access the Camera Roll on devices running iOS 10 or later. Add the NSPhotoLibraryUsageDescription key in your Info.plist with a string that describes how your app will use this data. This key will appear as Privacy - Photo Library Usage Description in Xcode.
If you are targeting devices running iOS 11 or later, you will also need to add the NSPhotoLibraryAddUsageDescription key in your Info.plist. Use this key to define a string that describes how your app will use this data. By adding this key to your Info.plist, you will be able to request write-only access permission from the user. If you try to save to the camera roll without this permission, your app will exit.
Methods
saveToCameraRoll()
CameraRoll.saveToCameraRoll(tag, [type]);
Saves the photo or video to the camera roll or photo library.
On Android, the tag must be a local image or video URI, such as “file:///sdcard/img.png”.
On iOS, the tag can be any image URI (including local, remote asset-library and base64 data URIs) or a local video file URI (remote or data URIs are not supported for saving video at this time).
If the tag has a file extension of .mov or .mp4, it will be inferred as a video. Otherwise it will be treated as a photo. To override the automatic choice, you can pass an optional type parameter that must be one of ‘photo’ or ‘video’.
Returns a Promise which will resolve with the new URI.
getPhotos()
CameraRoll.getPhotos(params);
Returns a Promise with photo identifier objects from the local camera roll of the device matching shape defined by getPhotosReturnChecker
Using of geolocation
Cordova/PhoneGap:
Geolocation provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs. There is no guarantee that the API returns the device’s actual location.
As of version 3.0, Cordova implements device-level APIs as plugins. Use the CLI’s plugin command, described in The Command-Line Interface, to add or remove this feature for a project
APIs:
- geolocation.getCurrentPosition
Returns the device’s current position as a Position object.
navigator.geolocation.getCurrentPosition(geolocationSuccess,[geolocationError], [geolocationOptions])
geolocation.getCurrentPosition is an asynchronous function. It returns the device’s current position to the geolocationSuccess callback with a Position object as the parameter. If there is an error, the geolocationError callback is passed a PositionError object. - geolocation.watchPosition
Watches for changes to the device’s current position.
var watchId = navigator.geolocation.watchPosition(
geolocationSuccess, [geolocationError], [geolocationOptions]);
Returns String: a watch id that references the watch position interval. The watch id should be used with geolocation.clearWatch to stop watching for changes in position.
geolocation.watchPosition is an asynchronous function. It returns the device’s current position when a change in position is detected. When the device retrieves a new location, the geolocationSuccess callback executes with a Position object as the parameter. If there is an error, the geolocationError callback executes with a PositionError object as the parameter. - geolocation.clearWatch
Stop watching for changes to the device’s location referenced by the watchID parameter.
navigator.geolocation.clearWatch(watchID);
The geolocation.clearWatch stops watching changes to the device’s location by clearing the geolocation.watchPosition referenced by watchID.
Ionic
This plugin provides information about the device’s location, such as latitude and longitude. Common sources of location information include Global Positioning System (GPS) and location inferred from network signals such as IP address, RFID, WiFi and Bluetooth MAC addresses, and GSM/CDMA cell IDs.
This API is based on the W3C Geolocation API Specification, and only executes on devices that don’t already provide an implementation.
Installation
ionic cordova plugin add cordova-plugin-geolocation
npm install @ionic-native/geolocation
Usage this.geolocation.getCurrentPosition().then((resp) => {}) let watch = this.geolocation.watchPosition(); watch.subscribe((data) => {})
React-Native
The Geolocation API extends the Geolocation web spec.
As a browser polyfill, this API is available through the navigator.geolocation global - you do not need to import it.
On Android, this uses the android.location API. This API is not recommended by Google because it is less accurate and slower than the recommended Google Location Services API. In order to use it with React Native, use the react-native-geolocation-service module.
APIs
- setRNConfiguration()
geolocation.setRNConfiguration(config);
Sets configuration options that will be used in all location requests. - requestAuthorization()
geolocation.requestAuthorization();
Request suitable Location permission based on the key configured on pList. If NSLocationAlwaysUsageDescription is set, it will request Always authorization, although if NSLocationWhenInUseUsageDescription is set, it will request InUse authorization. - getCurrentPosition()
geolocation.getCurrentPosition(geo_success, [geo_error], [geo_options]);
Invokes the success callback once with the latest location info. - watchPosition()
geolocation.watchPosition(success, [error], [options]);
Invokes the success callback whenever the location changes. Returns a watchId (number). - clearWatch()
geolocation. clearWatch(watchID); - stopObserving()
geolocation.stopObserving();
Stops observing for device location changes. In addition, it removes all listeners previously registered.
Notice that this method has only effect if the geolocation.watchPosition(successCallback, errorCallback) method was previously invoked.