Foros del Web » Creando para Internet » Flash y Actionscript »

Linkificar enlaces http importados desde un texto externo, en swf

Estas en el tema de Linkificar enlaces http importados desde un texto externo, en swf en el foro de Flash y Actionscript en Foros del Web. Hola, hace poco hice este fabuloso tutorial: http://www.republicofcode.com/tutorials/flash/twitter_widget/ Sirve para crear un feed de los tweets de cualquier usuario y mostrarlos en un timeline diseñado ...
  #1 (permalink)  
Antiguo 02/01/2012, 08:52
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Linkificar enlaces http importados desde un texto externo, en swf

Hola,
hace poco hice este fabuloso tutorial:
http://www.republicofcode.com/tutorials/flash/twitter_widget/

Sirve para crear un feed de los tweets de cualquier usuario y mostrarlos en un timeline diseñado en flash. Y asi cargarlos dinamicamente al ejecutar el swf.
No tuve ningun problema para finalizar el tutorial.

Resulta que mi nivel de actionscript es muy bajo, y al final vi que le faltaba algo muy importante. Resulta que el texto que se muestra en el swf no es linkable cuando hay un enlace..
Es decir, cuando el usuario al que le estamos haciendo un feed, twitea un enlace, en el swf aparece como texto plano http://la_direccion_que sea.com pero al hacer click encima no se abre ninguna ventana.

Estuve mirando en la red, y encontre un codigo especifico para este asunto, pero era javascript, y venia a ser algo asi:

Código:
String.prototype.linkify_tweet = function() {
    var tweet = this.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/g, function(url) { 
        var wrap = document.createElement('div');
        var anch = document.createElement('a');
        anch.href = url;
        anch.target = "_blank";
        anch.innerHTML = url;
        wrap.appendChild(anch);
        return wrap.innerHTML;
    });
    tweet = tweet.replace(/(^|\s)@(\w+)/g, '$1@<a href="http://www.twitter.com/$2" target="_blank">$2</a>');
    return tweet.replace(/(^|\s)#(\w+)/g, '$1#<a href="http://search.twitter.com/search?q=%23$2" target="_blank">$2</a>');
 };
sacado de http://snipplr.com/view/45124/

Claro que yo necesito este codigo en actionscript 3. Espero haberme explicado correctamente,
Realmente necesito ayuda. Muy agradecido de antemano.
Saludos
  #2 (permalink)  
Antiguo 02/01/2012, 11:00
Avatar de Bandit
Moderador
 
Fecha de Ingreso: julio-2003
Ubicación: Lima - Perú
Mensajes: 16.726
Antigüedad: 20 años, 8 meses
Puntos: 406
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Hola Swivel:
Para mostrar el texto externo utiliza éste código:
Código actionscript:
Ver original
  1. var external:URLRequest=new URLRequest("nombre.txt");
  2. var externalloader:URLLoader = new URLLoader();
  3. externalloader.load(external);
  4. externalloader.addEventListener(Event.COMPLETE, mostraTexto);
  5. function mostraTexto(event:Event):void {
  6.  miTexto.htmlText=event.target.data;
  7. }
Coloca un campo de texto dinámico con nombre de instancia: miTexto.
El archivo .txt edítalo con los tag del HTML
Ejemplo: <a href="http://www.google.com.pe">GOOGLE</a>

Espero haberte sido de ayuda.
__________________
Bandit.
Si no sabes estudia y si sabes enseña.
http://www.banditwebdesign.com/
  #3 (permalink)  
Antiguo 02/01/2012, 11:12
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Ese codigo parece muy bueno. Gracias.
El problema es que yo no puedo editar el texto externo. Es un xml que proviene de twitter:

http://twitter.com/statuses/user_timeline.xml?screen_name=nombre_de_usuario

Ademas, yo ya consigo cargar el texto sin problema. Ya realice el tutorial del twitter widget cuyo enlace a el mismo lo puse al principio de mi anterior post.

El unico problema es que cuando el usuario del twitter publica un enlace en su mensaje: el enlace no es clicable. Al clicar sobre el no se abre ninguna ventana.

Gracias Bandit, o tu no me has entendido a mi, o yo no te he entendido a ti.
  #4 (permalink)  
Antiguo 02/01/2012, 18:27
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Basicamente, lo que creo que necesito es una funcion que me lea el status de la cuenta de twitter, por ejemplo:
http://twitter.com/statuses/user_timeline.xml?screen_name=Swivel
, y que alla donde dice <status><text>... (que es el tweet) cuando se encuentre algo que empiece por "http://" que lo reemplace en la carga del texto dinamico por un enlace. El problema es q no conozco bien el codigo actionscript. Por eso agradeceria que hubiera alguien que me lo explicara o en el caso de q entienda de que estoy hablando me envie un tutorial o alguna respuesta ya explicada paso a paso.
Gracias
  #5 (permalink)  
Antiguo 03/01/2012, 06:47
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

A ver estoy seguro que esto se hace con la funcion: replace() pero no tengo mucha idea de la sintaxis. Solo quiero que recoja el patron de texto http://.... recogido desde el xml
y lo renderice cambiandolo por <a href="http://...>http://...</a>

este es mi codigo por quien le sea util para ayudarme:

import flash.events.Event;
import flash.net.URLLoader;

var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("http://twitter.com/statuses/user_timeline.xml?screen_name=Swivel"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);
function processXML(e:Event):void{
var myXML:XML = new XML(e.target.data);
trace(myXML.status[0].text);
tweet_1.text = myXML.status[0].text;
tweet_2.text = myXML.status[1].text;
tweet_3.text = myXML.status[2].text;
tweet_4.text = myXML.status[3].text;
tweet_5.text = myXML.status[4].text;
tweet_6.text = myXML.status[5].text;
tweet_7.text = myXML.status[6].text;
}
  #6 (permalink)  
Antiguo 03/01/2012, 11:26
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Voy a insistir una vez mas, para que alguien pueda ayudarme de una vez.
A ver, para quien entienda de actionscript:
así funciona la funcion replace:

Código Actionscript:
Ver original
  1. var str:String = "AS3 rocks!";
  2. var search:String = "AS3";
  3. var replace:String = "Actionscript 3";
  4.  
  5. function strReplace(str:String, search:String, replace:String):String {
  6.  return str.split(search).join(replace);
  7. }
  8.  
  9. trace(strReplace(str, search, replace)); //Outputs Actionscript 3 rocks!


El problema es que en mi caso, el String tengo que recogerlo, pongamos desde:

tweet_1.text = myXML.status[0].text;

tweet_1.text es el nombre de instancia (de una caja de texto dinamica) que indican que el tweet (myXML.status[0].text; debe cargarse alli.

Por ejemplo, intuitivamente, sin tener mucha idea, a mi se me ocurre que deberia hacerse asi:

Código Actionscript:
Ver original
  1. import flash.events.Event;
  2. import flash.net.URLLoader;
  3.  
  4. var myXMLLoader:URLLoader = new URLLoader();
  5. myXMLLoader.load(new URLRequest("http://twitter.com/statuses/user_timeline.xml?screen_name=Swivel"));
  6. myXMLLoader.addEventListener(Event.COMPLETE, processXML);
  7.  
  8. function processXML(e:Event):void{
  9. var myXML:XML = new XML(e.target.data);
  10. trace(myXML.status[0].text);
  11. tweet_1.text = myXML.status[0].text;
  12. var str:String = myXML.status[0].text;
  13. var search:String = "http://";
  14. var replace:String = "<a href='http://*'>http://*</a>";
  15. function strReplace(str:String, search:String, replace:String):String {
  16. return str.split(search).join(replace);
  17. }

Pero claro esta, no funciona, porque asi no esta bien.

Alguien puede echar una mano?? Realmente llevo buscando esto durante mucho rato. No existe ninguna ayuda en la red!
Gracias
  #7 (permalink)  
Antiguo 03/01/2012, 12:56
Avatar de ocesitaro  
Fecha de Ingreso: diciembre-2011
Ubicación: Carabayllo
Mensajes: 274
Antigüedad: 12 años, 3 meses
Puntos: 36
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

¿ y cuál es el problema de ennviar el elace desde el xml?
  #8 (permalink)  
Antiguo 03/01/2012, 16:23
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

pues que en el XML los enlaces aparecen en texto plano. Sin poderse clicar. Y no se puede cambiar. Es un XML servido desde URL: http://twitter.com/statuses/user_tim...en_name=Swivel

Yo querria tener los enlaces...(los necesito vaya) asi:

http://www.porejemplo.com

Necesito hacer el reemplazo con el codigo actionscript que sea necesario, o mas bien, añadirle la etiqueta de enlace <a href="etc...> cuando importe el codigo del xml al swf.

Pero no se hacerlo! Alguna ayuda? Gracias!

Última edición por Swivel; 03/01/2012 a las 16:40
  #9 (permalink)  
Antiguo 03/01/2012, 16:56
Avatar de Bandit
Moderador
 
Fecha de Ingreso: julio-2003
Ubicación: Lima - Perú
Mensajes: 16.726
Antigüedad: 20 años, 8 meses
Puntos: 406
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Si los enlaces te salen en texto plano es porque tú estás usando el nombre de instancia de la caja de texto en el código así: tweet_1.text, si quieres que parezca como un link deberías de esribirlo así: tweet_1.htmlText

Espero haberte sido de ayuda.
__________________
Bandit.
Si no sabes estudia y si sabes enseña.
http://www.banditwebdesign.com/
  #10 (permalink)  
Antiguo 03/01/2012, 18:04
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Mi problema todavia no esta arreglado, pero gracias Bandit!
Hubiera necesitado justo eso que me ofreces, despues de solucionar mi pequeño problema!

He entendido que gracias a .htmlText los tags <a href="http://www...> pasan a renderizarse como enlaces clicables.
Pero actualmente yo, no tengo tags <a href="...> en mi new URLRequest, sino enlaces asi tal cual: http://....(sin el <a href="...>):
http://twitter.com/statuses/user_tim...en_name=Swivel
si lo abres veras que los tweets que estoy publicando en este swf (los tweets tardan en cargarse unos segundos):
http://alexmolinarico.com/swf_projec...ter_Widget.swf
que he subido a mi pagina web como ejemplo para que lo veas, No son clicables.
Por eso necesito el codigo que lea los http://blabla.com y los reemplace en <a href="http://blabla.com">http://blabla.com</a>

Y eso sera todo lo que necesite, supongo!!
Gracias!

Última edición por Swivel; 03/01/2012 a las 20:01
  #11 (permalink)  
Antiguo 04/01/2012, 14:52
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

Bueno, como esto es importante... sigo buscando soluciones. Pero esta la cosa dificil.

He encontrado este package en un post titulado: "Twitter Tweet String Encode Entity Utility"
http://snipplr.com/view/50732/

Código as3:
Ver original
  1. package {
  2.     /**
  3.      * @author Ninjaparade
  4.      */
  5.     public class TwitterStringUtil
  6.     {
  7.         public static function encodeTwitterString(tweet : String) : String
  8.         {
  9.             var twitterHash : RegExp = /(\#[a-zA-Z0-9_%]*)/g;
  10.             var twitterUser : RegExp = /(\@[a-zA-Z0-9_%]+)/ig;
  11.             var twitterLink : RegExp = /(https?:\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((\/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?/g;
  12.             var str : String = tweet;
  13.             var arr : Object = str.match(twitterLink);
  14.  
  15.             if (arr != null)
  16.             {
  17.                 for each ( var s:String in arr ) {
  18.                     str = str.replace(s, encodeURL(s));
  19.                 }
  20.             }
  21.             arr = str.match(twitterHash);
  22.             if (arr != null)
  23.             {
  24.                 for each (var k : String in arr) {
  25.                     str = str.replace(k, replaceHashtoURL(k));
  26.                 }
  27.             }
  28.             arr = str.match(twitterUser);
  29.             if (arr != null)
  30.             {
  31.                 for each (var j : String in arr) {
  32.                     str = str.replace(j, replaceURL(j));
  33.                     // str = "<a href = \"http://www.twitter.com/" + j.substr(1, j.length) + "\" " + "target=\"_blank\">" + j + "</a>";
  34.                 }
  35.             }
  36.             return str;
  37.         }
  38.  
  39.         public static function searchTwitterHash(value : String) : String
  40.         {
  41.             var pattern : RegExp = /(\#[a-zA-Z0-9_%]*)/g;
  42.             var str : String = value;
  43.             var arr : Object = value.match(pattern);
  44.  
  45.             // if(arr != null) {
  46.             for each ( var s:String in arr ) {
  47.                 str = str.replace(s, replaceHashtoURL(s));
  48.                 // }
  49.             }
  50.             return str;
  51.         }
  52.  
  53.         public static function searchTwitterUser(value : String) : String
  54.         {
  55.             var pattern : RegExp = /(\@[a-zA-Z0-9_%]+)/ig;
  56.             var str : String = value;
  57.             var arr : Object = value.match(pattern);
  58.  
  59.             for each ( var s:String in arr ) {
  60.                 str = str.replace(s, replaceURL(s));
  61.             }
  62.             return str;
  63.         }
  64.  
  65.         public static function searchTwitterURL(value : String) : String
  66.         {
  67.             var pattern : RegExp = /(https?:\/\/)?(www\.)?([a-zA-Z0-9_%]*)\b\.[a-z]{2,4}(\.[a-z]{2})?((\/[a-zA-Z0-9_%]*)+)?(\.[a-z]*)?/g;
  68.             var str : String = value;
  69.             var arr : Object = value.match(pattern);
  70.  
  71.             if (arr != null)
  72.             {
  73.                 for each ( var s:String in arr ) {
  74.                     str = str.replace(s, encodeURL(s));
  75.                 }
  76.             }
  77.             return str;
  78.         }
  79.  
  80.         public static function replaceURL(value : String) : String
  81.         {
  82.             var str : String = "<a href = \"http://www.twitter.com/" + value.substr(1, value.length) + "\" " + "target=\"_blank\">" + value + "</a>";
  83.             return str;
  84.         }
  85.  
  86.         public static function replaceHashtoURL(value : String) : String
  87.         {
  88.             var str : String = "<a href = \"http://twitter.com/#search?q=%23" + value.substr(1, value.length) + "\" " + "target=\"_blank\">" + value + "</a>";
  89.             return str;
  90.         }
  91.  
  92.         public static function encodeURL(value : String) : String
  93.         {
  94.             var str : String = "<a href = " + "\"" + value + "\" " + "target=\"_blank\">" + value + "</a>";
  95.             return str;
  96.         }
  97.     }
  98. }


Al parecer sirve para lo que necesito. Pero no se usar los packages, y si mi codigo actual es:

Código as3:
Ver original
  1. import flash.events.Event;
  2. import flash.net.URLLoader;
  3.  
  4. var myXMLLoader:URLLoader = new URLLoader();
  5. myXMLLoader.load(new URLRequest("http://twitter.com/statuses/user_timeline.xml?screen_name=Swivel"));
  6. myXMLLoader.addEventListener(Event.COMPLETE, processXML);
  7.  
  8. function processXML(e:Event):void{
  9. var myXML:XML = new XML(e.target.data);
  10.  
  11. tweet_1.text = myXML.status[0].text;
  12. }

Como importaria ese package a mi codigo?
No conozco muy bien este lenguaje, pero si no estoy equivocado estoy a punto de sacar algo de todo esto.

Alguien puede decirme si este package me seria util? y como lo cargo? es decir, no conozco la sintaxis! Se que arriba del codigo tengo que poner:
Código as3:
Ver original
  1. import TwitterStringUtil;
Pero luego ya no se como usar esta clase ni en que parte utilizarla...

gracias gente por vuestra ayuda!!!

Última edición por Swivel; 04/01/2012 a las 16:37
  #12 (permalink)  
Antiguo 04/01/2012, 17:49
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

GENTE ya se pueden olvidar. Ya lo he solucionado!

Ah se me olvidaba, aqui teneis mi codigo final por si alguien esta tan perdido como yo lo estaba...


import flash.events.Event;
import flash.net.URLLoader;

var t:TwitterStringUtil; new TwitterStringUtil();
var myXMLLoader:URLLoader = new URLLoader();
myXMLLoader.load(new URLRequest("http://twitter.com/statuses/user_timeline.xml?screen_name=Swivel"));
myXMLLoader.addEventListener(Event.COMPLETE, processXML);

function processXML(e:Event):void{
var myXML:XML = new XML(e.target.data);
var pattern:RegExp = /[^"|^>](http:\/\/+[\S]*)/;
var str:String = myXML.status[0].text;
var newstr = str.replace(pattern, ' <font color="#04717D"><a href="$1">$1</a></font>');

tweet_1.htmlText = newstr;


De nada.............................................. .................................................. ..
  #13 (permalink)  
Antiguo 04/01/2012, 18:30
Avatar de ocesitaro  
Fecha de Ingreso: diciembre-2011
Ubicación: Carabayllo
Mensajes: 274
Antigüedad: 12 años, 3 meses
Puntos: 36
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

buena con las expresioens regulares, ubieses comenzado pro eso
  #14 (permalink)  
Antiguo 04/01/2012, 18:56
 
Fecha de Ingreso: febrero-2011
Mensajes: 48
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Linkificar enlaces http importados desde un texto externo, en swf

No conocia el nombre de estas expresiones, hasta que encontre la solución mientras buscaba como cargar los packages.
Por eso la linea:
var t:TwitterStringUtil; new TwitterStringUtil(); del anterior codigo sobra.
Thx.

Etiquetas: actionscript, enlaces, externo, flash, swf, https
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 18:22.