tutorial open example iphone objective-c uiwebview foundation

iphone - open - web view swift 4



¿Cómo obtener el título de una página HTML que se muestra en UIWebView? (6)

Aquí está la versión de Swift 4, basada en la respuesta here

func webViewDidFinishLoad(_ webView: UIWebView) { let theTitle = webView.stringByEvaluatingJavaScript(from: "document.title") }

Necesito extraer el contenido de la etiqueta del título de una página HTML que se muestra en un UIWebView. ¿Cuál es el medio más robusto de hacerlo?

Sé que puedo hacer:

- (void)webViewDidFinishLoad:(UIWebView *)webView{ NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"]; }

Sin embargo, eso solo funciona si javascript está habilitado.

Alternativamente, podría escanear el texto del código HTML para el título, pero parece un poco engorroso y podría resultar frágil si los autores de la página se volvieran extraños con su código. Si se trata de eso, ¿cuál es el mejor método para usar para procesar el texto html dentro de la API de iPhone?

Siento que he olvidado algo obvio. ¿Hay un método mejor que estas dos opciones?

Actualizar:

A continuación de la respuesta a esta pregunta: UIWebView: ¿Se puede deshabilitar Javascript? parece que no hay forma de desactivar Javascript en UIWebView. Por lo tanto, el método de JavaScript anterior siempre funcionará.


No tengo experiencia con las vistas web hasta ahora, pero creo que establece su título en el título de la página, así que un truco que sugiero es usar una categoría en la vista web y sobrescribir el setter para self.title para que agregue un mensaje a uno de ustedes objeta o modifica alguna propiedad para obtener el título.

¿Podrías intentar decirme si funciona?


Para aquellos que simplemente se desplazan hacia abajo para encontrar la respuesta:

- (void)webViewDidFinishLoad:(UIWebView *)webView{ NSString *theTitle=[webView stringByEvaluatingJavaScriptFromString:@"document.title"]; }

Esto siempre funcionará ya que no hay forma de desactivar Javascript en UIWebView.


Si Javascript Habilitado Usa esto: -

NSString *theTitle=[webViewstringByEvaluatingJavaScriptFromString:@"document.title"];

Si JavaScript está deshabilitado, usa esto: -

NSString * htmlCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.appcoda.com"] encoding:NSASCIIStringEncoding error:nil]; NSString * start = @"<title>"; NSRange range1 = [htmlCode rangeOfString:start]; NSString * end = @"</title>"; NSRange range2 = [htmlCode rangeOfString:end]; NSString * subString = [htmlCode substringWithRange:NSMakeRange(range1.location + 7, range2.location - range1.location - 7)]; NSLog(@"substring is %@",subString);

Usé +7 y -7 en NSMakeRange para eliminar la longitud de <title> es decir, 7


WKWebView tiene propiedad ''título'', solo hazlo así,

func webView(_ wv: WKWebView, didFinish navigation: WKNavigation!) { title = wv.title }

No creo que UIWebView sea ​​adecuado en este momento.


Editar: acabo de ver que encontraste la respuesta ... sheeeiiitttt

¡Literalmente aprendí esto! Para hacer esto, ni siquiera necesita que se muestre en UIWebView. (Pero a medida que lo usa, puede obtener la URL de la página actual)

De todos modos, aquí está el código y alguna explicación (débil):

//create a URL which for the site you want to get the info from.. just replace google with whatever you want NSURL *currentURL = [NSURL URLWithString:@"http://www.google.com"]; //for any exceptions/errors NSError *error; //converts the url html to a string NSString *htmlCode = [NSString stringWithContentsOfURL:currentURL encoding:NSASCIIStringEncoding error:&error];

Entonces tenemos el código HTML, ¿ahora cómo obtenemos el título? Bueno, en cada documento basado en html el título está señalado por Este es el título Probablemente lo más fácil es buscar esa cadena htmlCode para, y para, y subsergirla para que podamos obtener el material intermedio.

//so let''s create two strings that are our starting and ending signs NSString *startPoint = @"<title>"; NSString *endPoint = @"</title>"; //now in substringing in obj-c they''re mostly based off of ranges, so we need to make some ranges NSRange startRange = [htmlCode rangeOfString:startPoint]; NSRange endRange = [htmlCode rangeOfString:endPoint]; //so what this is doing is it is finding the location in the html code and turning it //into two ints: the location and the length of the string //once we have this, we can do the substringing! //so just for easiness, let''s make another string to have the title in NSString *docTitle = [htmlString substringWithRange:NSMakeRange(startRange.location + startRange.length, endRange.location)]; NSLog(@"%@", docTitle); //just to print it out and see it''s right

¡Y eso es realmente! Básicamente, para explicar todos los chanchullos sucediendo en el título del documento, si hiciéramos un rango simplemente diciendo NSMakeRange (startRange.location, endRange.location) obtendríamos el título Y el texto de startString (que es) porque la ubicación es por el primer personaje de la cadena. Entonces, para compensar eso, acabamos de agregar la longitud de la cadena

Ahora, tenga en cuenta que este código no está probado ... si hay algún problema, podría ser un error ortográfico, o que no agregué / agregué un puntero cuando no debía hacerlo.

Si el título es un poco raro y no del todo correcto, intente jugar con el NSMakeRange-- Me refiero a sumar / restar diferentes longitudes / ubicaciones de las cadenas --- cualquier cosa que parezca lógica.

Si tiene alguna pregunta o si tiene algún problema, no dude en preguntar. Esta es mi primera respuesta en este sitio web, lo siento mucho si está un poco desorganizada