Set the WebView content - objective-c

Am consuming a JSON rest service from the web. That JSON has a property called "content", wich is a HTML content, so the JSON file is something like:
[{
"id":"4205",
"title":"SomeTitle",
"author":"Homero Simpson",
"content":"<html><head></head><body>Había una vez un molinero cuya única herencia para sus tres hijos eran su molino, su <a href='biblioSonidos://soundID=67'>asno</a> y su <a href='biblioSonidos://soundID=69'>gato</a>. Pronto se hizo la repartición sin necesitar de un clérigo ni de un abogado, pues ya habían consumido todo el pobre patrimonio. Al mayor le tocó el molino, al segundo el asno, y al menor el gato que quedaba. El pobre joven amigo estaba bien inconforme por haber recibido tan poquito. 'Mis hermanos' dijo él, 'pueden hacer una bonita vida juntando sus bienes, pero por mi parte, después de haberme comido al gato, y hacer unas sandalias con su piel, entonces no me quedará más que morir de hambre.' El gato, que oyó todo eso, pero no lo tomaba así, le dijo en un tono firme y serio: 'No te preocupes tanto, mi buen amo. Si me das un bolso, y me tienes un par de botas para mí, con las que yo pueda atravesar lodos y zarzales, entonces verás que no eres tan pobre conmigo como te lo imaginas.'</body></html>"
}]
I need to create a WebView with the code in the "content" property.
So, my question is:
How can set the WebView content from this JSON property?
Is that possible?

Use JSONSerialization to convert the JSON file to a foundation object (which will be an NSDictionary). Then use loadHTMLString to load the value for the content key:
NSError *jsonError = nil;
id json = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:pathToTheJSONFile] options:0 error:&jsonError];
if (json) {
[webView loadHTMLString:[(NSDictionary *)json objectForKey:#"content"] baseURL:nil];
} else {
NSLog(#"Error loading JSON: %#", jsonError);
}
(Pass whatever's appropriate for baseURL instead of nil if you want relative links in the content to work.)

Related

Display a message between a date range in velocity language

I want to display a message between a date range in Velocity language. Like from 1/3/2023 to 23/3/2023. How can I do that.
I tried to put condition but it's not working.
#set($user = SpermissionChecker.getUser() if (Guser.female)
#set($genre = "Madame")
#else
#set($genre = "Monsieur")
#end
#get (fact-Suser.getExpandoBridge ().getAttribute("active_"))
if("$/act"=="RESILIE"}
Suite à la résiliation de votre contrat, l'acces
contenu est limité à 6 mois, nous vous conseillons de sauvegarder vos documer
#set ($timete dateUtil.getCurrentDate ("dd/MM/yyyy", Locale))
#end
#if($timet =="03/12/2022" && $timet =="10/12/2022")
Rapprochement des banques du Groupe Crédit du Nord et portail et votre application mobile Santé évoluent </span

GAS Spreadsheet script to create and open / download Drive PDF in Custom Dialog

Good morning, I have some scripts with which I save a PDF file in a specific folder and then send it by email. Everything works fine, even if my code is not optimized. Recently I put a previous query where they helped me how to create a Custom Dialog to show the link to download the PDF file, however when I click on the link I automatically get error 400 which makes it impossible for me to download that PDF. I still cannot determine what I am failing, besides that, I would like the PDF to be displayed in the Custom Dialog. The code:
function CrearPDF(){
var spreadsheet = SpreadsheetApp.getActive();
var nombreHoja = 'LP con Seguros';
var sheet = spreadsheet.getSheetByName(nombreHoja).activate();
var gid = sheet.getSheetId()
var fecha = Utilities.formatDate(new Date(), "GMT-5", "dd/MM/yyyy HH:mm:ss");//Captura de la fecha de acuerdo a la zona horaria
var dni = spreadsheet.getRange('\'LP con Seguros\'!B1').getValues();
var nrocuenta = spreadsheet.getRange('\'LP con Seguros\'!C6').getValues();
var correo = spreadsheet.getRange('\'LP con Seguros\'!K13').getValues();
var valRegisSimul=spreadsheet.getRange('\'LP con Seguros\'!P10').getValues();
var nombrePDF = valRegisSimul + " de LP DNI "+dni+" " +fecha+".pdf";
var ssID = spreadsheet.getId();
var url = "https://docs.google.com/spreadsheets/d/"+ssID+"/export"+
"?format=pdf&"+
"size=a4&"+
"portrait=true&"+
"scale=4&"+
//"top_margin=0.40&"+
//"bottom_margin=0.40&"+
//"left_margin=0.40&"+
//"right_margin=0.40&"+
"gridlines=false&"+
"printnotes=false&"+
//"pageorder=2&"+
"horizontal_alignment=CENTER&"+
"vertical_alignment=TOP&"+
"printtitle=false&"+
"sheetnames=false&"+
"fzr=false&"+
"fzc=false&"+
"attachment=false&"+
"gid=" + gid + "&"+
"r1=" + 0 + "&"+
"c1=" + 0 + "&"+
"r2=" + 62 + "&"+
"c2=" + 8;
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var response = UrlFetchApp.fetch(url, params).getBlob();
// Creamos un fichero con el Blob anterior y le cambiamos el nombre
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(url, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName(nombrePDF).getAs('application/pdf');
var folders = DriveApp.getRootFolder().getFolders(); // En esta variable se almacenan solo los carpetas del directorio raiz
var nombrecarpeta = "DNIs de LP y Simulaciones";
if(folders.hasNext() == false)//Para cuando no hay carpetas o folder aún en el Drive
{
var NewFolder = DriveApp.createFolder(nombrecarpeta);
NewFolder.createFile(pdf);
var file = NewFolder.createFile(pdf);
Logger.log(file.getDownloadUrl());
}
else //En el caso de que sí haya carpetas o folder en el Drive, los recorre hasta encontrar el nombre "nombrecarpeta" sino lo encuentra la creará y ahí guarda el archivo
{
while (folders.hasNext())
{
var folder = folders.next();
if(folder.getName() == nombrecarpeta)// en el caso de que exista una carpeta con el nombre terminamos la iteracion de las carpetas
{
var folderid = folder.getId();
var Transfolder = DriveApp.getFolderById(folderid);
Transfolder.createFile(pdf);
var file = Transfolder.createFile(pdf);
Logger.log(file.getDownloadUrl());
break;
}
else
{// Creamos la carpeta en el caso de que aún no exista y guardamos el archivo en la nueva carpeta
var NewFolder = DriveApp.createFolder(nombrecarpeta);
NewFolder.createFile(pdf);
var file = NewFolder.createFile(pdf);
Logger.log(file.getDownloadUrl());
break;
}
}
}
spreadsheet.setActiveSheet(spreadsheet.getSheetByName('LP con Seguros'), true);
var sheet = spreadsheet.getActiveSheet();
//Obtiene el nombre del archivo PDF recién creado, así como su contenido
var archivo = docurl.getBlob().getAs('application/pdf').getBytes(); // sin la opción getBytes obtendríamos un archivo sin contenido
var attach = {fileName:nombrePDF,content:archivo, mimeType:'application/pdf'};
var subject = valRegisSimul + ' de Crédito Efectivo DNI ' + dni + ' ' + fecha;
var html = '<body>' + '<strong>' + ' <p>Estimado(a)' + '</strong>' + '</p>' +
'<p>A continuación encontrará adjunto el archivo del plan de pagos de su Crédito Efectivo, recuerde siempre realizar los abonos al número de cuenta del préstamo.</p>' +
'<p style="text-align: left;">==> El número de cuenta del Crédito Efectivo a donde se deben hacer los abonos es: ' + '<strong>' + nrocuenta + '</strong>' + '</p>'
//Muestra un Popup preguntando si deseas enviar la transferencia por correo
SpreadsheetApp.getUi()
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Se completó el registro correctamente, ¿Desea enviar el plan de pagos al correo registrado: '+ correo + ' ?' + '\n\n' + 'Caso contrario, el archivo ' + nombrePDF + ' sólo se guardará en la carpeta ' + nombrecarpeta + ' de Drive', ui.ButtonSet.YES_NO);
// Si la respuesta es si, mandará el correo, de lo contrario termina el programa
if (response == ui.Button.YES)
{
GmailApp.sendEmail(correo, subject, "Cuerpo", {htmlBody:html, attachments:[attach]});
SpreadsheetApp.getUi().alert('Se envió correctamente el plan de pagos al correo '+ correo + '.' + '\n\n' + 'Mencione regreso por seguros y número de cuenta del Crédito efectivo');
}else
{
//Solo por referencia
Logger.log('El archivo '+ nombrePDF + ' quedó guardado en la carpeta ' + nombrecarpeta + ' de Drive');
};
var url = file.getDownloadUrl();
var html = 'Para descargar el PDF con la simulación de pagos, haz clic aquí';
var userInterface = HtmlService.createHtmlOutput(html);
var title = "Descargar PDF de Google Drive";
SpreadsheetApp.getUi().showModalDialog(userInterface, title);
}
Custom Dialog Error 400
Thanks in advance for the answers I will receive.
Thanks to #Adam Stevenson for the support, I corrected the code, however I still can't download the PDF, now I get a different error. Attachment screenshot.
Error after correcting the code
When you define html:
var html = 'Para descargar el PDF con la simulación de pagos, haz clic aquí';
…you did not break up the string with single quotes '. The double quote " does not end the string since you started it with single quotes. So + url + is just being read as part of the string. The corrected code:
var html = 'Para descargar el PDF con la simulación de pagos, haz clic aquí';

Threading App crash ntdll.dll every 2 or 3 days

I have an app running on a client machine, that uses threading, and is working fine, until the problem arrives.
The app crash every 2 or 3 days, and I have to restart it.
This is the error information I can get from the Event Viewer on the client machine.
Nombre de la aplicación con errores: SEM.CCQ.exe, versión: 1.15.0.0, marca de tiempo: 0x5b4488d8
Nombre del módulo con errores: ntdll.dll, versión: 6.1.7601.24094, marca de tiempo: 0x5abee643
Código de excepción: 0xc0000374
Desplazamiento de errores: 0x00000000000bf6b2
Id. del proceso con errores: 0x18700
Hora de inicio de la aplicación con errores: 0x01d41a9f081a1380
Ruta de acceso de la aplicación con errores: C:\SEM.CCQ\SEM.CCQ.exe
Ruta de acceso del módulo con errores: C:\Windows\SYSTEM32\ntdll.dll
Id. del informe: 1fa3b455-8919-11e8-9638-ec8eb5708651
It's crazy to try to locate the problem. Don't know how to start as the problem is not coming very often.
Is there any way to debug/catch this kind of problem to try to solve it?
Any help will be appreciated.

How can i display multiple views with ModuleFrontController in PS 1.6

With my Module Front Controller, i need to initialize it to display a form (formulaire.tpl) that the customer has to fill. Then the controller processes the data posted from the form using methods defines in my model (Formulaire.php) and then i would like to make it display another view (recapitulatif.tpl) that displays a reminder of data sent, an add to cart button for example or the possibility to fill the form in again.
As i would like to implement it the MVC way, i don't want to create a new php page to redirect my customer to but i would like to display somehow this second template after processing the data. Is there any way to do so with the controller? Here below, you can find my code, it doesn't work and it displays my first template and below my second..
class FormulaireModuleDefaultModuleFrontController extends ModuleFrontController
{
public $ssl = true;
private $done_traitement = false;
public function postProcess()
{
//On vérifie le bouton submit du formulaire
if(Tools::isSubmit('bouton'))
{
// On va commencer en premier par récupérer l'id customer avec la variable cookie
// et vérifier que la personnes est bien loggée
global $cookie;
if(!isset($cookie->id_customer))
{
$message='Aucun client loggé';
}
else
{
$errors=array();
$id_cart=$this->context->cart->id;
$customer=$cookie->id_customer;
//On récupère les valeurs du formulaire
$prix=Tools::getValue('resultat');
$titre='porte_test';
$desc='Largeur de passage de '.Tools::getValue('largeur_passage').' mm, hauteur de passage de '.Tools::getValue('hauteur_passage')
.' mm, hauteur de linteau de '.Tools::getValue('hauteur_linteau').' mm, ecoinçon gauche de '.Tools::getValue('ecoincon_gauche')
.' mm, ecoincon_droit de '.Tools::getValue('ecoincon_droit'). ' mm, motif en '.Tools::getValue('motif_porte').' et de couleur '
.Tools::getValue('couleur_porte');
//On va vérifier les champs obligatoires
//Les champs sont remplis, on va faire le traitement des données.
$idprod=Formulaire::creerProduct($titre,0,13,$prix,$desc, 'mod_100',$customer);
Formulaire::addProduitauPanier($idprod);
$this->done_traitement=true;
}
//On envoie le message si il existe:
if(isset($message))self::$smarty->assign('message',$message);
if(isset($errors))self::$smarty->assign('erreurs',$errors);
}
}
public function initContent()
{
parent::initContent();
if($this->done_traitement)
$this->display(__FILE__,'recapitulatif.tpl');
}
public function init(){
$this->display_column_left = false;
$this->display_column_right = false;
$this->page_name = 'Configurateur';
parent::init();
$this->setTemplate('formulaire.tpl');
}
}
Thanks in advance for your help !
EDIT :
Ok sorry for the question. It just took me 2 minutes to figure it out after posting the question. I only needed to change:
$this->display(__FILE__,'recapitulatif.tpl');
by :
$this->setTemplate('recapitulatif.tpl');
And now it works. Sorry for the inconvenience !

Objective c getting image from an html string

Hi i need some code to extract from a string like this
<div><img border="0" height="260" src="http://3.bp.blogspot.com/-uBx6ZoJ1DmY/TWPc1zD7aMI/AAAAAAAAANE/xeTZXtv4KYk/s320/ipad-light-peak.jpg" width="320" /></div><div>Come ormai tutti sappiamo, il nuovo iPad 2 è già in produzione da un po' di tempo, e, secondo recentissime voci, il nuovo iPad sarà equipaggiato con Light Peak. </div><div><br /></div><div>Light Peak è una tecnologia sviluppata da Intel che utilizza la fibra ottica per la trasmissione dei dati, portando così la velocità di trasferimento dei dati da PC/Mac a iPad ad una velocità altissima. </div><div><br /></div><div>Una connessione Light Peak su iPad 2 è secondo noi alquanto improbabile, dato che ormai il dock a 30 pin è quasi uno "standard" di comunicazione dei dispositivi Apple; inoltre se su iPad 2 sarà presente solo Light Peak, tutte le case che producono accessori per iPad dovranno riprogettare il loro prodotti.</div><div><br /></div><div>E voi, cosa ne pensate ? Fatecelo sapere utilizzando il form qui sotto.</div><div><img width="1" height="1" src="https://blogger.googleusercontent.com/tracker/5674629894325206938-2710160962386980433?l=eugystyle.blogspot.com" alt="" /></div>
The path of the image... in this eìcode for esample I need the "http://3.bp.blogspot.com/-uBx6ZoJ1DmY/TWPc1zD7aMI/AAAAAAAAANE/xeTZXtv4KYk/s320/ipad-light-peak.jpg"
thanks
if you are not going to parse the html then a simple substringFromIndex and substringToIndex will do the trick.
NSString *yourFullURL = fullHTMLString;
NSRange t = [yourFullURL rangeOfString:#"\"><img border=\"0\""];
//check range exists
if(t.location !=NSNotFound){
NSString *yourJPGURL = [yourFullURL substringToIndex:t.location];
}
// this will give you a new string up to the end of the URL//
// then repeat for the first part using a new NSRange for the beginning of
// the URL, use range.location+x (where x is the number of characters to add as NSRange
// returns the beginning of the string you search for.