iOS – How To Manage App’s Life Cycle In iOS ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Manage App’s Life Cycle In iOS ?).

In this article, We will understand how to manage App’s Life Cycle in iOS. We will discuss how to respond to system notifications when our app is in the foreground or background, and handle other significant system-related events.

For Understanding the App’s Lifecycle concepts, We will discuss on the below topics:

  • Overview
  • Respond to The Scene-Based Life-Cycle Events
  • Responds to App-Based Life-Cycle Events
  • Respond to Other Significant Events

A famous quote about Learning is :

” One learns from books and example only that certain things can be done. Actual learning requires that you do those things. “

So Let’s begin.


Overview

The current state of our app determines what it can and cannot do at any time. For example, a foreground app has the user’s attention, so it has priority over system resources, including the CPU. By contrast, a background app must do as little work as possible, and preferably nothing, because it is offscreen. As our app changes from state to state, we must adjust its behavior accordingly.

When our app’s state changes, UIKit notifies us by calling methods of the appropriate delegate object:

  • In iOS 13 and later, use UISceneDelegate objects to respond to life-cycle events in a scene-based app.
  • In iOS 12 and earlier, use the UIApplicationDelegate object to respond to life-cycle events.

If we enable scene support in our app, iOS always uses our scene delegates in iOS 13 and later. In iOS 12 and earlier, the system uses our app delegate.


Respond to The Scene-Based Life-Cycle Events

If our app supports scenes, UIKit delivers separate life-cycle events for each. A scene represents one instance of our app’s UI running on a device. The user can create multiple scenes for each app, and show and hide them separately. Because each scene has its own life cycle, each can be in a different state of execution. For example, one scene might be in the foreground while others are in the background or are suspended.

Scene support is an opt-in feature. To enable basic support, add the UIApplicationSceneManifest key to our app’s Info.plist file.

The following figure shows the state transitions for scenes. When the user or system requests a new scene for our app, UIKit creates it and puts it in the unattached state. User-requested scenes move quickly to the foreground, where they appear onscreen. A system-requested scene typically moves to the background so that it can process an event. For example, the system might launch the scene in the background to process a location event. When the user dismisses our app’s UI, UIKit moves the associated scene to the background state and eventually to the suspended state. UIKit can disconnect a background or suspended scene at any time to reclaim its resources, returning that scene to the unattached state.

We use scene transitions to perform the following tasks:

  • When UIKit connects a scene to our app, configure our scene’s initial UI and load the data our scene needs.
  • When transitioning to the foreground-active state, configure our UI and prepare to interact with the user.
  • Upon leaving the foreground-active state, save data and quiet our app’s behavior.
  • Upon entering the background state, finish crucial tasks, free up as much memory as possible, and prepare for our app snapshot.
  • At scene disconnection, clean up any shared resources associated with the scene.
  • In addition to scene-related events, we must also respond to the launch of our app using our UIApplicationDelegate object.


Responds to App-Based Life-Cycle Events

In iOS 12 and earlier, and in apps that don’t support scenes, UIKit delivers all life-cycle events to the UIApplicationDelegate object. The app delegate manages all of your app’s windows, including those displayed on separate screens. As a result, app state transitions affect our app’s entire UI, including content on external displays.

App State Transitions

The following figure shows the state transitions involving the app delegate object. After launch, the system puts the app in the inactive or background state, depending on whether the UI is about to appear onscreen. When launching to the foreground, the system transitions the app to the active state automatically. After that, the state fluctuates between active and background until the app terminates.

We use app transitions to perform the following tasks:

  • At launch, initialize our app’s data structures and UI.
  • At activation, finish configuring our UI and prepare to interact with the user.
  • Upon deactivation, save data and quiet our app’s behavior.
  • Upon entering the background state, finish crucial tasks, free up as much memory as possible, and prepare for our app snapshot.
  • At termination, stop all work immediately and release any shared resources.


Respond to Other Significant Events

In addition to handling life-cycle events, apps must also be prepared to handle the events listed in the following below points. We can use our UIApplicationDelegate object to handle most of these events. In some cases, we may also be able to handle them using notifications, allowing us to respond from other parts of our app.

  • Memory warnings – Received when our app’s memory usage is too high. Reduce the amount of memory our app uses.
  • Protected data becomes available/unavailable – Received when the user locks or unlocks their device. We use applicationProtectedDataDidBecomeAvailable(_:) and applicationProtectedDataWillBecomeUnavailable(_:) methods to check protected data availability.
  • Handoff tasks – Received when an NSUserActivity object needs to be processed. We can use application(_:didUpdate:) method to handoff tasks.
  • Time changes – Received for several different time changes, such as when the phone carrier sends a time update. We can use applicationSignificantTimeChange(_:) method to see time changes.
  • Open URLs – Received when your app needs to open a resource. We can use application(_:open:options:) method to open URLs.

That’s all about in this article.


Conclusion

In this article, We understood how to manage App’s Life Cycle in iOS. We also discussed how to respond to system notifications when our app is in the foreground or background, and handle other significant system-related events in iOS.

Thanks for reading ! I hope you enjoyed and learned about App’s Lifecycle Management Concepts in iOS. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow other website and tutorials of iOS as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – Understanding Flexbox Layout

Hello Readers, CoolMonkTechie heartily welcomes you in this article (Understanding Flexbox Layout).

In this article, we will learn about Flexbox layout in React Native. We will discuss the different props of Flexbox layout for styling a component in React Native.

A component can specify the layout of its children using the Flexbox algorithm. Flexbox is designed to provide a consistent layout on different screen sizes. We will normally use a combination of flexDirectionalignItems, and justifyContent to achieve the right layout.

Flexbox works the same way in React Native as it does in CSS on the web, with a few exceptions. The defaults are different, with flexDirection defaulting to column instead of row, and the flex parameter only supporting a single number.

A famous quote about learning is :

” Wisdom is not a product of schooling but of the lifelong attempt to acquire it. “


So Let’s begin.


1. flex

flex will define how our items are going to “fill” over the available space along our main axis. Space will be divided according to each element’s flex property.

In React Native flex does not work the same way that it does in CSS. flex is a number rather than a string, and it works according to the Yoga.

When flex is a positive number, it makes the component flexible, and it will be sized proportional to its flex value. So a component with flex set to 2 will take twice the space as a component with flex set to 1. flex: <positive number> equates to flexGrow: <positive number>, flexShrink: 1, flexBasis: 0.

When flex is 0, the component is sized according to width and height, and it is inflexible.

When flex is -1, the component is normally sized according to width and height. However, if there’s not enough space, the component will shrink to its minWidth and minHeight.

flexGrowflexShrink, and flexBasis work the same as in CSS.

In the following example, the red, yellow, and green views are all children in the container view that has flex: 1 set. The red view uses flex: 1 , the yellow view uses flex: 2, and the green view uses flex: 3 . 1+2+3 = 6, which means that the red view will get 1/6 of the space, the yellow 2/6 of the space, and the green 3/6 of the space.


2. flexDirection

‘column’/’column-reverse’/’row’/’row-reverse’

Defines the direction of the main axis. Opposite to the web, React Native default flexDirection is column which makes sense, most mobile apps much more vertically oriented.


3. justifyContent

‘flex-start’, ’flex-end’, ’center’, ’space-between’, ’space-around’

Determines the distribution of children along the primary axis. justifyContent describes how to align children within the main axis of their container (parent container). The default value is flex-start.


4. alignItems

‘flex-start’, ‘flex-end’, ‘center’, ‘stretch

Align items along the cross axis. So in a default view, it will control the horizontal alignment of items. alignItems describes how to align children along the cross axis of their container (parent container). alignItems is very similar to justifyContent but instead of applying to the main axis, alignItems applies to the cross axis. The default value is stretch.

For instance, if the parent has a flexDirection set to row. Then the opposite axis is the column. The alignItems will then align the children based on the value provided in vertical(column) axis.


5. alignSelf

‘auto’, ‘flex-start’, ‘flex-end’, ‘center’, ‘stretch’

Align an item along the cross axis overwriting his parent alignItem property. alignSelf can apply the property to a single child within a parent element, instead of applying it to all the children.

alignSelf has the same options and effect as alignItems but instead of affecting the children within a container, we can apply this property to a single child to change its alignment within its parent. alignSelf overrides any option set by the parent with alignItems. The default value is auto.


6. flexWrap

‘wrap’, ‘nowrap’, ‘wrap-reverse’

Controls whether flex items are forced on a single line or can be wrapped on multiple lines. The default value is nowrap.


7. alignContent

‘flex-start’, ’center’, ’flex-end’, ’stretch’, ’space-between’, ’space-around’

Defines the distribution of lines along the cross-axis. This only has effect when items are wrapped to multiple lines using flexWrap. The default value is flex-start.


8. position

‘relative’/’absolute’

The position type of an element defines how it is positioned within its parent.

position in React Native is similar to regular CSS, but everything is set to relative by default, so absolute positioning is always relative to the parent.

If we want to position a child using specific numbers of logical pixels relative to its parent, set the child to have absolute position.

If we want to position a child relative to something that is not its parent, don’t use styles for that. Use the component tree.

For example, Think of our container as a line of people. And we are telling each person to stand 5 meters behind the person in front of him (marginTop: 5). If this person is set to relative he will respect the line and will position himself relatively to the person in front of him. If this person is set to absolute he will ignore all of the people in the line and will position himself as if the line was empty, 5 meters from where the line (his parent container) starts.


9. zIndex

zIndex controls which components display on top of others. Normally, we don’t use zIndex. Components render according to their order in the document tree, so later components draw over earlier ones. zIndex may be useful if we have animations or custom modal interfaces where we don’t want this behavior.

It works like the CSS z-index property – components with a larger zIndex will render on top. Think of the z-direction like it’s pointing from the phone into our eyeball.

On iOS, zIndex may require Views to be siblings of each other for it to work as expected.

In the following example the zIndex of the yellow square to 1.


10. Flex Basis, Grow, and Shrink

  • flexGrow  describes how any space within a container should be distributed among its children along the main axis. After laying out its children, a container will distribute any remaining space according to the flex grow values specified by its children. flexGrow accepts any floating point value >= 0, with 0 being the default value. A container will distribute any remaining space among its children weighted by the children’s flexGrow values.
  • flexShrink describes how to shrink children along the main axis in the case in which the total size of the children overflows the size of the container on the main axis. flexShrink is very similar to flexGrow and can be thought of in the same way if any overflowing size is considered to be negative remaining space. These two properties also work well together by allowing children to grow and shrink as needed. flexShrink accepts any floating point value >= 0, with 1 being the default value. A container will shrink its children weighted by the children’s flexShrink values.
  • flexBasis is an axis-independent way of providing the default size of an item along the main axis. Setting the flexBasis of a child is similar to setting the width of that child if its parent is a container with flexDirection: row or setting the height of a child if its parent is a container with flexDirection: column. The flexBasis of an item is the default size of that item, the size of the item before any flexGrow and flexShrink calculations are performed.


11. Width and Height

The width property specifies the width of an element’s content area. Similarly, the height property specifies the height of an element’s content area.

Both width and height can take the following values:

  • auto (default value) React Native calculates the width/height for the element based on its content, whether that is other children, text, or an image.
  • pixels Defines the width/height in absolute pixels. Depending on other styles set on the component, this may or may not be the final dimension of the node.
  • percentage Defines the width or height in percentage of its parent’s width or height, respectively.

That’s all about in this article.


Conclusion

In this article, We understood about Flexbox layout in React Native. We also discussed the different basic props of Flexbox layout for styling a component in React Native. 

Thanks for reading ! I hope you enjoyed and learned about the Flexbox layout concepts in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

React Native – How To Create Responsive Layouts In React Native ?

Hello Readers, CoolMonkTechie heartily welcomes you in this article (How To Create Responsive Layouts In React Native ?).

In this article, we will learn how to create Responsive Layouts in React Native. Native application developers put a lot of effort into making engaging and stable apps that are supported on multiple devices. This means that Android developers have to make sure that their apps are supported on hundreds of devices. iOS developers also need to support their apps on a growing number of devices.

React Native enables developers to develop apps that can run both on iOS and Android. The problem is that the number of devices they need to support now is doubled. One particular problem is making the app responsive. There is no such thing as CSS media queries in React Native. React Native developers need to scale all of their layouts to make the app responsive on smartphones, tablets, and other devices.

A famous quote about learning is :

” I am always ready to learn although I do not always like being taught. “


So Let’s begin.


Problems With Responsive Layout in React Native

React Native developers make their apps work on one-dimensional devices as a default. As a result, the app looks distorted on devices with different dimensions because different devices have different pixel ratios. React Native style properties accept either Density-Independent Pixels (DP) or percentage.


Independent Pixels

A density-independent pixel is a unit of length that enables mobile apps to scale across different screen sizes. DPs are not the classic screen pixels. Rather, DPs are mathematically calculated through the following equation: DP=PX/ScaleFactor.

PX is the number of classic screen pixels, and the scaling factor indicates how much the pixels should be enlarged.

React Native developers can scale DP values to screens of different sizes only if they have the same resolution. The problem is that there are hundreds of different devices and most of them have screens with different resolutions.


Percentage

Most web development frameworks use percentage values to design different layouts. However, React Native style properties like border-radius and border-width do not accept percentage value. Properties that do accept percentage include maxWidthminWidthmargin and height.


Useful Tips for Creating Responsive Layouts for React Native Apps

The following tips will help us develop responsive React Native apps on a massive range of devices.


1. Layout With Flexbox

Components can control layout with a flexbox algorithm. It’s created to keep the proportions and consistency of the layout on different screen sizes.

Flexbox works very similar to CSS on the Web with just a few exceptions which are really easy to learn. When flex prop is a positive number, then components become flexible and will adjust to the screen respective to its flex value. That means that flex equates to flexGrow: [number], flexShrink: 1, flexBasis: 0.

When flex: 0 — it’s sized accordingly to the height and width and is inflexible. If flex is a negative number it also uses height and width but if there is not enough space it will shrink to its minHeight and minWidth.

There are few main properties provided by flexbox, so let’s get through them!

Flex – describes how elements divide space between them. As mentioned above it’s limited to single numbers. If all elements have flex: 1 they will have the same width. In other cases they will split the sum of the flex among themselves.

Flex direction – controls the direction or the main axis of the content layout. You can layout the content in a row or in a column. The default direction is a column because of the nature of mobile device screens.

Justify content – describes the position of content along the main axis. You can align the content to the right-left of the center of the main axis. You can also determine the space between content components.

Align items – aligns content on the cross axis, as opposed to justifyContent that aligns on the main axis.

Flex prop do a really good job of keeping proportions between elements. Regardless of screen size. FlexDirection and justifyContent keep layout behaviour consistent.

There are many more flexbox props. We touched just a few to show how they can be helpful.


2. Aspect Ratio

Another cool prop is aspect ratio which helps keep proportions of our elements under control. Aspect ratio describes the relationship between the width and the height of an image. It is usually expressed as two numbers separated by a colon, like 16:9. Aspect ratio is a non-standard property available only in React Native, and not in CSS. The aspect ratio property controls the size of undefined element dimensions.

For example, we can use the aspectRatio property to adjust images to screen size when our images extend beyond the screen dimensions. We do not need to know the actual width and height of the image, just set the aspect ratio to 1:1. Our images will take all available screen width, without extending beyond the dimensions.


3. Screen Dimensions

It is great when our designs are the same for both platforms, and all types of devices (mobile, tablets, ipads). However, sometimes we have to deal with different layouts for specific screen dimensions or device types.

React Native does not provide properties that can identify the device type or screen size when we work with different layouts. The solution is to use the Dimensions API. The syntax for obtaining the dimensions of a screen is:

import { Dimensions } from 'react-native';

const {width, height} = Dimensions.get(‘window');

Since React Native 0.61 we can also use a hook.

const {width, height} = useWindowDimensions();

Once we obtain the width from supported range screen sizes , we can pick breakpoints from which our layout can change. We can provide different styles to component or hide some parts of the screen. This is similar behaviour to media queries used in CSS.

import { Text, View, Dimensions } from 'react-native';
 
class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      width: Dimensions.get('window').width
    };
  }
 
  render() {
    return (
     <View>
       {this.state.width < 320 ? <Text>width of the past</Text> : <Text>how big is big enough?</Text>}
     </View>
    );
  }
}


4. Detect the Platform

Apart from screen size we can also change the layout depending on which platform app is launched. To achieve this , we can use the Platform module.

There are many cases where it can be used:

In component render function:

<View>
    {Platform.OS === 'ios' ? <Text>Hi Apple!</Text> : <Text>Hi Android!</Text>}
 </View>

In styles:

cube: {
    width: Platform.OS === 'ios' ? 200 : 300,
    aspectRatio: 1
  }

The Platform module provides select method which can accept any type of args. With this flexibility, we can achieve the same effect as above but cleaner code:

const Logo = Platform.select({
  ios: () => require('Apple'),
  android: () => require('Android'),
})();
 
<Logo />;

In styles:

import {Platform, StyleSheet} from 'react-native';
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    ...Platform.select({
      ios: {
        backgroundColor: 'red',
      },
      android: {
        backgroundColor: 'blue',
      },
    }),
  },
});


5. Device Rotation

Many apps can work in portrait and landscape mode. If this is the case for our app , we have to ensure that the layout doesn’t break when changing orientation. As we can expect sometimes the layout can change drastically when we flip the device. Our components may need different styling depending on the orientation. Unfortunately, by default rotation of the device does not trigger a re-render. That’s why it has to be handled manually. We already have the knowledge required to build our own and it’s quite easy!

class RotateComponent extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
 
  getOrientation = () => {
    if (Dimensions.get('window').width < Dimensions.get('window').height) {
      this.setState({ orientation: 'portrait' });
    } else { this.setState({ orientation: 'landscape' }); }
  };
 
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
  render() {
    return (
      <Text>{this.state.orientation}</Text>
    );
  }
}

If we need to support orientation change across the app, it’s a good idea to use HOC to inject orientation.

const HOC = WrappedComponent => class extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      orientation: ''
    };
  }
  componentDidMount() {
    Dimensions.addEventListener('change', this.getOrientation);
  }
 
      getOrientation = () => {
        if (Dimensions.get('window').width < Dimensions.get('window').height) {
          this.setState({ orientation: 'portrait' });
        } else { this.setState({ orientation: 'landscape' }); }
      };
 
      render() {
        return <WrappedComponent {...this.props} orientation={this.state.orientation} />;
      }
};

We can also pass getOrientation to onLayout prop exposed by View component. It is fired on every layout change, so it should be used carefully.

If we want to take advantage of the orientation in our styles, remember that it should be inline styles. We already know how to trigger a re-render of the layout when the device is rotated, but the styles are loaded only once. That’s why styles which affect the layout on rotation should be placed inline.

That’s all about in this article.


Conclusion

In this article, We understood how to create Responsive Layouts in React Native. We reviewed responsive layouts challenges in React Native apps and provided solutions for making our responsive layouts much easier. Responsiveness solutions include techniques like Flexbox, dimensions, and aspect ratio properties. In addition, we can detect the device platform and screen orientation to adjust our app to different screen sizes. 

Thanks for reading ! I hope you enjoyed and learned about the Responsive Layout challenges and solutions in React Native. Reading is one thing, but the only way to master it is to do it yourself.

Please follow and subscribe us on this blog and support us in any way possible. Also like and share the article with others for spread valuable knowledge.

You can find Other articles of CoolmonkTechie as below link :

You can also follow official website and tutorials of React Native as below links :

If you have any comments, questions, or think I missed something, feel free to leave them below in the comment box.

Thanks again Reading. HAPPY READING !!???

Exit mobile version