2010-11-24 33 views

Respuesta

15

Mediante el uso de [url scheme] y [url host] así:

NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"]; 
NSLog(@"Base url: %@://%@", [url scheme], [url host]); 
// output is http://www.foo.com 
+3

esto no es universal ya que puede haber nombre de usuario y la contraseña también ... esto es mejor solución: “Otra manera que he encontrado para hacerlo es que NSURL contiene un método de la ruta. Puedo obtener el camino, y restarlo de la URL completa, y me queda lo que quiero ". – Renetik

+1

Sí restar el camino es más seguro en caso de que haya un puerto allí también – petenelson

-2
NSString *str = @"http://www.foo.com/bar/baragain"; 
NSArray *temp = [str componentsSeparatedByString: @".com"]; 
str = [NSString stringWithFormat: @"%@%@", [temp objectAtIndex:0], @".com"]; 
+0

¿Alguien puede decirme por favor mi voto negativo? respuesta – Swastik

+0

upvoted ............. – Bourne

+2

¿Por qué esto fue downvoted? Es simplemente incorrecto, imagine una url como 'http: // www.computer.com /' Btw, no era yo –

10
NSURL *url = [NSURL URLWithString:@"http://www.foo.com/bar/baragain"]; 
NSURL *root = [NSURL URLWithString:@"/" relativeToURL:url]; 
NSLog(@"root = '%@'", root.absoluteString); // root = 'http://www.foo.com/' 
+0

Perfecto! Gracias. – cmilhench

2

Se puede quitar el NSURL 's path de la cadena. Esto representa los números de puerto y otros datos que forman parte del sitio raíz.

NSString *urlString = @"http://www.foo.com/bar/baragain"; 
NSURL *rootUrl = [NSURL URLWithString:urlString]; 
NSString *rootUrlString = [urlString stringByReplacingOccurrencesOfString:rootUrl.path withString:@""]; 
+0

¡Brillante! Gracias. – PaulJ

+0

Uh oh. Pruebe con '@" http://www.foo.com/www.f "' – Hafthor

+0

@Hafthor, tiene razón, esto sigue siendo incorrecto. Siéntase libre de editar. –

Cuestiones relacionadas