Skip to content

Instantly share code, notes, and snippets.

@SilentKernel
Created March 12, 2018 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SilentKernel/eacfee4093e9990607f9f87ecd5c7494 to your computer and use it in GitHub Desktop.
Save SilentKernel/eacfee4093e9990607f9f87ecd5c7494 to your computer and use it in GitHub Desktop.
import {Injectable} from "@angular/core";
import {Httpd} from "@ionic-native/httpd";
import {File} from '@ionic-native/file';
import {Platform} from 'ionic-angular';
import {Subscription} from "rxjs/Subscription";
@Injectable()
export class IosHttpdService {
private readonly serverPort: number = 1210;
private platformIsReady: boolean = false;
private platformListener: boolean = false;
private serverSubscription: Subscription = null;
private serverUrl: string = null;
constructor(private httpd: Httpd, private file: File, private platform: Platform) {
}
platformReadyNow(): Promise<boolean> {
return new Promise<boolean>((resolve, reject) => {
if (this.platform.is('ios')) {
this.platformIsReady = true;
}
resolve(this.platformIsReady);
});
}
stopAndResumeListener() {
if (!this.platformListener) {
this.platformListener = true;
this.platform.resume.subscribe(() => {
this.startServerIfNotRunning();
});
this.platform.pause.subscribe(() => {
if (this.serverSubscription !== null) {
this.serverSubscription.unsubscribe();
this.serverUrl = null;
}
});
}
}
startServer() {
this.serverSubscription = this.httpd.startServer({
www_root: this.file.applicationStorageDirectory.replace('file://', '') + '/Library/files/',
port: this.serverPort,
localhost_only: true
}).subscribe((serverUrl) => {
this.serverUrl = serverUrl;
this.stopAndResumeListener();
});
}
startServerIfNotRunning() {
if (this.platformIsReady) {
this.httpd.getLocalPath().then((path) => {
if (path.length < 1) {
this.startServer();
}
});
}
}
getServerUrl() {
if (this.serverUrl !== null) {
return this.serverUrl;
} else { // if for any reason we don't get this URL
return `http://127.0.0.1:${this.serverPort}/`;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment