旧 : このページは削除予定。ウェブ関連のストレージの管理は、chrome://settings/content/all から行う。
新 : こちらの chrome://settings/content/all で、ユーザーがウェブ関連のストレージを削除できる。
詳細な Cookie の管理は引き続き DevTools で実行可能
/app/App_Resources/Android folder
/app/App_Resources/iOS folder
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",
platforms
tns run ios
tns run android
tns livesync ios --watch
tns livesync android --watch
app/main.ts
// this import should be first in order to load some required settings (like globals and 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 should be set to false as otherwise numbers aren't returned during 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) { //empty array, then refill and filter 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() { // here, we sort must emit a *new* value (immutability!) 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; //save the source image to a file, then send that file path to 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){ //upload the file, then save all 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 { //just edit the description 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); }); }
var storageRef = firebase.storage.ref("folderName/file.jpg");
let storageRef = FIRStorage.reference().child("folderName/file.jpg")
StorageReference storageRef = FirebaseStorage.getInstance().reference().child("folderName/file.jpg");
var storageRef = firebase.storage.ref("folderName/file.jpg"); var fileUpload = document.getElementById("fileUpload"); fileUpload.on(‘change’, function(evt) { var firstFile = evt.target.file[0]; // get the first file uploaded var uploadTask = storageRef.put(firstFile); });
let storageRef = FIRStorage.reference().child("folderName/file.jpg"); let localFile: NSURL = // get a file; // Upload the file to the path "folderName/file.jpg" let uploadTask = storageRef.putFile(localFile, metadata: nil)
StorageReference storageRef = FirebaseStorage.getInstance().reference().child("folderName/file.jpg"); Uri file = Uri.fromFile(new File("path/to/folderName/file.jpg")); UploadTask uploadTask = storageRef.putFile(file);
<input type="file" />
UploadTask
DownloadTasks
var storageRef = firebase.storage.ref("folderName/file.jpg"); var fileUpload = document.getElementById("fileUpload"); fileUpload.on(‘change’, function(evt) { var firstFile = evt.target.file[0]; // get the first file uploaded var uploadTask = storageRef.put(firstFile); uploadTask.on(‘state_changed’, function progress(snapshot) { console.log(snapshot.totalBytesTransferred); // progress of upload }); });
let storageRef = FIRStorage.reference().child("folderName/file.jpg"); let localFile: NSURL = // get a file; // Upload the file to the path "folderName/file.jpg" let uploadTask = storageRef.putFile(localFile, metadata: nil) let observer = uploadTask.observeStatus(.Progress) { snapshot in print(snapshot.progress) // NSProgress object }
StorageReference storageRef = FirebaseStorage.getInstance().reference().child("folderName/file.jpg"); Uri file = Uri.fromFile(new File("path/to/images/file.jpg")); UploadTask uploadTask = storageRef.putFile(file); uploadTask.addOnProgressListener(new OnProgressListener() { @Override public void onProgress(UploadTask.TaskSnapshot snapshot) { System.out.println(snapshot.getBytesTransferred().toString()); } });
var storageRef = firebase.storage.ref("folderName/file.jpg"); storageRef.getDownloadURL().then(function(url) { console.log(url); });
let storageRef = FIRStorage.reference().child("folderName/file.jpg"); storageRef.downloadURLWithCompletion { (URL, error) -> Void in if (error != nil) { // Handle any errors } else { // Get the download URL for 'images/stars.jpg' } }
StorageReference storageRef = FirebaseStorage.getInstance().reference().child("folderName/file.jpg"); storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener() { @Override public void onSuccess(Uri uri) { // Got the download URL for 'users/me/profile.png' } }).addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception exception) { // Handle any errors } });
// Only a user can upload their profile picture, but anyone can view it service firebase.storage { match /b//o { match /users/{userId}/profilePicture.png { allow read; allow write: if request.auth.uid == userId; } } }