2011-05-11 75 views
4

嗨,大家好,我有一個數組,我得到的鏈接網站,如如何獲取域名?

http://clickfrom.buy.com/default.asp?adid\u003d17379&sURL\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fkimberly-clark-professional-kleenex-boutique-white-facial-tissue-2-ply%2Fq%2Floc%2F66357%2F211347223.html 

我要的是隻獲得例如主域名。 clickfrom.buy.com

主要網站地址。 如何實現這一目標?

回答

11

如果你有一個NSURL,你可以要求

[url host] 

這應與「clickfrom.buy.com」同上。

+0

請參閱下面的評論,我越來越Null.I我得到的數組中的值的鏈接 – Sabby 2011-05-11 10:15:44

3

你用就可以了:

NSString *myUrl = @"http://clickfrom.buy.com/default.asp?adid\\u003d17379&sURL\\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fkimberly-clark-professional-kleenex-boutique-white-facial-tissue-2-ply%2Fq%2Floc%2F66357%2F211347223.html"; 

NSURL *url = [NSURL URLWithString:myUrl]; 

NSLog(@"%@", [url host]); 

編輯

序列

\u003d 

在一個NSString被解釋爲普遍性,所以它必須被引用爲我們例如:

\\u003d 

而且會導致錯誤:\ u003d不是有效的通用字符。仍然存在解析問題,因爲反斜槓在URI語法中似乎是無效的字符。它必須被百分比逃脫。

看看RFC 2396/2.4.3。排除的US-ASCII字符

... 
Other characters are excluded because gateways and other transport 
agents are known to sometimes modify such characters, or they are 
used as delimiters. 

unwise  = "{" | "}" | "|" | "\" | "^" | "[" | "]" | "`" 

Data corresponding to excluded characters must be escaped in order to 
be properly represented within a URI. 

這樣做

NSString *myUrl = [@"http://clickfrom.buy.com/default.asp?adid\\u003d17379&sURL\\u003dhttp%3A%2F%2Fwww.buy.com%2Fprod%2Fkimberly-clark-professional-kleenex-boutique-white-facial-tissue-2-ply%2Fq%2Floc%2F66357%2F211347223.html" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

應該讓分析工​​作。

+0

我嘗試這樣做對接,這是顯示空,我用這種方式的NSLog(@「鏈接%@」 ,[itemArray valueForKey:@「link」]); \t NSString * linkstring = [NSString stringWithFormat:@「%@」,[itemArray valueForKey:@「link」]]; (@「string is%@」,linkstring);對於(int i = 0; i <[[itemArray valueForKey:@「link」] count]; i ++){ \t { \t NSURL * url = [NSURL URLWithString:linkstring]; (@「%@」,[url host]); \t} \t我有我從哪裏得到這個數組 – Sabby 2011-05-11 10:15:04

+0

看起來好像'\ u003d'打破瞭解析。 – 2011-05-11 10:26:26

+0

\ u003d是什麼意思,你能告訴我怎麼做,然後...... – Sabby 2011-05-11 12:03:06

0

使用rangeOfString方法NSString獲取您的域名的綁定,然後使用substringWithRange方法NSString提取域名文本。

- (NSString *)substringWithRange:(NSRange)aRange 
- (NSRange)rangeOfString:(NSString *)aString