This question already has answers here:
Convert HTML to Plain Text in Swift
(8 answers)
Closed 3 years ago.
I am trying to decode html data to simple string but I get all html syntax along with
I am using alamofire get method
Link for html data
http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es
Any help will be appreciated
I have tried all codes and extension on stack overflow but unable to get proper results
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString).response { response in
if let data = response.data{
let str = data.html2AttributedString
print(str)
}
}
I get String in along with html syntax
I want this text
Te damos la bienvenida a La Orotava, el pueblo con mayor desnivel de
España. Abarca desde las playas del Rincón, a nivel del mar, hasta
los 3718 metros del pico Teide, el punto más alto de España, cuya
última erupción fue en 1798. Se cree que el nombre Orotava deriva de
la palabra Arautápala, con el que denominaban a este territorio los
antiguos aborígenes guanches. Tras la conquista, fue declarada Villa
por el rey Felipe IV en 1648. Te invitamos a recorrerlo a través de
dos rutas diferentes: La Orotava Secreta o Ruta Azul y La Orotava
Legendaria o Ruta Verde.Cada ruta dura aproximadamente una hora y
media a paso normal y sus contenidos son diferentes. Si dispones de
tiempo, te recomendamos que hagas las dos rutas por separado para
disfrutar de rincones, leyendas y secretos que La Orotava te ofrece. A
lo largo del recorrido encontrarás, incrustadas en el suelo, placas
circulares de metal dorado. Cada placa indica el número de pista en el
color de la ruta a la que pertenece. Cuando te encuentres frente a
estas placas, pulsa el número de pista correspondiente. Si no
dispones del tiempo suficiente, te recomendamos que elijas sólo una
ruta. Pregunta al personal de la Oficina Municipal de Turismo, te
atenderán encantados y te ayudarán a elegir una de ellas en función de
tus intereses. También tienes a tu disposición folletos y otros
materiales en la oficina para ayudarte en esta decisión. Ten en
cuenta que La Orotava está llena de calles pendientes con subidas y
bajadas muy pronunciadas. Si eliges la ruta de La Orotava Legendaria,
o Ruta Verde, te encontrarás un recorrido con menos desnivel. Por
otro lado, la Ruta de La Orotava Secreta o Ruta Azul ofrece a los más
aventureros vistas panorámicas únicas desde las mayores alturas a las
que llega la visita. Te recomendamos realizar las rutas en horario de
oficina para que tengas la oportunidad de encontrar abiertos el mayor
número de espacios posible. Las iglesias suelen estar abiertas en
horario de culto. Recuerda que tienes a tu disposición un botón de
pausa y otro de repetición de los últimos 10 segundos en el
reproductor, para hacerte más cómodo el recorrido. Cualquiera de las
dos rutas está llena de sorpresas y rincones maravillosos. Adelante,
pulsa la ruta de tu elección y adentrémonos juntos en este paseo por
La Orotava.
Your answer is here
extension String{
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
API Call
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString, method: .get, parameters: nil).responseJSON { response in
do {
if let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String:AnyObject]{
if let body = jsonDict["body"] as? String{
print(body.htmlToString) // Your output is Here
}
}
} catch _ {
print("Exception!")
}
}
Output:
You need to create NSAttributedString from HTML string.
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return NSAttributedString() }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return NSAttributedString()
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
Whenever you want to use HTML text:
textView.attributedText = htmlString.htmlToAttributedString
Use the Below Extension for Data & String
extension Data {
var html2AttributedString: NSAttributedString? {
do {
return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
print("error:", error)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
extension String {
var html2AttributedString: NSAttributedString? {
return Data(utf8).html2AttributedString
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
Implementation in your code should be Like this.
let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
Alamofire.request(urlString).response { response in
if let data = response.data{
let str:NSAttributedString = data.html2AttributedString //call the extension method here
print(str)
}
}
Related
I am trying to read some data from my MySql DB using a function (Node), the code bellow is what i had tryed so far.
/**
*
* main() será executado quando você chamar essa ação
*
* #param As ações do Cloud Functions aceitam um único parâmetro, que deve ser um objeto JSON.
*
* #return A saída dessa ação, que deve ser um objeto JSON.
*
*/
var sql = require('mysql');
var connection = sql.createConnection({
host: 'xxxxxxxxxxxxxxxxx',
user: 'ccccccccccccccc',
password: 'wwwwwwwwwwww',
database: 'dsssssssssssssss'
});
function main(params) {
try {
connection.connect();
var sql="SELECT * FROM db_a43aea_frenew.funcionarios where Owner = 208 AND CodigoVendedor = 20";
console.log("Olaaaaaaaa....");
connection.query(sql,function(err,result){
return{message:result};
//console.log(result);
})
//console.log(result);
//console.log(rows);
connection.end();
}
catch (e) {
return { message:"error ==> " + e};
//return{message:"FALSE"};
}
}
But it produced no results. And have no error also.
Can someone give some hint of where the problem is..
Thank you.
I'm trying to return a JSON with a nested list using Navigation properties but I keep getting null in the 'Usuario' collection here's the output.
[
{
"$id": "1",
"id": 1,
"encabezado": "Como llamar a un metodo en c#",
"cuerpo": "Estoy intentando llamar un metodo metodo() pero no puedo alguna sugerencia xD?",
"points": 0,
"Usuario": null,
"Respuestas": []
},
{
"$id": "2",
"id": 2,
"encabezado": "Como cambiar conection String",
"cuerpo": "Es posible cambiar el conection string en asp.net si ya esta creada?",
"points": 1,
"Usuario": null,
"Respuestas": []
}
]
here's my .edmx
And finally this is where I have the web api
namespace AskTecProject.Controllers
{
public class QuestionController : ApiController
{
[HttpGet]
public List<Pregunta> GetQuestions()
{
using (asktecdbEntities entities = new asktecdbEntities())
{
List<Pregunta> p = entities.Usuarios.Where(m => m.id.Equals(1)).SelectMany(m => m.Preguntas).ToList<Pregunta>();
return p;
}
}
}
}
I got his query from Getting a related collection but I'm still having trouble with this, I'll appreciate any help
You should use Eager Loading:
List<Pregunta> preguntas = entities.Usuarios
.Where(u => u.id.Equals(1))
.SelectMany(u => u.Preguntas)
.Include(p => p.Usuario) // here
.ToList<Pregunta>();
Side note - seems like all your Preguntas entities will have same Usuario entity with id = 1. Also you don't need to specify generic parameter for ToList method - parameter should be inferred.
I try clone my response json, but the id is the same..
I want to clone an item in my json to facilitate the addition of content.
The problem is following the same ID, then the answer is to update and no new item ..
the function:
$scope.cloneItem = function(id) {
$scope.itemtoclone = allDB.get({section: section, id: id}, function(){
$scope.itemnew = new allDB({section: section});
$scope.itemnew = angular.copy($scope.itemtoclone);
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}
and the response:
GET http://localhost:5000/posts/25 304 Not Modified 7ms
POST http://localhost:5000/25 201 Created 2ms
json object to clone:
{
"id": 25,
"title": "Willian busca protagonismo igual ao de Neymar: \"Sempre joguei assim\"",
"subtitle": "Com 94% de aproveitamento nos passes na estreia da Copa América, jogador tem chamado a
responsabilidade e dividido a missão de criar os lances com o camisa 10",
"slug": "brasil-post-1",
"published": true,
"originalDate": "2015-06-16T03:00:00.000Z",
"excerpt": "Com 94% de aproveitamento nos passes na estreia da Copa América",
"$promise": {},
"$resolved": true,
"cats": [
2,
3,
4,
5,
7
]
}
Resolved, It was not quite what I wanted, but I help!
$scope.cloneItem = function(id) {
$scope.getclone = allDB.get({section: section, id: id}, function(response){
console.log(response);
$scope.itemnew = new allDB({section: section});
$scope.itemnew.title = response.title;
$scope.itemnew.subtitle = response.subtitle;
$scope.itemnew.excerpt = response.excerpt;
$scope.itemnew.$save(function(){
$mdToast.show($mdToast.simple({position: 'top right'}).content('Clone criado!'));
});
});
}
Hi i encountered a problem on my production environement with Crystal Reports 13. My OS is Windows Server 2003 with IIS 6.
I explain:
Since many month, my production environement worked with Crystal Reports 10 but 1 month ago i install Crystal Reports 13. I precise the 2 version Cohabite and i change in the web.config versions of assembly. Since, i got 2 problems, the first is resolved, i increase the printjoblimit to 150. The other problem who was not resolved is an exception :
Une erreur interne a été détectée. Veuillez nous excuser pour le désagrément.
L'appel à la fonction Suiv_Click a levé l'exception suivante :
CrystalDecisions.CrystalReports.Engine.LoadSaveReportException: Chemin d'accès au fichier de rapport non valide. à
CrystalDecisions.CrystalReports.Engine.EngineExceptionUtils.DoThrowException(String
message, EngineExceptionErrorID id) à CrystalDecisions.CrystalReports.Engine.ExceptionThrower.ThrowEngineException(String
messageID, EngineExceptionErrorID id) à
CrystalDecisions.CrystalReports.Engine.ReportDocument.Load(String filename,
OpenReportMethod openMethod, Int16 parentJob) à
CrystalDecisions.CrystalReports.Engine.ReportDocument.EnsureLoadReport() à
CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSourceInternal(Object val,
Type type) à CrystalDecisions.CrystalReports.Engine.ReportDocument.SetDataSource(DataSet
dataSet) à WebOvins_DocumentCirculationv3.CreerEtat_DocCirculation(dsDocCirculation ds)
dans d:\Inetpub\wwwroot\Synel\WOC\WOC\DocumentCirculationv3.aspx.cs:ligne 1182 à
WebOvins_DocumentCirculationv3.Suiv_Click(Object sender, EventArgs e) dans
d:\Inetpub\wwwroot\Synel\WOC\WOC\DocumentCirculationv3.aspx.cs:ligne 1009
The exception occur beetween 12 or 16 o'clock when i print a report. Before no problem. I supposed is a problem of load. In the night something was flush?
Do you have an idea?
Sorry for my english.
Thanks
Here is my code.
private void CreerEtat_DocCirculation(dsDocCirculation ds)
{
//try
//{
// Variables utilisées pour la suppression dans le fichier aspx
objname = this.Session.SessionID;
objtype = "dir";
ReportDocument rd = new ReportDocument();
//if (Master.ElevageCours.TypeAdhesion != eTypeAdhesion.V1 && !Master.ElevageCours.SansInventaire)
if (false)
{
rd.Load(this.Request.PhysicalApplicationPath + "WOC\\Editions\\DocCirculation.rpt");
}
else
{
rd.Load(this.Request.PhysicalApplicationPath + "WOC\\Editions\\DocCirculationv3.rpt");
}
rd.SetDataSource(new dsDocCirculation());
// Remplissage des divers paramètres de l'édition
rd.DataDefinition.FormulaFields["AFFANI"].Text = "'0'"; // Suppression de la section liste des animaux
//if (Master.ElevageCours.TypeAdhesion != eTypeAdhesion.V1 && !Master.ElevageCours.SansInventaire)
if (false)
{
if (vuesDocumentCirculation.GetActiveView().Equals(vueChargement))
{
EditionDocCirculation.AffectationParametres(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
0,//txtNbOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbOvinsCharge.Text),
0,//txtNbCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbCaprinsCharge.Text),
0,
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
true);
}
else
{
EditionDocCirculation.AffectationParametres(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
0,//txtNbOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbOvinsDecharge.Text),
0,//txtNbCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbCaprinsDecharge.Text),
txtNbMortsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbMortsDecharge.Text),
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
false);
}
}
else
{
if (vuesDocumentCirculation.GetActiveView().Equals(vueChargement))
{
EditionDocCirculation.AffectationParametresV3(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
txtNbAgneauxOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxOvinsCharge.Text),
txtNbReproducteursOvinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursOvinsCharge.Text),
txtNbAgneauxCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxCaprinsCharge.Text),
txtNbReproducteursCaprinsCharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursCaprinsCharge.Text),
0,
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
true);
}
else
{
EditionDocCirculation.AffectationParametresV3(rd,
(DocCirculation)Session[sSession.DocumentCirculation],
Master.ElevageCours,
txtNbAgneauxOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxOvinsDecharge.Text),
txtNbReproducteursOvinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursOvinsDecharge.Text),
txtNbAgneauxCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbAgneauxCaprinsDecharge.Text),
txtNbReproducteursCaprinsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbReproducteursCaprinsDecharge.Text),
txtNbMortsDecharge.Text == "" ? 0 : Convert.ToInt32(txtNbMortsDecharge.Text),
BaseWOC,
Master.UtilisateurCours.EnDemo ? Coord_ARSOE : null,
false);
}
}
if (ds.dtListeBoucles.Count == 0)
rd.DataDefinition.FormulaFields["AFFBOUCLES"].Text = "'0'";
else
{
// Affichage de la liste des boucles
rd.DataDefinition.FormulaFields["AFFBOUCLES"].Text = "'1'";
rd.Subreports[0].SetDataSource(ds);
rd.Subreports[1].SetDataSource(ds);
}
// Affichage de l'aperçu
rd.Export(Editions.OptionsImpression(this.Request.PhysicalApplicationPath + "Editions\\" + objname + "\\DocCirculation.pdf"));
//}
//catch (Exception e)
//{
// String str = string.Empty;
// str = "L'appel à la fonction CreerEtat_DocCirculation a levé l'exception suivante : " + e.ToString();
// Exception ex = new Exception(str);
// Session["LastError"] = ex;
// ScriptManager.RegisterStartupScript(this, typeof(string), "ErrApplication", "window.open('/WOC/WOC/PopUp/ErreurInterne.aspx','Params','resizable=no,width=400,height=270');", true);
//}
}
Without seeing the code we cannot determine the reason for this exception. with this exception , a simple idea is that the location of the report too be created is not exist and unavailable or dont have permission
This is my code:
#include <mysql.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *server = "nope";
char *user = "nope";
char *password = "nope";
char *database = "nope";
unsigned int port = 0;
int cprint(char *text){//Imprime como encabezado el numero de productos sin stock sumado al argumento
MYSQL *conn;
MYSQL_RES *res;
my_ulonglong num;
conn = mysql_init(NULL);
/* Connect to database */
if (!mysql_real_connect(conn, server,
user, password, database, port, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
/* send SQL query */
if (mysql_query(conn, "SELECT id FROM productos WHERE stock <= 0")) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
res = mysql_store_result(conn);
num = mysql_num_rows(res);
printf("\n===============================\n\n");
if(num > 0){
printf("Productos sin stock: %llu\n",num);
}
else{
printf("No hay productos sin stock\n");
}
printf("\n===============================\n\n%s",text);
/*close connection */
mysql_free_result(res);
mysql_close(conn);
return 0;
}
char *remove_newline(char *s)
{
int len = strlen(s);
if (len > 0 && s[len-1] == '\n') // if there's a newline
s[len-1] = '\0'; // truncate the string
return s;
}
int newproduct(){
char *name = malloc(127*sizeof(char));//nombre del producto
char *desc = malloc(127*sizeof(char));//descripcion del producto
double price;//precio del producto
cprint("Agregar nuevo producto\n\n");
printf("Nombre del producto: ");
fgets(name, 127, stdin);
name = remove_newline(name);
printf("Descripcion: ");
fgets(desc, 127, stdin);
name = remove_newline(desc);
printf("Precio: ");
scanf("%e", &price);
MYSQL *conn;
conn = mysql_init(NULL);
printf("Mysql initiated\n");
if (!mysql_real_connect(conn, server,
user, password, database, port, NULL, 0)) {
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}
printf("connection established\n");
char rname[256];//string donde guardar el nombre con caracteres de escape
char rdesc[256];
printf("Vars declared\n");
mysql_real_escape_string(conn,rname,name,256);//se agregan los caracteres de escape
printf("name escaped\n");
mysql_real_escape_string(conn,rdesc,desc,256);
printf("desc escaped\n");
/*
char *query;//donde guardar el query
snprintf(query,1000,"INSERT INTO productos (nombre,descripcion,stock,precio) VALUES( %s,%s, 0, %e)",rname,rdesc,price);//query a enviar
if (mysql_query(conn, query)) {//enviar el query
fprintf(stderr, "%s\n", mysql_error(conn));
exit(1);
}*/
mysql_close(conn);
printf("Mysql closed\n");
return 0;
}
int main(){
printf("Sales Assistant Alpha v0.0\n");//Nombre y version del programa
unsigned int choice;//numero de eleccion del menu
char *err = NULL;//Error
while(1){//loop infinito
cprint("Menu Principal\n\n");//imprime el encabezado
printf("1-Agregar nuevo producto\n");
printf("2-Editar producto existente\n");
printf("3-Productos sin stock\n");
printf("4-Agregar pedido\n");
printf("5-Salir de la aplicacion\n\n");
if(err != NULL){//evalua si hubo un error y lo imprime
printf("%s\n",err);
err = NULL;
}
printf("Numero de eleccion: ");
scanf("%i",&choice);//pide eleccion
if (scanf("%*[^\n]") != EOF){//read and discard all non-newlines
scanf("%*c"); //then read and discard the newline
}
switch(choice){//evalua la eleccion y ejecuta la funcion correspondiente
case 1:
newproduct();
printf("returned\n");
break;
case 2:
break;
case 3:
break;
case 4:
break;
case 5:
exit(0);//termina el programa
break;
default:
err = "Eleccion no valida";//error
break;
}
}
return 0;
}
And the console execution:
Sales Assistant Alpha v0.0
===============================
Productos sin stock: 3
===============================
Menu Principal
1-Agregar nuevo producto
2-Editar producto existente
3-Productos sin stock
4-Agregar pedido
5-Salir de la aplicacion
Numero de eleccion: 1
===============================
Productos sin stock: 3
===============================
Agregar nuevo producto
Nombre del producto: a
Descripcion: a
Precio: 1
Mysql initiated
connection established
Vars declared
name escaped
desc escaped
Mysql closed
*** stack smashing detected ***: ./sales_assistant terminated
Aborted (core dumped)
------------------
(program exited with code: 134)
Press return to continue
i have this stack smashing thing that is unknown to me. Besides that i want to know how much memory i can safely allocate without getting bus error.
IMPORTANT:when i disable the mysql_real_escape_string functions the code works normally, so the problem is there, but i dont know what the problem is.
thanks, matt.
edited
Added the complete code and translated to english. Also changed the question because i got a new error. Added debugging code.
When you ask for a number with scanf("%i", &choice); (the result of which should be checked!), you leave the newline behind. When you read a line with fgets() in newproduct(), it reads the newline left behind.
Ultimately, if you're doing line-based inputs, use fgets() or readline() (from POSIX 2008) to read the line and sscanf() to parse the line.
your malloc() is wrong for a (char*)
should be:
char *name = malloc(127*sizeof(char));//nombre del producto
char *desc = malloc(127*sizeof(char));
The problem was indeed mysql_real_escape_string(). the thing was that the length argument must be the *from lenght instead of the *to lenght like i was doing. im very happy that i worked that thing out, i was getting really frustrated.