Rupert  Beatty

Rupert Beatty

1673098980

LeeGo: Declarative, Configurable & Highly Reusable UI Development

LeeGo

LeeGo is a lightweight Swift framework that helps you decouple & modularise your UI component into small pieces of LEGO style's bricks, to make UI development declarative, configurable and highly reusable.

Rational behind

We all know that MVC pattern has some serious problems when dealing with a complex iOS project. Fortunately there are also a bunch of approaches that aim to fix the problems, most of them mainly address the Controller part, such as MVP, MVVM, MVSM or VIPER. But there is barely a thing which addresses the View part. Does that mean we just run out of all the problems in the View part ? I think the answer is NO, especially when we need our app to be fully responsive.

I’ve talked this idea on a dotSwift’s talk, and also on my blog posts:

Please checkout through for more details.

LeeGo, replaces the View part of MVC by Brick.

LeeGo

Features

What may LeeGo helps you:

  • Describe your whole UI in small pieces of Lego style’s bricks. Let you configure your view as a brick whenever & wherever you want.
  • No longer need to deal with a bunch of custom UIView’s subclasses. Instead, you only need to deal with different Bricks which is lightweight and pure value type.
  • Designed to be UIKit friendly and non-intrusive. There is no need to inherit from other base class at all.
  • Capable to update remotely almost everything via your JSON payload.
  • Built-in convenience methods to make UIStackView like layout hassle-free.
  • Built-in self-sizing mechanism to calculate cell’s height automatically.
  • Method chaining syntax sugar.
  • Benefits from Swift’s enum, let you put the whole UI in a single enum file.

Compare with Facebook ComponentKit

Both:

  • Brings declarative, configurable & reusable UI development for iOS.

Pros:

  • Written in Swift, built for Swift. No more Obj-C++ stuff.
  • Lightweight and UIKit friendly. No inheritance, dealing with standard UIView and Auto Layout directly.
  • Totally smooth to begin with integrating only a small part, also free to drop all without any side effect.
  • Possible to update any part of UI which powered by LeeGo remotely via JSON payload.
  • Powered by standard auto layout which you probably familiar with already.

Cons:

  • Lack of high level features for the moment. Such as support of built-in configurable view controller, view animation, auto layout animation or UIControl component’s action.
  • Powered by standard auto layout which may have some potential performance issues in some circumstances.
  • Still requires the basic knowledge of standard auto layout and Visual Format Language.

Full Documentation

Usages

Basic bricks

Create a Brick instance which named "title" as UILabel, with default text "Showcase" and gray background color

import LeeGo

let titleBrick: Brick = "title".build(UILabel).style([.text("Showcase"), .backgroundColor(.lightGrayColor())])

Configure an UILabel instance just as title brick

let titleLabel = UILabel()
titleLabel.lg_configureAs(titleBrick)

#### More complex bricks Create the bricks inside a cell brick


let titleBrick = "title".build(UILabel).style([.numberOfLines(0), .text("title")])
let subtitleBrick = "subtitle".build(UILabel).style([.textColor(.lightGrayColor()), .numberOfLines(0), .font(.systemFontOfSize(14)), .text("subtitle")])
let imageBrick = "image".build(UIImageView).style([.ratio(1.5), .backgroundColor(.blueColor())]).width(68)

/// Create a brick stand for `UIView` which contains a `title`,
/// a `subtitle` and an `image` inside, layout them with
/// standard auto layout VFL.
let brickName = "cell"
let cellBrick = brickName.build().bricks(titleBrick, subtitleBrick, imageBrick) {
    title, subtitle, image in
    return Layout([
            "H:|-left-[\(image)]-spaceH-[\(title)]-right-|",
            "H:[\(image)]-spaceH-[\(subtitle)]-right-|",
            "V:|-top-[\(title)]-spaceV-[\(subtitle)]-(>=bottom)-|",
            "V:|-top-[\(image)]-(>=bottom)-|"], metrics: LayoutMetrics(20, 20, 20, 20, 10, 10))
}

Dequeue a standard UICollectionViewCell instance, then configure it as cell brick with element as data source

let cell = collectionView.dequeueCell…
cell.lg_configureAs(cellBrick, dataSource: element[indexPath.item])

UIStackView inspired layout

Create a brick stand for UIView which contains the 3 bricks (red, green & blue block), then lay them out with the UIStackView inspired layout helper method.

let bricks = ["red".build().style(Style.redBlockStyle).height(50),
 "green".build().style(Style.greenBlockStyle).height(80),
 "blue".build().style(Style.blueBlockStyle).height(30)]

let layout = Layout(bricks: bricks, axis: .Horizontal, align: .Top, distribution: .FillEqually, metrics: LayoutMetrics(10, 10, 10, 10, 10, 10))
let viewBrick = "view".build().style(Style.blocksStyle).bricks(bricks, layout: layout).height(100)

Configure a UIView instance just as the brick

view.lg_configureAs(viewBrick)

#### Union different bricks Union different bricks to a new brick with `UIStackView` style’s layout.

let viewBrick = Brick.union("brickName", bricks: [
                    title,
                    subtitle,
                    Brick.union("blocks", bricks: [
                        redBlock.height(50),
                        greenBlock.height(80),
                        blueBlock.height(30)], axis: .Horizontal, align: .Top, distribution: .FillEqually, metrics: LayoutMetrics(10, 10, 10, 10, 10, 10)).style([.backgroundColor(.yellowColor())])
                    ], axis: .Vertical, align: .Fill, distribution: .Flow(3), metrics: LayoutMetrics(20, 20, 20, 20, 10, 10))
                

Configure a UIView instance just as the brick

view.lg_configureAs(viewBrick)

#### More complex brick and build with an enum An enum which implements `BrickBuilderType`, used to centralize all `brick` designs in a single enum file.

import LeeGo

enum TwitterBrickSet: BrickBuilderType {
    // leaf bricks
    case username, account, avatar, tweetText, tweetImage, date, replyButton, retweetButton, retweetCount, likeButton, likeCount
    
    // complex bricks
    case retweetView, likeView
    case accountHeader, toolbarFooter, retweetHeader
    
    // root bricks
    case standardTweet

    static let brickClass: [Twitter: AnyClass] = [username: UILabel.self, account: UILabel.self, avatar: UIImageView.self, tweetText: UITextView.self]
    
    func brick() -> Brick {
        switch self {
        case .username:
            return build().style([.font(.boldSystemFontOfSize(14))])
        case .account:
            return build().style([.font(.systemFontOfSize(14))])
        case .avatar:
            return build().style([.ratio(1), .backgroundColor(.lightGrayColor()), .cornerRadius(3)]).width(50)
        case .tweetText:
            return build().style([.scrollEnabled(false)])
        …
        case .standardTweet:
            return build().style([.backgroundColor(.whiteColor())])
                .bricks(
                    avatar.brick(),
                    accountHeader.brick(),
                    tweetText.brick(),
                    tweetImage.brick(),
                    toolbarFooter.brick()
                ) { (avatar, accountHeader, tweetText, image, toolbarFooter) in
                    Layout(["H:|-10-[\(avatar)]-10-[\(tweetText)]-10-|",
                        "H:[\(avatar)]-10-[\(accountHeader)]-10-|",
                        "H:[\(avatar)]-10-[\(image)]-10-|",
                        "H:[\(avatar)]-10-[\(toolbarFooter)]-10-|",
                        "V:|-10-[\(avatar)]-(>=10)-|",
                        "V:|-10-[\(accountHeader)]-10-[\(tweetText)]-10-[\(image)]-10-[\(toolbarFooter)]-(>=10)-|"])
            }
        }
    }
}

/// Configure your cell
let cell = collectionView.dequeueCell…
cell.lg_configureAs(TwitterBrickSet.standardTweet.brick(), dataSource: element[indexPath.item])

## Update UI remotely `Brick` is designed to be JSON convertible, which makes possible that you can control your app’s interface, from tweak some UIKit appearances to create view/cell with brand new design **remotely** via JSON payload. Please check out ["JSON encodable & decodable"](Docs/Remote.md) for more details.

Best practices

For best practices and more design details, please checkout more design details

Installation

CocoaPods

LeeGo is available through CocoaPods. To install it, simply add the following line to your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '8.0'
use_frameworks!

pod "LeeGo"

Carthage

To integrate LeeGo into your Xcode project using Carthage, specify it in your Cartfile:

github "wangshengjia/LeeGo"

Then, run the following command to build the LeeGo framework:

$ carthage update

At last, you need to set up your Xcode project manually to add the LeeGo framework.

Contributing

If you like LeeGo and willing to make it better, you are more than welcomed to send pull request for:

  • Proposing new features.
  • Answering questions on issues.
  • Improving documentation.
  • Reviewing pull requests.
  • Finding, reporting or fixing bugs.

Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by [its terms](Docs/Code of Conduct.md).

Well...

If you have any thing want to tell me, please ping me on Twitter, on Weibo or just fire the issue.

I'd like to thank every one who helped me, inspired me and encouraged me. Also thank to my team at Le Monde, especially Vincent & Blaise.

Enjoy~ 🎉 🎉 🍻 🍻

Download Details:

Author: Wangshengjia
Source Code: https://github.com/wangshengjia/LeeGo 
License: MIT license

#swift #ios #components 

What is GEEK

Buddha Community

LeeGo: Declarative, Configurable & Highly Reusable UI Development

Hire Dedicated UI/UX Developer

Do you need UI/UX Designers for hire?

Hire Dedicated UI/UX Developer from HourlyDeveloper.io, having minimum years of experience in the various critical user experience designing projects. Our UI UX designers are highly passionate about developing user interface designs to propaganda user experience. We offer a various range of UI UX development services to our global clients ensuring enhancement in the productivity and ROI.

Contact us:- https://bit.ly/2YMesRJ

#hire dedicated ui/ux developer #ui/ux developer #ui/ux development company #ui/ux development services #ui designer #ux designer

Fredy  Larson

Fredy Larson

1595059664

How long does it take to develop/build an app?

With more of us using smartphones, the popularity of mobile applications has exploded. In the digital era, the number of people looking for products and services online is growing rapidly. Smartphone owners look for mobile applications that give them quick access to companies’ products and services. As a result, mobile apps provide customers with a lot of benefits in just one device.

Likewise, companies use mobile apps to increase customer loyalty and improve their services. Mobile Developers are in high demand as companies use apps not only to create brand awareness but also to gather information. For that reason, mobile apps are used as tools to collect valuable data from customers to help companies improve their offer.

There are many types of mobile applications, each with its own advantages. For example, native apps perform better, while web apps don’t need to be customized for the platform or operating system (OS). Likewise, hybrid apps provide users with comfortable user experience. However, you may be wondering how long it takes to develop an app.

To give you an idea of how long the app development process takes, here’s a short guide.

App Idea & Research

app-idea-research

_Average time spent: two to five weeks _

This is the initial stage and a crucial step in setting the project in the right direction. In this stage, you brainstorm ideas and select the best one. Apart from that, you’ll need to do some research to see if your idea is viable. Remember that coming up with an idea is easy; the hard part is to make it a reality.

All your ideas may seem viable, but you still have to run some tests to keep it as real as possible. For that reason, when Web Developers are building a web app, they analyze the available ideas to see which one is the best match for the targeted audience.

Targeting the right audience is crucial when you are developing an app. It saves time when shaping the app in the right direction as you have a clear set of objectives. Likewise, analyzing how the app affects the market is essential. During the research process, App Developers must gather information about potential competitors and threats. This helps the app owners develop strategies to tackle difficulties that come up after the launch.

The research process can take several weeks, but it determines how successful your app can be. For that reason, you must take your time to know all the weaknesses and strengths of the competitors, possible app strategies, and targeted audience.

The outcomes of this stage are app prototypes and the minimum feasible product.

#android app #frontend #ios app #minimum viable product (mvp) #mobile app development #web development #android app development #app development #app development for ios and android #app development process #ios and android app development #ios app development #stages in app development

UI/UX Design & Development Company | UI/UX Design Services

UI/UX Design & Development Company

The main factor that defines the success of any mobile app or website is the UI/UX of that app. The UI/UX is responsible for app elegance and ease of use of the app or website.

Want a unique UI/UX designer for an app or website development?

WebClues Infotech has the best UI/UX developers as they have a good experience of developing more than 950+ designs for the customers of WebClues Infotech. With a flexible price structure based on customer requirements, WebClues Infotech is one of the efficient and flexible UI/UX developers.

Want to know more about our UI/UX design services?

Visit: https://www.webcluesinfotech.com/ui-ux-development-company/

Share your requirements https://www.webcluesinfotech.com/contact-us/

View Portfolio https://www.webcluesinfotech.com/portfolio/

#ui/ux design & development company #ui/ux design services #ui ux design company #ui/ux development services #hire ui/ux designers #hire dedicated ui/ux designer

Mitchel  Carter

Mitchel Carter

1602979200

Developer Career Path: To Become a Team Lead or Stay a Developer?

For a developer, becoming a team leader can be a trap or open up opportunities for creating software. Two years ago, when I was a developer, I was thinking, “I want to be a team leader. It’s so cool, he’s in charge of everything and gets more money. It’s the next step after a senior.” Back then, no one could tell me how wrong I was. I had to find it out myself.

I Got to Be a Team Leader — Twice

I’m naturally very organized. Whatever I do, I try to put things in order, create systems and processes. So I’ve always been inclined to take on more responsibilities than just coding. My first startup job, let’s call it T, was complete chaos in terms of development processes.

Now I probably wouldn’t work in a place like that, but at the time, I enjoyed the vibe. Just imagine it — numerous clients and a team leader who set tasks to the developers in person (and often privately). We would often miss deadlines and had to work late. Once, my boss called and asked me to come back to work at 8 p.m. to finish one feature — all because the deadline was “the next morning.” But at T, we were a family.

We also did everything ourselves — or at least tried to. I’ll never forget how I had to install Ubuntu on a rack server that we got from one of our investors. When I would turn it on, it sounded like a helicopter taking off!

At T, I became a CTO and managed a team of 10 people. So it was my first experience as a team leader.

Then I came to work at D — as a developer. And it was so different in every way when it came to processes.

They employed classic Scrum with sprints, burndown charts, demos, story points, planning, and backlog grooming. I was amazed by the quality of processes, but at first, I was just coding and minding my own business. Then I became friends with the Scrum master. I would ask him lots of questions, and he would willingly answer them and recommend good books.

My favorite was Scrum and XP from the Trenches by Henrik Kniberg. The process at D was based on its methods. As a result, both managers and sellers knew when to expect the result.

Then I joined Skyeng, also as a developer. Unlike my other jobs, it excels at continuous integration with features shipped every day. Within my team, we used a Kanban-like method.

We were also lucky to have our team leader, Petya. At our F2F meetings, we could discuss anything, from missing deadlines to setting up a task tracker. Sometimes I would just give feedback or he would give me advice.

That’s how Petya got to know I’d had some management experience at T and learned Scrum at D.

So one day, he offered me to host a stand-up.

#software-development #developer #dev-team-leadership #agile-software-development #web-development #mobile-app-development #ios-development #android-development

Background Fetch for React Native Apps

react-native-background-fetch

Background Fetch is a very simple plugin which attempts to awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.

There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently or if an iOS user disables background refresh they may not happen at all.

:new: Background Fetch now provides a scheduleTask method for scheduling arbitrary "one-shot" or periodic tasks.

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android

Installing the plugin

⚠️ If you have a previous version of react-native-background-fetch < 2.7.0 installed into react-native >= 0.60, you should first unlink your previous version as react-native link is no longer required.

$ react-native unlink react-native-background-fetch

With yarn

$ yarn add react-native-background-fetch

With npm

$ npm install --save react-native-background-fetch

Setup Guides

iOS Setup

react-native >= 0.60

Android Setup

react-native >= 0.60

Example

ℹ️ This repo contains its own Example App. See /example

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import {
  Header,
  Colors
} from 'react-native/Libraries/NewAppScreen';

import BackgroundFetch from "react-native-background-fetch";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    // Initialize BackgroundFetch ONLY ONCE when component mounts.
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    // BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      await this.addEvent(taskId);
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);
  }

  // Add a BackgroundFetch event to <FlatList>
  addEvent(taskId) {
    // Simulate a possibly long-running asynchronous task with a Promise.
    return new Promise((resolve, reject) => {
      this.setState(state => ({
        events: [...state.events, {
          taskId: taskId,
          timestamp: (new Date()).toString()
        }]
      }));
      resolve();
    });
  }

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <Header />

            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
              </View>
            </View>
          </ScrollView>
          <View style={styles.sectionContainer}>
            <FlatList
              data={this.state.events}
              renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
              keyExtractor={item => item.timestamp}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
});

export default App;

Executing Custom Tasks

In addition to the default background-fetch task defined by BackgroundFetch.configure, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional Setup Instructions). However, all events will be fired into the Callback provided to BackgroundFetch#configure:

⚠️ iOS:

  • scheduleTask on iOS seems only to run when the device is plugged into power.
  • scheduleTask on iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks. scheduleTask will never run as frequently as you want.
  • The default fetch event is much more reliable and fires far more often.
  • scheduleTask on iOS stop when the user terminates the app. There is no such thing as stopOnTerminate: false for iOS.
// Step 1:  Configure BackgroundFetch as usual.
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback
  // This is the fetch-event callback.
  console.log("[BackgroundFetch] taskId: ", taskId);

  // Use a switch statement to route task-handling.
  switch (taskId) {
    case 'com.foo.customtask':
      print("Received custom task");
      break;
    default:
      print("Default fetch task");
  }
  // Finish, providing received taskId.
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});

// Step 2:  Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  forceAlarmManager: true,
  delay: 5000  // <-- milliseconds
});

API Documentation

Config

Common Options

@param {Integer} minimumFetchInterval [15]

The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval.

@param {Integer} delay (milliseconds)

ℹ️ Valid only for BackgroundFetch.scheduleTask. The minimum number of milliseconds in future that task should execute.

@param {Boolean} periodic [false]

ℹ️ Valid only for BackgroundFetch.scheduleTask. Defaults to false. Set true to execute the task repeatedly. When false, the task will execute just once.

Android Options

@config {Boolean} stopOnTerminate [true]

Set false to continue background-fetch events after user terminates the app. Default to true.

@config {Boolean} startOnBoot [false]

Set true to initiate background-fetch events when the device is rebooted. Defaults to false.

NOTE: startOnBoot requires stopOnTerminate: false.

@config {Boolean} forceAlarmManager [false]

By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.

Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.

let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15,
  forceAlarmManager: true
}, async (taskId) => {  // <-- Event callback
  console.log("[BackgroundFetch] taskId: ", taskId);
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});
.
.
.
// And with with #scheduleTask
BackgroundFetch.scheduleTask({
  taskId: 'com.foo.customtask',
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false
});

@config {Boolean} enableHeadless [false]

Set true to enable React Native's Headless JS mechanism, for handling fetch events after app termination.

  • 📂 index.js (MUST BE IN index.js):
import BackgroundFetch from "react-native-background-fetch";

let MyHeadlessTask = async (event) => {
  // Get task id from event {}:
  let taskId = event.taskId;
  let isTimeout = event.timeout;  // <-- true when your background-time has expired.
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing immediately finish(taskId)
    console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
    BackgroundFetch.finish(taskId);
    return;
  }
  console.log('[BackgroundFetch HeadlessTask] start: ', taskId);

  // Perform an example HTTP request.
  // Important:  await asychronous tasks when using HeadlessJS.
  let response = await fetch('https://reactnative.dev/movies.json');
  let responseJson = await response.json();
  console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

  // Required:  Signal to native code that your task is complete.
  // If you don't do this, your app could be terminated and/or assigned
  // battery-blame for consuming too much time in background.
  BackgroundFetch.finish(taskId);
}

// Register your BackgroundFetch HeadlessTask
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);

@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]

Set basic description of the kind of network your job requires.

If your job doesn't need a network connection, you don't need to use this option as the default value is BackgroundFetch.NETWORK_TYPE_NONE.

NetworkTypeDescription
BackgroundFetch.NETWORK_TYPE_NONEThis job doesn't care about network constraints, either any or none.
BackgroundFetch.NETWORK_TYPE_ANYThis job requires network connectivity.
BackgroundFetch.NETWORK_TYPE_CELLULARThis job requires network connectivity that is a cellular network.
BackgroundFetch.NETWORK_TYPE_UNMETEREDThis job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like".
BackgroundFetch.NETWORK_TYPE_NOT_ROAMINGThis job requires network connectivity that is not roaming (being outside the country of origin)

@config {Boolean} requiresBatteryNotLow [false]

Specify that to run this job, the device's battery level must not be low.

This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.

@config {Boolean} requiresStorageNotLow [false]

Specify that to run this job, the device's available storage must not be low.

This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.

@config {Boolean} requiresCharging [false]

Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.

@config {Boolean} requiresDeviceIdle [false]

When set true, ensure that this job will not run if the device is in active use.

The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.

This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.


Methods

Method NameArgumentsReturnsNotes
configure{FetchConfig}, callbackFn, timeoutFnPromise<BackgroundFetchStatus>Configures the plugin's callbackFn and timeoutFn. This callback will fire each time a background-fetch event occurs in addition to events from #scheduleTask. The timeoutFn will be called when the OS reports your task is nearing the end of its allowed background-time.
scheduleTask{TaskConfig}Promise<boolean>Executes a custom task. The task will be executed in the same Callback function provided to #configure.
statuscallbackFnPromise<BackgroundFetchStatus>Your callback will be executed with the current status (Integer) 0: Restricted, 1: Denied, 2: Available. These constants are defined as BackgroundFetch.STATUS_RESTRICTED, BackgroundFetch.STATUS_DENIED, BackgroundFetch.STATUS_AVAILABLE (NOTE: Android will always return STATUS_AVAILABLE)
finishString taskIdVoidYou MUST call this method in your callbackFn provided to #configure in order to signal to the OS that your task is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
startnonePromise<BackgroundFetchStatus>Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
stop[taskId:String]Promise<boolean>Stop the background-fetch API and all #scheduleTask from firing events. Your callbackFn provided to #configure will no longer be executed. If you provide an optional taskId, only that #scheduleTask will be stopped.

Debugging

iOS

🆕 BGTaskScheduler API for iOS 13+

  • ⚠️ At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
  • See Apple docs Starting and Terminating Tasks During Development
  • After running your app in XCode, Click the [||] button to initiate a Breakpoint.
  • In the console (lldb), paste the following command (Note: use cursor up/down keys to cycle through previously run commands):
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
  • Click the [ > ] button to continue. The task will execute and the Callback function provided to BackgroundFetch.configure will receive the event.

Simulating task-timeout events

  • Only the new BGTaskScheduler api supports simulated task-timeout events. To simulate a task-timeout, your fetchCallback must not call BackgroundFetch.finish(taskId):
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback.
  // This is the task callback.
  console.log("[BackgroundFetch] taskId", taskId);
  //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
}, async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  print("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
  • Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]

Old BackgroundFetch API

  • Simulate background fetch events in XCode using Debug->Simulate Background Fetch
  • iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, your can be sure that everything is working fine. You just need to wait.

Android

  • Observe plugin logs in $ adb logcat:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
  • Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk 21+:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
  • For devices with sdk <21, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH

Download Details:
Author: transistorsoft
Source Code: https://github.com/transistorsoft/react-native-background-fetch
License: MIT license

#react  #reactnative  #mobileapp  #javascript