How to use random text in UILocalNotifications? - arrays

I'm trying to make an app that will receive local notifications with random text. I used some code but it's not working well. It's coming only "006" or "005", and it won't change.
The code that I used is:
let myArray = ["000", "001", "002", "003", "004", "005", "006"]
let notification = UILocalNotification()
notification.alertBody = myArray[Int(arc4random_uniform(UInt32(myArray.count)))] // text that will be displayed in the notification
notification.fireDate = NSDate() // right now (when notification will be fired)
notification.soundName = UILocalNotificationDefaultSoundName // play default sound
notification.repeatInterval = NSCalendarUnit.NSHourCalendarUnit // this line defines the interval at which the notification will be repeated
UIApplication.sharedApplication().scheduleLocalNotification(notification)
Can you please show me where I made mistake ? Thanks.

What you are doing is correct. Maybe you haven't tried your code enough and had a long string of extreme values.

Related

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

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.

How to keep track of what question user is responding to?

Some questions my messenger chatbot is asking require textual input. In the button template I can set the payload so I know what exactly user chosen and handle it based on that. But with textual responses I need to filter if user answer is somehow related to "Change address, Billing, Returns, etc." For example:
bot-question: What is your new phone number?
user-answer: +123 123 12345
And now in the back-end I'm doing this:
if(user-answer in_array('billing keywords') {
// code
} elseif (user-answer in_array('delivery keywords')) {
// code
} elseif (user-answer in_array('payments keywords')) {
// code
} elseif (user-answer in_array('change-phone-number keywords')) {
// Finally got where I wanted 🎉😒
}
Isn't it possible to somehow add some tag to bot-question, so I would already know that the answer will be related to change-phone-number keywords? For example like this:
"template_type" => "text",
"text" => "What is your new phone number?",
"payload" => "changing_phone_number"
In the end it was impossible to get some postback from a normal text message, so what I did, I created additional columns:
expecting_billing_info
expecting_phone_number_update
etc.
And I set it to 0 by default, but when bot asks a question like:
Would you like to change your phone number?
I set it to 1 and when user types it in I do:
if (expecting_phone_number_update == 1) {
// 1. get the message
// 2. Check if it's correct phone number format
// 3. Reply based on 2. and update phone number
} elseif (expecting_billing_info == 1) {
// ...
}
This is not perfectly clean solution, but it does the work. Let's hope messenger will release this postback feature one day for normal messages as well! :)

Extracting Arrays as values in a JSON file using AngularJS

This is sort of a three part question. I have a JSON file. A few of the values in the JSON file are arrays. Keeping that in mind:
1) On any given page, I'd only want one set of values coming out of the JSON file. For example (as you'll see in code below) my JSON file is a list of attorneys. On any given bio page, I'd obviously only want one attorney's information. I'm currently, successfully, doing this by pulling back the entire JSON and then using ng-show. But this is causing some other issues that I'll explain in later points, so I'm wondering if there's something to put in the app.factory itself to only bring back the one set in the first place.
2) As mentioned, some of the values are arrays. This comes into play two ways in this situation. One of the ways is that there is an array of quotes about the attorney that I'll need to drop into a JS array so that my JS function can loop through them. Currently, I'm hardcoding the quotes for the one test attorney but I'm really trying to figure out how to make this dynamic. This is one reason I'm trying to figure out how to bring back only one attorney's information so I can then, somehow, say his quotes go into this array.
3) Another array value is a list of his specialty areas. I have another, hardcoded, JS object, associating the short terms with the display names. I realized though, that this has two issues.
a) The JS renders after the Angular, so I can't reference that JS in the Angular code
b) I have no way , anyway, to display the JS dynamically inside the Angular code.
My solution to that aspect was to create a second JSON file holding the area hash but besides being a little cumbersome, I'm also not sure how to dynamically display just the ones I want. e.g: If my attorney only specializes in securities and litigation, how would I tell the code to only display {{areas.securities}} and {{areas.litigation}}? So,I'm open to thoughts there as well.
Here is the current, relevant code. If you need more, just ask.
Thanks.
attorneys.json (irrelevant lines removed)
{"attorneys":
[
{
"id":1,
"name":"Bob Smith",
"quotes":
[
{
"id": 1,
"quote": "Wonderful guy!",
"person": "Dovie"
},
{
"id": 2,
"quote": "If ye be wanting a haggis like no other, Bob be yer man!",
"person": "Angus McLoed"
},
{
"id": 3,
"quote": "Wotta Hottie!",
"person": "Bob's wife"
}
],
"areas": ["altdispute", "litigation", "securities"],
}
]
}
...and the relevant current JS object that I'm not sure what to do with:
var practiceareas = {
altdispute: "Alternative Dispute Resolution",
businesscorp: "Businesses & Corporations",
estateplanning: "Estate Planning",
futures: "Futures & Derivatives",
litigation: "Litigation",
productliability: "Product Liability",
realestate: "Real Estate",
securities: "Securities"
}
script.js (relevant function)
var idno = 0;
/* This is what I want replaced by the Angular pull */
var quotelist = ["\"Wonderful guy!\"<br/>-Dovie", "\"If ye be wanting a haggis like no other, Bob be yer man!\"<br/>-Angus McLoed", "\"Hubba, Hubba! What a hottie!\"<br/>-Bob's wife"];
$("#bio_quotes").html(quotelist[0]);
function quoteflip(id, total){
var src1 = quotelist[idno];
$("#bio_quotes").fadeOut(500, function(){
$("#bio_quotes").html(src1).fadeIn(500);
});
idno = (id + 1) % total;
window.setTimeout(function(){quoteflip(idno, quotelist.length);}, 5000);
}
window.setTimeout(function(){quoteflip(idno, quotelist.length);}, 500);
By the way, as far as the quotes, I'm even happy to turn the JSON into a more condensed version by removing the id and consolidating the quote and author - making it an array of strings instead of mini-objects - if that makes it easier. In fact, it might be easier as far as the function anyway.
Can definitely filter things out at the service / factory using Array.filter. If you want to filter it server side, you have to have the code at server side that will do that.
Not sure what your backend store is but definitely doable.
Again, you can do this pretty easily with Array.map which let you pull specific values into a new Array. If you just want the name and quotes' quote and person name, you can definitely do this using Array .filter and .map and bind the new array to your viewmodel / scope.
Hmm.. again, I'd disagree, this look like the same issue with JavaScript array manipulation. You can definitely as part of the transformation in point 1 and 2, include this so it will transfer area to the long practice area names. The easiest way to show the relevant practice area is to map it to the long name during the transformation in the service layer.
//get matching attorney from the store by id
var matches = data.attorneys.filter(function(a) {
return a.id === id;
});
//If match found,
if (matches.length === 1) {
var result = matches[0];
//map the long name for practicing area
//use the matching attorney's area name as key
//and overwrite the result areas with the map
result.areas = result.areas.map(function(a) {
return practiceareas[a];
});
return result;
}
See this solution: http://embed.plnkr.co/xBPju7/preview
As for the fade in and fade out, I'll let you figure it out...

How to disable automatic syncing of a Store in ExtJS

ExtJS version is ext-4.0.7-gpl.
When syncing a Store, the server returns me the same object in JSON format, but populated with generated Ids, that I need to put into my store data. The identifiers are in enclosed entities, like this:
{
"id": 46,
"name": "Excel",
"typeExt": [{
"ext": "xls",
"id": "137",
"isMain": "false",
}, {
"ext": "xslx",
"id": "136",
"isMain": "false",
}]
}
So the ids 137 and 136 are generated on server-side.
I am trying to make it in a store's proxy (edit: Ajax type) (which itself could be wrong):
proxy.afterRequest = function(request) {
if (request.action === 'create' && request.records.length == 1) {
me.store.autoSync = false;
var created = Ext.JSON.decode(request.operation.response.responseText);
request.records[0].set('id', created.id);
request.records[0].set('typeExt', created.typeExt);
//request.records[0].modified = {};
//request.records[0].dirty = false;
me.store.autoSync = true;
}
if (request.action === 'update' && request.records.length == 1) {
var updated = Ext.JSON.decode(request.operation.response.responseText);
me.store.autoSync = false;
request.records[0].set('typeExt', updated.typeExt);
me.store.autoSync = true;
}
};
See the commented variants.
If I don't set autoSync to false, it gets looped infinitely.
If I don't clear those read-only fields modified and dirty, the modified records are included in the next syncronization request, if I edited another record, it sends an Array of records which breaks my server-side service.
If I clear dirty and modified like it is shown in the commented lines, the update operation works only once. I press Update button in RowEditing plugin dialog, but it never sends the needed request to the server for the second time.
In the latter case I guess I broke something by hand-editing the readonly fields, but I can not find what.
How do people usually handle issues liek this?
PS.
request.records[0].commit(true); || request.records[0].editing = false;
|| request.records[0].beginEdit();
Were tried with no seccess too.
While this won't do you much good on Ext 4.0.7, the suspendAutoSync and resumeAutoSync methods were added in Ext 4.1.0. Hopefully this will be useful to someone else.
I have this working for grids stores with Ext 4.0.7, but having similar issues with tree stores. All this with a direct proxy (and autosync true)
If you look at the code of Ext.data.Store::onCreateRecords, you'll see that the store records are replaced by those returned from the server, given the order is the same.
So, it is pretty straight-forward: just return from the server the same json/object sent to the create method, but with the id set and it should update them automatically on the store.
I know this is of not much help, but perhaps will give you some direction.
I think it would help if you mention:
the type of proxy you're using
the exact ext version
perhaps the code initiating the creation of the record

qx.ui.form.Spinner.setValue() question

I got a qx.ui.form.Spinner object and I am setting the initial value from an XML file. The value is unfortunately returned as a string, which leads to the following confusing error in Firebug:
Error in property value of class qx.ui.form.Spinner in method setValue with incoming value '3': Is invalid!
Running this sample in the Playground doesn't produce any error, but the spinner is not being set:
// Create a button
var button1 = new qx.ui.form.Button("First Button", "icon/22/apps/internet-web-browser.png");
// Document is the application root
var doc = this.getRoot();
var spinner = new qx.ui.form.Spinner(1, 1, 60);
doc.add(spinner);
// Add button to document at fixed coordinates
doc.add(button1,
{
left : 100,
top : 50
});
// Add an event listener
button1.addListener("execute", function(e) {
spinner.setValue("3");
});
So my questions are:
should the string value be working? So far it seemed to be seldom a problem when number are actually string.
should the Playground give an error?
To answer your questions:
No, the string value will not work. Try using the parseInt() function to convert the string into an integer.
Actually the Playground is giving a problem, but the exception is not handled by the Playground, Try adding a try .. catch and you will see the exact same errormessage you already know.
try {
spinner.setValue("3");
} catch (e) {
alert(e);
}
Thanks.
I already uses parseInt() to get it worked and I submitted a bug report: http://bugzilla.qooxdoo.org/show_bug.cgi?id=4457
I daresay the Playground should at least log the error in its "Log" window. You might want to consider opening a bug for this.

Resources