• Stars
    star
    101
  • Rank 325,945 (Top 7 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 8 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Background Upload plugin for the NativeScript framework

NativeScript 7

If using 6 and below, see the following:

Background Upload NativeScript plugin Build Status

A cross platform plugin for the NativeScript framework, that provides background upload for iOS and Android.

There is a stock NativeScript http module that can handle GET/POST requests that work with strings and JSONs. It however comes short in features when it comes to really large files.

The plugin uses NSURLSession with background session configuration for iOS; and a fork of the gotev/android-upload-service library for Android.

Installation

tns plugin add nativescript-background-http

Usage

The below attached code snippets demonstrate how to use nativescript-background-http to upload single or multiple files.

Uploading files

Sample code for configuring the upload session. Each session must have a unique id, but it can have multiple tasks running simultaneously. The id is passed as a parameter when creating the session (the image-upload string in the code bellow):

// file path and url
var file =  "/some/local/file/path/and/file/name.jpg";
var url = "https://some.remote.service.com/path";
var name = file.substr(file.lastIndexOf("/") + 1);

// upload configuration
var bghttp = require("nativescript-background-http");
var session = bghttp.session("image-upload");
var request = {
        url: url,
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream"
        },
        description: "Uploading " + name
    };

For a single file upload, use the following code:

var task = session.uploadFile(file, request);

For multiple files or to pass additional data, use the multipart upload method. All parameter values must be strings:

var params = [
   { name: "test", value: "value" },
   { name: "fileToUpload", filename: file, mimeType: "image/jpeg" }
];
var task = session.multipartUpload(params, request);

In order to have a successful upload, the following must be taken into account:

  • the file must be accessible from your app. This may require additional permissions (e.g. access documents and files on the device). Usually this is not a problem - e.g. if you use another plugin to select the file, which already adds the required permissions.
  • the URL must not be blocked by the OS. Android Pie or later devices require TLS (HTTPS) connection by default and will not upload to an insecure (HTTP) URL.

Upload request and task API

The request object parameter has the following properties:

Name Type Description
url string The request url (e.g.https://some.remote.service.com/path).
method string The request method (e.g. POST).
headers object Used to specify additional headers.
description string Used to help identify the upload task locally - not sent to the remote server.
utf8 boolean (Android only/multipart only) If true, sets the charset for the multipart request to UTF-8. Default is false.
androidDisplayNotificationProgress boolean (Android only) Used to set if progress notifications should be displayed or not. Please note that since API26, Android requires developers to use notifications when running background tasks. https://developer.android.com/about/versions/oreo/background
androidNotificationTitle string (Android only) Used to set the title shown in the Android notifications center.
androidAutoDeleteAfterUpload boolean (Android only) Used to set if files should be deleted automatically after upload.
androidMaxRetries number (Android only) Used to set the maximum retry count. The default retry count is 0. https://github.com/gotev/android-upload-service/wiki/Recipes#backoff
androidAutoClearNotification boolean (Android only) Used to set if notifications should be cleared automatically upon upload completion. Default is false. Please note that setting this to true will also disable the ringtones.
androidRingToneEnabled boolean (Android only) Used to set if a ringtone should be played upon upload completion. Default is true. Please note that this flag has no effect when androidAutoClearNotification is set to true.
androidNotificationChannelID string (Android only) Used to set the channel ID for the notifications.

The task object has the following properties and methods, that can be used to get information about the upload:

Name Type Description
upload number Bytes uploaded.
totalUpload number Total number of bytes to upload.
status string One of the following: error, uploading, complete, pending, cancelled.
description string The description set in the request used to create the upload task.
cancel() void Call this method to cancel an upload in progress.

Handling upload events

After the upload task is created you can monitor its progress using the following events:

task.on("progress", progressHandler);
task.on("error", errorHandler);
task.on("responded", respondedHandler);
task.on("complete", completeHandler);
task.on("cancelled", cancelledHandler); // Android only

Each event handler will receive a single parameter with event arguments:

// event arguments:
// task: Task
// currentBytes: number
// totalBytes: number
function progressHandler(e) {
    alert("uploaded " + e.currentBytes + " / " + e.totalBytes);
}

// event arguments:
// task: Task
// responseCode: number
// error: java.lang.Exception (Android) / NSError (iOS)
// response: net.gotev.uploadservice.ServerResponse (Android) / NSHTTPURLResponse (iOS)
function errorHandler(e) {
    alert("received " + e.responseCode + " code.");
    var serverResponse = e.response;
}


// event arguments:
// task: Task
// responseCode: number
// data: string
function respondedHandler(e) {
    alert("received " + e.responseCode + " code. Server sent: " + e.data);
}

// event arguments:
// task: Task
// responseCode: number
// response: net.gotev.uploadservice.ServerResponse (Android) / NSHTTPURLResponse (iOS)
function completeHandler(e) {
    alert("received " + e.responseCode + " code");
    var serverResponse = e.response;
}

// event arguments:
// task: Task
function cancelledHandler(e) {
    alert("upload cancelled");
}

Testing the plugin

In order to test the plugin, you must have a server instance to accept the uploads. There are online services that can be used for small file uploads - e.g. http://httpbin.org/post However, these cannot be used for large files. The plugin repository comes with a simple server you can run locally. Here is how to start it:

cd demo-server
npm i
node server 8080

The above commands will start a server listening on port 8080. Remember to update the URL in your app to match the address/port where the server is running.

Note: If you are using the iOS simulator then http://localhost:8080 should be used to upload to the demo server. If you are using an Android emulator, http://10.0.2.2:8080 should be used instead.

Contribute

We love PRs! Check out the contributing guidelines. If you want to contribute, but you are not sure where to start - look for issues labeled help wanted.

Get Help

Please, use github issues strictly for reporting bugs or requesting features. For general questions and support, check out Stack Overflow or ask our experts in NativeScript community Slack channel.

License

Apache License Version 2.0, January 2004

More Repositories

1

NativeScript

⚑ Empowering JavaScript with native platform APIs. ✨ Best of all worlds (TypeScript, Swift, Objective C, Kotlin, Java). Use what you love ❀️ Angular, Capacitor, Ionic, React, Solid, Svelte, Vue with: SwiftUI, Jetpack Compose, Flutter and you name it compatible.
TypeScript
23,002
star
2

nativescript-angular

Integrating NativeScript with Angular
TypeScript
1,213
star
3

nativescript-cli

Command-line interface for building NativeScript apps
JavaScript
1,036
star
4

android

Android runtime for NativeScript (based on V8)
C++
509
star
5

sample-Groceries

🍏 🍍 πŸ“ A NativeScript-built iOS and Android app for managing grocery lists
TypeScript
484
star
6

docs-v7

Documentation, API reference, and code snippets for NativeScript
CSS
444
star
7

nativescript-marketplace-demo

NativeScript kitchen sink demo. All of NativeScript’s functionality in one app.
TypeScript
325
star
8

ios-jsc

NativeScript for iOS using JavaScriptCore
JavaScript
295
star
9

nativescript-sdk-examples-ng

NativeScript and Angular code samples.
TypeScript
293
star
10

nativescript-app-templates

Monorepo for NativeScript app templates
TypeScript
216
star
11

nativescript-schematics

nativescript, mobile, schematics, angular
TypeScript
186
star
12

plugins

@nativescript plugins to help with your developments.
TypeScript
184
star
13

tailwind

Makes using TailwindCSS in NativeScript a whole lot easier!
JavaScript
140
star
14

theme

The gorgeous default NativeScript theme, currently under active development
SCSS
127
star
15

ios

NativeScript for iOS using V8
JavaScript
124
star
16

push-plugin

Contains the source code for the Push Plugin.
Objective-C
123
star
17

nativescript-app-sync

♻️ Update your app without going through the app store!
C
123
star
18

sample-ng-todomvc

Angular2 + NativeScript TodoMVC example
115
star
19

nativescript-imagepicker

Imagepicker plugin supporting both single and multiple selection.
TypeScript
104
star
20

nativescript-dev-webpack

A package to help with webpacking NativeScript apps.
JavaScript
97
star
21

nativescript-camera

NativeScript plugin to empower using device camera.
TypeScript
92
star
22

canvas

C++
87
star
23

android-dts-generator

A tool that generates TypeScript declaration files (.d.ts) from Jars
Java
87
star
24

nativescript-facebook

NativeScript plugin, wrapper of native Facebook SDK for Android and iOS
TypeScript
78
star
25

nativescript-dev-appium

A package to help with writing and executing e2e Appium tests in NativeScript apps
TypeScript
69
star
26

windows-runtime

NativeScript Runtime for the Universal Windows Platform
C
64
star
27

sample-android-background-services

Using Android Background Services in NativeScript
JavaScript
63
star
28

nx

NativeScript for Nx.
TypeScript
61
star
29

android-v8

Contains the Google's V8 build used in android runtime.
Shell
54
star
30

nativescript-fresco

This repository holds the NativeScript plugin that exposes the functionality of the Fresco image library to NativeScript developers.
TypeScript
52
star
31

nativescript-sdk-examples-js

JavaScript
50
star
32

firebase

Modular Firebase πŸ”₯ implementation for NativeScript. Supports both iOS & Android platforms for all Firebase services.
TypeScript
50
star
33

sample-Angular2

49
star
34

nativescript-canvas

HTML5-like 2D and WebGL canvas implementation for NativeScript
C++
48
star
35

nativescript-dev-sass

SASS CSS pre-processor for NativeScript projects
JavaScript
44
star
36

plugin-seed

TypeScript
42
star
37

angular

TypeScript
37
star
38

sample-ios-background-execution

Running Custom Background Tasks with NativeScript
JavaScript
36
star
39

worker-loader

JavaScript
36
star
40

functional-tests-core

Appium based framework for testing Android and iOS native mobile apps.
Java
36
star
41

nativescript-app-encryption

This plugin encrypts all your app/**.js files during a release build. In experimental state.
JavaScript
35
star
42

capacitor

NativeScript for Capacitor
TypeScript
34
star
43

tutorials

Project source to tutorials presented here: https://docs.nativescript.org/tutorial/
TypeScript
33
star
44

rfcs

RFCs for NativeScript and related tooling
33
star
45

capacitor-docs

JavaScript
30
star
46

payments

In-App Purchase, Subscriptions, Google Pay, Apple Pay for NativeScript
TypeScript
30
star
47

sample-iOS-Profiling

Performance comparison of popular cross-platform frameworks
JavaScript
29
star
48

docs-v8

HTML
29
star
49

sample-Android-Widgets

JavaScript
29
star
50

animation-demo

A sample app demonstrating different kinds of animations achieved with CSS, keyframes and NativeScript.
TypeScript
29
star
51

nativescript-datetimepicker

Plugin with date and time picking fields
TypeScript
26
star
52

nativescript-remote-builds

A NativeScript plugin for remote builds when running and publishing NativeScript apps without env setup.
JavaScript
26
star
53

login-tab-navigation-ng

{N} Angular with login and tabs page navigation
JavaScript
26
star
54

nativescript-ui-charts

NativeScript wrapper around HiCharts library
TypeScript
25
star
55

mlkit

TypeScript
24
star
56

workshop

NativeScript! And workshops! πŸŽ‰
TypeScript
23
star
57

nativescript-picker

Plugin that provides a custom TextField which lets you pick a value from a list opened in a modal popup.
TypeScript
22
star
58

nativescript-app-sync-server

JavaScript
22
star
59

sample-ImageUpload

An integration of nativescript-image-picker and nativescript-background-http
JavaScript
22
star
60

nativescript-cordova-support

A NativeScript plugin which enables you to use cordova plugins inside your NativeScript-based project.
Java
21
star
61

nativescript-dev-typescript

TypeScript support for NativeScript projects
JavaScript
20
star
62

sample-ios-embedded

Embedding the NativeScript for iOS runtime in an existing app
Objective-C
19
star
63

nativescript-angular-guide

A guide to building apps with NativeScript and Angular 2
HTML
17
star
64

summer-of-nativescript

Resources for the summer of NativeScript
JavaScript
17
star
65

sample-tvOS

A proof of concept app with the NativeScript runtime running on Apple TV
JavaScript
17
star
66

playground-feedback

Feedback for NativeScript Playground
15
star
67

artwork

NativeScript artwork
JavaScript
14
star
68

ios-device-lib

Allows interaction with iOS devices.
C++
14
star
69

nativescript-hook

Helper module for installing hooks into NativeScript projects
JavaScript
14
star
70

nativescript-ios-imessages

Simple app extension that interact with the Messages app
C
14
star
71

playground-tutorials

NativeScript Playground tutorials content
13
star
72

NativeScript-NEXT-Workshop

Workshop material for teaching NativeScript
13
star
73

nativescript-unit-test-runner

TypeScript
13
star
74

android-compose-example

@nativescript/jetpack-compose Example πŸš€πŸ““β™₯️
Kotlin
13
star
75

tns-core-modules-widgets

Repo for widgets used in NativeScript modules
Java
12
star
76

vue-x-platforms

Vue running on Web, iOS, Android and Vision Pro.
Vue
12
star
77

demo-workers

JavaScript
12
star
78

docs

The NativeScript Docs!
JavaScript
11
star
79

sample-iOS-HealthKit

This sample shows a simple use of the iOS HealthKit APIs.
JavaScript
11
star
80

sample-native-module

Sample native module for NativeScript
C++
11
star
81

examples-best-practices

TypeScript
10
star
82

functional-tests-demo

XSLT
10
star
83

ns-ng-animation-examples

TypeScript
10
star
84

pbxproj-dom

pbxproj object model
TypeScript
10
star
85

ios-metadata-generator

Visit the iOS Runtime repo for instructions and related issues
C++
10
star
86

nativescript-app-sync-web

Web client for the codepush server
JavaScript
9
star
87

ios-sim-portable

A Node.js command-line utility to launch an iOS application bundle (.app) in the Xcode iOS Simulator
TypeScript
9
star
88

visionos-hello-world

Vision Pro πŸ₯½ Hello World tutorial with NativeScript using various flavors - Angular, React, Solid, Svelte, TypeScript and Vue.
Swift
9
star
89

nativescript-dev-coffeescript

JavaScript
9
star
90

nativescript-doctor

Library that helps identifying if the environment can be used for development of {N} apps.
TypeScript
8
star
91

nativescript-dev-jade

JavaScript
8
star
92

eslint-plugin

ESLint plugin for NativeScript projects.
TypeScript
8
star
93

nativescript-cli-tests

NativeScript CLI Integration Tests
Python
8
star
94

androidx-migration-tool

JavaScript
8
star
95

nativescript-dev-debugging

This package allows the developer of a NativeScript plugin to use a workflow that allows to debug both the native iOS (objective-c, swift) and Android (Java) code and the wrapper TypeScript/JavaScript code of the plugin used inside an NativeScript application. This is a powerful "tool" which will rebuild both the native framework (iOS) and arr files (Android) and the TypeScript/JavaScript code of your NativeScript plugin.
JavaScript
8
star
96

widget-example

iOS Home Screen Widget Example
TypeScript
8
star
97

sample-iOS-CameraApp

In this sample we are demonstrating how you can write platform specific code with NativeScript. We are building iOS only app which uses the latest iOS8 camera APIs.
JavaScript
7
star
98

flutter-example

Using Flutter with NativeScript including Bluetooth integration via @nativescript-community/ble
Dart
7
star
99

storybook

πŸ“š Storybook for NativeScript πŸ“²
TypeScript
7
star
100

android-metadata-generator

Contains the source for metadata generation in Android Runtime
7
star