Detecting if the wifi is enabled in swift - asynchronous

In my app i have some NSURLConnection.sendAsynchronousRequest but because of that if the user has wifi disabled the app crashes.
Is there a way to detect if the wifi is disabled so i can do something like that:
if(wifi is enabled)
{
NSURLConnection.sendAsynchronousRequest
}

Found the answer in this blog post:
Step 1:
Add "SystemConfiguration" framework to your project
Step 2:
Add this function to your project:
func isConnectionAvailble()->Bool{
var rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com").takeRetainedValue()
var flags : SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(rechability, &flags) == 0
{
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}

And now for a Swift 2.0:
func isConnectionAvailble()->Bool{
let rechability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "www.apple.com")
var flags : SCNetworkReachabilityFlags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(rechability!, &flags) == false {
return false
}
let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection)
}

Related

how to import or require CSS file conditionally eg(According to IOS version)

checkVersion() {
if (typeof window !== 'undefined' && window && window.navigator && window.navigator !== undefined) {
let agent = window.navigator.userAgent, start = agent.indexOf("OS");
if ((agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && start > -1) {
return window.Number(agent.substr(start + 3, 3).replace("_", "."))
}
return 0;
}
},
const checkVersion = Common.checkVersion();
require("../assets/style.css");
require("../assets/style2.css");
require("../assets/sprite.css");
require("../assets/ondemandpagestyle.css");
require("../assets/newstyle.css");
require("../assets/landingpage.css");
if (checkVersion <= 14) {
require("../assets/styleIOSUpgrade.css");
}
Here u see I have require the last CSS file conditionally(according to IOS version) , here i have used CheckVersion function to detect the Ios version and according to it and i have require the different CSS file
checkVersion() {
if (typeof window !== 'undefined' && window && window.navigator && window.navigator !== undefined) {
let agent = window.navigator.userAgent, start = agent.indexOf("OS");
if ((agent.indexOf("iPhone") > -1 || agent.indexOf("iPad") > -1) && start > -1) {
return window.Number(agent.substr(start + 3, 3).replace("_", "."))
}
return 0;
}
},
const checkVersion = checkVersion();
require("../assets/style.css");
require("../assets/style2.css");
require("../assets/sprite.css");
require("../assets/ondemandpagestyle.css");
require("../assets/newstyle.css");
require("../assets/landingpage.css");
if (checkVersion <= 14) {
require("../assets/styleIOSUpgrade.css");
}
U can use above code to require CSS file conditionally

Multiple promises fulfilled and saved in NodeJS

I have this part of code that work but strangely the latest step of outputting the result doesn't work.. When i try to log the first element of array it returns undefined bacause the execution is asynchronous. I thought to build a series of nested callbacks but I think that is a bad practice. Is there any other way to makes it work without create nested promise callbacks?
CODE:
var ImgGalleyURL = [];
//CONTROLLO SE SONO STATE INSERITE IMMAGINI DA CARICARE E LE CARICO
if (postwp.postImgGallery1 != null && postwp.postImgGallery1 != "") {
msg.createMedia(postwp.postImgGallery1).then((imgURL)=>ImgGalleyURL.push(imgURL));
}
if (postwp.postImgGallery2 != null && postwp.postImgGallery2 != "") {
msg.createMedia(postwp.postImgGallery2).then((imgURL)=>ImgGalleyURL.push(imgURL));
}
if (postwp.postImgGallery3 != null && postwp.postImgGallery3 != "") {
msg.createMedia(postwp.postImgGallery3).then((imgURL)=>ImgGalleyURL.push(imgURL));
}
if (postwp.postImgGallery4 != null && postwp.postImgGallery4 != "") {
msg.createMedia(postwp.postImgGallery4).then((imgURL)=>ImgGalleyURL.push(imgURL));
}
if (postwp.postImgGallery5 != null && postwp.postImgGallery5 != "") {
msg.createMedia(postwp.postImgGallery5).then((imgURL)=>ImgGalleyURL.push(imgURL));
}
console.log(ImgGalleyURL[0] + "this is the first image loaded");
Thank you all
I think you're looking for Promise.race:
const promises = [];
for (let i=1; i<=5; i++) {
const propName = "postImgGallery" + i;
if (postwp[propName] != null && postwp[propName] != "") {
promises.push(msg.createMedia(postwp[propName]));
}
}
Promise.race(promises).then(firstUrl => {
console.log(firstUrl + "this is the first image loaded");
});
Promise.all(promises).then(imgGalleryURLs => {
console.log("All images ("+ imgGalleryURLs.join(", ") + ") loaded");
});
You were trying to log the first value of the array when none of the promises was fulfilled yet, so it was still empty.

Google Maps API complaining in IE11 about polyfill Array.from()

I'm trying to figure out an issue with Google Maps v3 and a polyfill we use for non-ES6 browsers (IE11 for example). The error we get is:
This site overrides Array.from() with an implementation that doesn't support iterables, which could cause Google Maps JavaScript API v3 to not work correctly.
The polyfill is: ( from https://vanillajstoolkit.com/polyfills/arrayfrom/ )
if (!Array.from) {
Array.from = (function () {
var toStr = Object.prototype.toString;
var isCallable = function (fn) {
return typeof fn === 'function' || toStr.call(fn) === '[object Function]';
};
var toInteger = function (value) {
var number = Number(value);
if (isNaN(number)) { return 0; }
if (number === 0 || !isFinite(number)) { return number; }
return (number > 0 ? 1 : -1) * Math.floor(Math.abs(number));
};
var maxSafeInteger = Math.pow(2, 53) - 1;
var toLength = function (value) {
var len = toInteger(value);
return Math.min(Math.max(len, 0), maxSafeInteger);
};
// The length property of the from method is 1.
return function from(arrayLike/*, mapFn, thisArg */) {
// 1. Let C be the this value.
var C = this;
// 2. Let items be ToObject(arrayLike).
var items = Object(arrayLike);
// 3. ReturnIfAbrupt(items).
if (arrayLike == null) {
throw new TypeError('Array.from requires an array-like object - not null or undefined');
}
// 4. If mapfn is undefined, then let mapping be false.
var mapFn = arguments.length > 1 ? arguments[1] : void undefined;
var T;
if (typeof mapFn !== 'undefined') {
// 5. else
// 5. a If IsCallable(mapfn) is false, throw a TypeError exception.
if (!isCallable(mapFn)) {
throw new TypeError('Array.from: when provided, the second argument must be a function');
}
// 5. b. If thisArg was supplied, let T be thisArg; else let T be undefined.
if (arguments.length > 2) {
T = arguments[2];
}
}
// 10. Let lenValue be Get(items, "length").
// 11. Let len be ToLength(lenValue).
var len = toLength(items.length);
// 13. If IsConstructor(C) is true, then
// 13. a. Let A be the result of calling the [[Construct]] internal method
// of C with an argument list containing the single item len.
// 14. a. Else, Let A be ArrayCreate(len).
var A = isCallable(C) ? Object(new C(len)) : new Array(len);
// 16. Let k be 0.
var k = 0;
// 17. Repeat, while k < len… (also steps a - h)
var kValue;
while (k < len) {
kValue = items[k];
if (mapFn) {
A[k] = typeof T === 'undefined' ? mapFn(kValue, k) : mapFn.call(T, kValue, k);
} else {
A[k] = kValue;
}
k += 1;
}
// 18. Let putStatus be Put(A, "length", len, true).
A.length = len;
// 20. Return A.
return A;
};
}());
}
This works fine on other pages - but for some reason Google Maps seems to have an issue with it!
Even more frustratingly, is that it then breaks one of my other plugins (a lazy load script), which works fine until the Google map stuff is loaded
Any ideas on what its moaning about, and how to fix it?
If you have IE11 or a VM, you can test it at: https://www.chambresdhotes.org/Detailed/1768.html (click on the map at the bottom of the page, and this will load the Google Map - but then you get this annoying error, and it breaks the lazyload scrolling after)
Thanks!

Vue.js - Update computed property after async computed property gets updated

I have a computed property (filteredSyms) that depends on the asynchronous computed property (allSynonyms). I am using async-computed plugin for this:
https://www.npmjs.com/package/vue-async-computed.
However, when the data gets updated the computed property doesn't wait until the result of the async property update. Therefore, I receive not up to date information. Then after the async property actually return new value computed property doesn't run update again.
How can I make it work the way that computer property waits until there is a result from the async computed property?
The code is below:
asyncComputed: {
async allSynonyms() {
let allSyns = await this.$axios.$post('/db/sym/synonyms', this.model.syms);
return allSyns;
}
},
computed: {
filteredSyms() {
let that = this;
let allSyn = this.allSynonyms;
let exactMatch = this.symsByRating.filter(
function (v) {
let isExactMatch = v.title.toLocaleLowerCase().indexOf(that.searchString.toLocaleLowerCase()) >= 0;
return !that.idsToFilter.includes(v.id) && isExactMatch
&& (!that.currentBodyPart || v.bodyParts.indexOf(that.currentBodyPart) >= 0)
&& that.hasMoreSubsyms(v)
&& (!allSyn || !that.containsObject(v, allSyn))
&& (v.sex == that.model.sex || v.sex == 'NA');
});
let partialList = [];
exactMatch.forEach(ex => partialList.push({n: 100, sym: ex}));
for (let sym of this.symsByRating ) {
let searchWords = this.searchString.toLocaleLowerCase().split(' ');
let symWords = sym.title.toLocaleLowerCase().split(' ');
let n = 0;
let isPartialMatch = false;
symLoop:for (let symWord of symWords) {
symWord = symWord.substring(0, symWord.length - 1);
for (let searchWord of searchWords) {
// don't count last letters of the words
searchWord = searchWord.substring(0, searchWord.length - 1);
if (searchWord.length > 2 && symWord.indexOf(searchWord) >= 0) {
n++;
isPartialMatch = true;
}
}
}
if (exactMatch.indexOf(sym) < 0 && isPartialMatch
&& (!this.currentBodyPart || sym.bodyParts.indexOf(this.currentBodyPart) >= 0)
&& this.hasMoreSubsyms(sym)
&& (!allSyn || !this.containsObject(sym, allSyn))
&& (sym.sex == that.model.sex || sym.sex == 'NA')) {
partialList.push({n: n, sym: sym});
}
}
partialList.sort(function(obj1, obj2) {
return obj2.n - obj1.n;
});
if (this.searchString && this.searchString != '') {
partialList = this.filterSynonyms(partialList);
}
let fs = partialList.map(ws => ws.sym);
console.dir(fs);
return fs;
}
}
A lot of stuff is going on the filtered method, but I guess the main point here that it is using this.allSynonyms to do the check but it is not updated at the time filteredSyms is executed.
Thanks for your suggestions!
(I haven't really tested this out, but it should work.)
vue-async-computed does provide the status in this.$asyncComputed.allSynonyms.success.
try adding this.$asyncComputed.allSynonyms.success as a dependencies to filteredSyms and it should update when success state change.

Can I connect to CouchDB from ASP Classic / Javascript running on Windows?

Cloudant offers a hosted CouchDB, with a free starter level allowing 6GB of IO per month.
Good for developers learning CouchDB.
Since CouchDB allows specification of the map/reduce functions in Javascript, it might make sense to connect to it via Javascript, running in Classic ASP.
Possible?
Yes, why not?
Cloudant is accessible via HTTP/REST. Nothing special there.
ASP Classic / Javascript can use MSXML2.ServerXMLHttp to send out requests, in much the same way that XMLHttpRequest can be used on client-side Javascript.
What would be nice is a Javascript library for CouchDB that does not assume it is running in a browser, nor in Node, since ASP Classic is neither of those. Here's a start:
https://gist.github.com/3016476
Example ASP code:
var creds = getCloudantCredentials("cloudantCreds.txt");
var couch = new CouchDB(couchUrl);
couch.connect(creds[0],creds[1]);
var r = couch.listDbs();
say("all dbs: " + JSON.stringify(r, null, 2));
r = couch.view('dbname', 'baseViews', 'bywords',
{ include_docs: false,
key: "whatever",
reduce:true} );
say("view: " + JSON.stringify(r, null, 2));
This is how you might create a set of views:
function createViews(dbName, viewSet) {
var r, doc,
empty = function(doc) {
if ( ! doc.observation || doc.observation === '') {
emit(null, doc);
}
},
bywordsMap = function(doc) {
var tokens, re1,
uniq = function(a) {
var o = {}, i = 0, L = a.length, r = [];
for (; i < L; i++) {
if (a[i] !== '' && a[i] !== ' ') {
o[a[i]] = a[i];
}
}
for (i in o) { r.push(o[i]); }
return r;
};
if ( doc.observation && doc.observation !== '') {
tokens = uniq(doc.observation.split(/( +)|\./));
if (tokens && tokens.length > 0) {
tokens.map(function(token) {
emit(token, 1);
});
}
}
};
viewSet = viewSet || 'baseViews';
try {
r = couch.deleteView(dbName, viewSet);
doc = { views: { empty: { map:stringRep(empty) },
bywords: { map:stringRep(bywordsMap)}}};
r = couch.createView(dbName, viewSet, doc);
}
catch (exc1) {
say ('createViews() failed: ' + JSON.stringify(exc1));
}
}
function stringRep(fn) {
return fn.toString()
.replace(/[\s\t]*\/\/.*$/gm, '') // comments
.replace(/\n */gm, ' ')
.replace(/\r */gm, ' ')
.replace(/\{ +/gm, '{')
.replace(/ +\}/gm, '}');
}

Resources