// Create a storage reference from our app StorageReference storageRef = storage.getReferenceFromUrl("gs://"); // Get reference to the file StorageReference forestRef = storageRef.child("images/forest.jpg"); forestRef.getMetadata().addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(StorageMetadata storageMetadata) { // Metadata now contains the metadata for 'images/forest.jpg' } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Uh-oh, an error occurred! } });
Task task = forestRef.getMetadata(); task.addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(StorageMetadata storageMetadata) { // Metadata now contains the metadata for 'images/forest.jpg' } }); task.addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Uh-oh, an error occurred! } });
private FirebaseAuth auth = FirebaseAuth.getInstance(); private FirebaseAuth.AuthStateListener authStateListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { // Welcome! Or goodbye? } }; @Override protected void onStart() { super.onStart(); auth.addAuthStateListener(authStateListener); } @Override protected void onStop() { super.onStop(); auth.removeAuthStateListener(authStateListener); }
{"requests": [ {"repeatCell": { "range": { "sheetId": 0, "startRowIndex": 0, "endRowIndex": 1 }, "cell": { "userEnteredFormat": { "textFormat": { "bold": true } } }, "fields": "userEnteredFormat.textFormat.bold" }} ]}
SHEETS.spreadsheets().batchUpdate(spreadsheetId=SHEET_ID, body=requests).execute()
Indexable note = Indexables.noteDigitalDocumentBuilder() .setUrl("http://example.net/users/42/lists/23") .setName("Shopping list") .setText("steak, pasta, wine") .setImage("http://example.net/images/shopping.jpg") .build(); FirebaseAppIndex.getInstance().update(note);
swimming_game_end
score
num_stars
API_LEVEL
DEVICE_BRAND
DEVICE_BOARD
OutOfMemoryError
SwimmingObstacleDensity
DisableSwimmingGame
cartella /app/App_Resources/Android
cartella /app/App_Resources/iOS
package.json
"nativescript-angular": "1.2.0", "nativescript-camera": "^0.0.8", "nativescript-iqkeyboardmanager": "^1.0.1", "nativescript-plugin-firebase": "^3.8.4", "nativescript-theme-core": "^1.0.2",
piattaforme
tns run ios
tns run android.
tns livesync ios --watch
tns livesync android --watch
app/main.ts
// questo import dovrebbe essere il primo per caricare alcune impostazioni necessarie (come globals e reflect-metadata) import { platformNativeScriptDynamic } from "nativescript-angular/platform"; import { AppModule } from "./app.module"; import { BackendService } from "./services/backend.service"; import firebase = require("nativescript-plugin-firebase"); firebase.init({ //persist deve essere impostato su false, altrimenti i numeri non vengono restituiti durante livesync persist: false, storageBucket: 'gs://giftler-f48c4.appspot.com', onAuthStateChanged: (data: any) => { console.log(JSON.stringify(data)) if (data.loggedIn) { BackendService.token = data.user.uid; } else { BackendService.token = ""; } } }).then( function (instance) { console.log("firebase.init done"); }, function (error) { console.log("firebase.init error: " + error); } ); platformNativeScriptDynamic().bootstrapModule(AppModule);
app/login/login.component.ts
user@nativescript.org
onAuthStateChanged
onAuthStateChanged: (data: any) => { console.log(JSON.stringify(data)) if (data.loggedIn) { BackendService.token = data.user.uid; } else { BackendService.token = ""; } }
loggedIn
token
app/services/backend.service.ts
app/auth-guard.service.ts
export class AuthGuard implements CanActivate { constructor(private router: Router) { } canActivate() { if (BackendService.isLoggedIn()) { return true; } else { this.router.navigate(["/login"]); return false; } }
const listRoutes: Routes = [ { path: "", component: ListComponent, canActivate: [AuthGuard] }, ];
app/list/list.html
app/list/list.component.ts
public gifts$: Observable;
ngOnInit(){ this.gifts$ = this.firebaseService.getMyWishList(); }
getMyWishList(): Observable { return new Observable((observer: any) => { let path = 'Gifts'; let onValueEvent = (snapshot: any) => { this.ngZone.run(() => { let results = this.handleSnapshot(snapshot.value); console.log(JSON.stringify(results)) observer.next(results); }); }; firebase.addValueEventListener(onValueEvent, `/${path}`); }).share(); }
handleSnapshot
handleSnapshot(data: any) { //array vuoto, quindi riempi e filtra this._allItems = []; if (data) { for (let id in data) { let result = (Object).assign({id: id}, data[id]); if(BackendService.token === result.UID){ this._allItems.push(result); } } this.publishUpdates(); } return this._allItems; }
publishUpdates() { // qui we sort deve emettere un *nuovo* valore (immutabilità!) this._allItems.sort(function(a, b){ if(a.date < b.date) return -1; if(a.date > b.date) return 1; return 0; }) this.items.next([...this._allItems]); }
<Label class="gold card" textWrap="true" [text]="message$ | async"></Label>
message$
ngOnInit(){ this.message$ = this.firebaseService.getMyMessage(); }
(app/services/firebase.service.ts
getMyMessage(): Observable{ return new Observable((observer:any) => { firebase.getRemoteConfig({ developerMode: false, cacheExpirationSeconds: 300, properties: [{ key: "message", default: "Happy Holidays!" }] }).then( function (result) { console.log("Fetched at " + result.lastFetch + (result.throttled ? " (throttled)" : "")); for (let entry in result.properties) { observer.next(result.properties[entry]); } } ); }).share(); }
app/list-detail/list-detail.component.ts
ngOnInit() { camera.requestPermissions(); ... }
takePhoto() { let options = { width: 300, height: 300, keepAspectRatio: true, saveToGallery: true }; camera.takePicture(options) .then(imageAsset => { imageSource.fromAsset(imageAsset).then(res => { this.image = res; //salva l'immagine sorgente in un file, poi invia quel percorso file a firebase this.saveToFile(this.image); }) }).catch(function (err) { console.log("Error -> " + err.message); }); }
saveToFile(res){ let imgsrc = res; this.imagePath = this.utilsService.documentsPath(`photo-${Date.now()}.png`); imgsrc.saveToFile(this.imagePath, enums.ImageFormat.png); }
/Gifts
editGift(id: string){ if(this.image){ //carica il file, quindi salva tutto this.firebaseService.uploadFile(this.imagePath).then((uploadedFile: any) => { this.uploadedImageName = uploadedFile.name; //get downloadURL and store it as a full path; this.firebaseService.getDownloadUrl(this.uploadedImageName).then((downloadUrl: string) => { this.firebaseService.editGift(id,this.description,downloadUrl).then((result:any) => { alert(result) }, (error: any) => { alert(error); }); }) }, (error: any) => { alert('File upload error: ' + error); }); } else { //modifica solo la descrizione this.firebaseService.editDescription(id,this.description).then((result:any) => { alert(result) }, (error: any) => { alert(error); }); } }
uploadFile(localPath: string, file?: any): Promise { let filename = this.utils.getFilename(localPath); let remotePath = `${filename}`; return firebase.uploadFile({ remoteFullPath: remotePath, localFullPath: localPath, onProgress: function(status) { console.log("Uploaded fraction: " + status.fractionCompleted); console.log("Percentage complete: " + status.percentageCompleted); } }); } getDownloadUrl(remoteFilePath: string): Promise { return firebase.getDownloadUrl({ remoteFullPath: remoteFilePath}) .then( function (url:string) { return url; }, function (errorMessage:any) { console.log(errorMessage); }); } editGift(id:string, description: string, imagepath: string){ this.publishUpdates(); return firebase.update("/Gifts/"+id+"",{ description: description, imagepath: imagepath}) .then( function (result:any) { return 'You have successfully edited this gift!'; }, function (errorMessage:any) { console.log(errorMessage); }); }
https://cdn.ampproject.org
pub.com
pub-com.cdn.ampproject.org
https://[pub-com].cdn.ampproject.org
https://*.ampproject.org
https://ampbyexample-com.cdn.ampproject.org
function initialize() { macaddress.one('wlan0', function (err, mac) { mac_address = mac; if (mac === null) { console.log('exiting due to null mac Address'); process.exit(1); } firebase.initializeApp({ serviceAccount: '/node_app_slot/<service-account-key>.json', databaseURL: 'https://<project-id>.firebaseio.com/' }); var db = firebase.database(); ref_samples = db.ref('/samples'); locationSample(); }); }
function locationSample() { var t = new Date(); iwlist.scan('wlan0', function(err, networks) { if(err === null) { ref_samples.push({ mac: mac_address, t_usec: t.getTime(), t_locale_string: t.toLocaleString(), networks: networks, }); } else { console.log(err); } }); setTimeout(locationSample, 10000); }
private void GeolocateWifiSample(DataSnapshot sample, Firebase db_geolocations, Firebase db_errors) { // initalize the context and request GeoApiContext context = new GeoApiContext(new GaeRequestHandler()).setApiKey(""); GeolocationApiRequest request = GeolocationApi.newRequest(context) .ConsiderIp(false); // for every network that was reported in this sample... for (DataSnapshot wap : sample.child("networks").getChildren()) { // extract the network data from the database so it’s easier to work with String wapMac = wap.child("address").getValue(String.class); int wapSignalToNoise = wap.child("quality").getValue(int.class); int wapStrength = wap.child("signal").getValue(int.class); // include this network in our request request.AddWifiAccessPoint(new WifiAccessPoint.WifiAccessPointBuilder() .MacAddress(wapMac) .SignalStrength(wapStrength) .SignalToNoiseRatio(wapSignalToNoise) .createWifiAccessPoint()); } ... try { // call the api GeolocationResult result = request.CreatePayload().await(); ... // write results to the database and remove the original sample } catch (final NotFoundException e) { ... } catch (final Throwable e) { ... } }
ChildEventListener samplesListener = new ChildEventListener() { @Override public void onChildAdded(DataSnapshot dataSnapshot, String previousChildName) { // geolocate and write to new location GeolocateWifiSample(dataSnapshot, db_geolocations, db_errors); } ... }; db_samples.addChildEventListener(samplesListener);
function initMap() { // attach listeners firebase.database().ref('/visualization').on('child_added', function(data) { ... data.ref.on('child_added', function(vizData) { circles[vizData.key]= new CircleRoyale(map, vizData.val().lat, vizData.val().lng, vizData.val().accuracy, color); set_latest_position(data.key, vizData.val().lat, vizData.val().lng); }); data.ref.on('child_removed', function(data) { circles[data.key].removeFromMap(); }); }); // create the map map = new google.maps.Map(document.getElementById('map'), { center: get_next_device(), zoom: 20, scaleControl: true, }); ... }