SwiftUI FireStore - Get Field from Document and display as Text() - arrays

I'm very new to SwiftUI so bare with me - it's for a project.
I have stored user's details into my Firestore database which looks like this:
image of database
I want to take the name from the database and display it in a Text("Hello" [name])
I have been able to fetch the name from the database and append it into an array. This function is run when the 'Log in' button is clicked.
The code is as follows:
func getData(){
let docRef = db.collection(FStore.collectionName).document(userID)
docRef.getDocument { (document, error) in
if let document = document, document.exists {
if let fetchedName = document.get("name") as? String {
userArray.append(fetchedName)
print(userArray)
}
}
}
}
When printing userArray, the correct name does print.
However I am struggling to display the name outside of the console and on my Text UI field. When I attempt the code below, it gives me an index out of range error.
Text("Hello: \(userArray[0])")
Any help is appreciated / any other methods of retrieving field data from a specific document.

Thanks to #Steve M , it ended up being a kind of silly mistake.
He was right, the display was attempting to read the array before the array had even been populated.
As described in my comments, I called the getData() function then ran code to display the next screen. I wrapped the "display next screen code" in a DispatchQueue to delay the next screen being displayed
DispatchQueue.main.asyncAfter(deadline# .now() + 1){
nextView = true
}
This ran a 1-second delay before displaying the next screen and successfully displayed the name from the database.

Related

Create drop down menu from external JSON in Javascript

I am using an external JSON to retrieve the name of the volcano and put all names into a drop down menu to be selected and shown on my map. Currently, I have no errors on my webpage console but I am not getting any names inside the dropdown. I am very new to coding and I am blank on what is wrong. Any advice?
'''
//Call JSON for map latitude and longitude, showing volcaones locations
// with last eruption in a hover feature
var data = {};
d3.json("./Graphs/Vol_cleaned.json").then(function (data) {
console.log(data);
// Once we get a response, send the data.features object to the createFeatures function
makeMap(data);
makeDrop();
});
//MAKE DROP DOWN MENU TO SELECT VOLCANO NAME
function makeDrop(){
for (var i = 0; i < data.Volcano_Name; i++){
let name = data.Volcano_Name[i];
d3.select("#arr").append("option").text(name);
}
}
function optionChanged() {
makeMap(data);
}
function makeMap(data) {
'''
JSON
I have tried several ways to call the data, I don't think I will be able to describe them correctly being that I am new to the coding world. My current code in the picture provide is working with no errors but nothing is populated in the drop down.

How can I retrieve data within an array from an API call in Google script?

I'm pretty new, so bear with me.
I'm making a Google script that will let me call the TMDb API and get some information from a movie list I'm compiling for myself. I'm trying to get all the values to automatically fill by just using the TMDB ID.
After struggling, I found it was easiest to create a function for each column I want to fill (title, date, genre, poster url, etc.) and pass the input from the cell in the spreadsheet to be able to retrieve the info, then return the data to that cell.
I can't figure it out though, when it comes to the "genre" category, because it's in an array.
Here's my code that works for a different column:
function getPoster(input) {
var movieID = input
// Call the TMDB API for movie details
var response = UrlFetchApp.fetch("https://api.themoviedb.org/3/movie/" + movieID + "?api_key=<<mykey>>");
// Parse the JSON reply
var json = response.getContentText();
var data = JSON.parse(json);
return data["poster_path"];
}
Using the API data:
"poster_path":"/hXLScIERphkTsMGdfKKvF4p4SPB.jpg",
However, the "genre" category lists them as an array:
"genres":[{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}],
How can I write the return so that it sends a string with the shown genres "Action, Drama, Thriller" into the single corresponding cell (not spilling into adjacent cells), while also ignoring the "id"?
you need to create an array from the genre's name values.
use this snippet:
var genres = [{"id":28,"name":"Action"},{"id":18,"name":"Drama"},{"id":53,"name":"Thriller"}];
// Return "Action, Drama, Thriller" as a string into a single cell
return genres.map(function(genre){
return genre.name;
}).join(", ");
Sample output when printed:

Perform a task with all of the values in an array (Swift, Firebase)

My situation is that I am creating a social media app, and I have an array of all of the people that the user is following. It looks like this:
let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]
So, I want to perform a function using every userUid in the array to fetch their posts and display it onto a collectionView.
To give more context the function looks like this (the "userUid" is the element that I need to repeat with all of the userUid's using the array):
databaseRef.child("posts").child(userUid).observeSingleEvent(of: .value) { (snapshot) in
// all of the code to get the posts information into another array to display on the collection view.
}
Thanks a lot!
To do something with every element in an array you can always use forEach(_:). Try:
let followingArray:[String] = ["user1Uid", "user2Uid", "user3Uid", "user4Uid"]
for userID in followingArray {
databaseRef.child("posts").child(userID).observeSingleEvent(of: .value) { (snapshot) in
// all of the code to get the posts information into another array to display on the collection view.
}
}

ng2-smart-table display list of object

Is there a way to display a list of objects in a single table cell for ng2-smart-table? I have tried creating a renderComponent but I am getting an empty value. Another question is will the filtering and sorting still work for this?
As I understood , You have a object and you want to display that data in ng2-smart-table.
For that follow this step.
import { LocalDataSource } from 'ng2-smart-table';
source : any = LocalDataSource;
When you call API then you have to set that data in source.
this.apiService.POST({}, 'getProductList').subscribe((res) => {
console.log(res);
this.source = new LocalDataSource(res.data); // Set response as per your res.
});
As you can see I have also set one array and that array has objects of data and I have set in table.
I hope this may help you. :)

How to get selected image

I have a Word 2016 Add-in that creates images using graphviz and stores the corresponding dot code in the altdescription of the image.
I can select the image and load the dot code back to the editor in the add-in. But this only works in my current implementation for inlinePictures.
function getDataFromSelection() {
Word.run(function (context) {
var range = context.document.getSelection();
var paragraphs = range.paragraphs;
context.load(paragraphs);
return context.sync().then(function () {
var pictures = paragraphs.items[0].inlinePictures;
context.load(pictures);
return context.sync().then(function () {
var picture = pictures.items[0];
editor.getSession().getDocument().setValue(picture.altTextDescription);
});
});
})
}
How can I obtain the selected picture if it is free floating in the document?
The Goal of the add in is to create and edit already created graphs using dot. But the editing part is currently the problem.
great question. as you properly deduced the inlinePictures collection only includes, excuse the redundance, inlinePicture images. Floating images are not included in that collection, something we will add in future iterations of the API.
There is a workaround that I suggest you to do to check if there are floating images in the selection.
you can get and analyze the OOXML from the selection and find out of there are any floating images in the selection.
this code shows how to get the OOXML from the selection:
// Run a batch operation against the Word object model.
Word.run(function (context) {
// Queue a command to get the current selection and then
// create a proxy range object with the results.
var range = context.document.getSelection();
// Queue a commmand to get the OOXML of the current selection.
var ooxml = range.getOoxml();
// Synchronize the document state by executing the queued-up commands,
// and return a promise to indicate task completion.
return context.sync().then(function () {
console.log('The OOXML read from the document was: ' + ooxml.value);
});
}).catch(function (error) {
console.log('Error: ' + JSON.stringify(error));
if (error instanceof OfficeExtension.Error) {
console.log('Debug info: ' + JSON.stringify(error.debugInfo));
}
});
Once you have the OOXML you can actually get (with string search or XML editors) what's within in the of if look for something like this element, you will know there is a floating image there. you can also get the alt text and description as you can see. if so needed you can use that string replace the alt text properties you need and can write back the OOXML to update that floating image. its a bit painful but doable and hopefully we can ship the floating images collection soon! thanks and happy coding!!!
<w:drawing>
<wp:anchor allowOverlap="1" layoutInCell="1" locked="0" behindDoc="0" relativeHeight="251659264" simplePos="1" distR="114300" distL="114300" distB="0" distT="0">
<wp:simplePos y="3710305" x="1729105"/>
<wp:positionH relativeFrom="margin">
<wp:posOffset>1729105</wp:posOffset>
</wp:positionH>
<wp:positionV relativeFrom="margin">
<wp:posOffset>3710305</wp:posOffset>
</wp:positionV>
<wp:extent cx="2847975" cy="2133600"/>
<wp:effectExtent r="9525" b="0" t="0" l="0"/>
<wp:wrapSquare wrapText="bothSides"/>
<wp:docPr title="alt text sample" name="Picture 1" descr="alt test description!!" id="1"/>
<wp:cNvGraphicFramePr>
<a:graphicFrameLocks noChangeAspect="1" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"/>
</wp:cNvGraphicFramePr>
<a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main">
<a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<pic:nvPicPr>
<pic:cNvPr name="stratus2.jpg" id="1"/>
<pic:cNvPicPr/>
</pic:nvPicPr>
<pic:blipFill>
<a:blip r:embed="rId4">
<a:extLst>
<a:ext uri="{28A0092B-C50C-407E-A947-70E740481C1C}">
<a14:useLocalDpi val="0" xmlns:a14="http://schemas.microsoft.com/office/drawing/2010/main"/>
</a:ext>
</a:extLst>
</a:blip>
<a:stretch>
<a:fillRect/>
</a:stretch>
</pic:blipFill>
<pic:spPr>
<a:xfrm>
<a:off y="0" x="0"/>
<a:ext cx="2847975" cy="2133600"/>
</a:xfrm>
<a:prstGeom prst="rect">
<a:avLst/>
</a:prstGeom>
</pic:spPr>
</pic:pic>
</a:graphicData>
</a:graphic>
</wp:anchor>
</w:drawing>

Resources