- (void)viewDidLoad { [super viewDidLoad]; NSString *urlString = @"https://free-api.heweather.com/v5/weather?city=北京市&key=a87a9fb94f824080a4f8c60106abeee4"; NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];//确保url字符串中没有非法字符 NSURL *url = [NSURL URLWithString:urlS]; NSLog(@"Scheme:%@",[url scheme]); NSLog(@"Host:%@",[url host]); NSLog(@"Port:%@",[url port]); NSLog(@"Path:%@",[url path]); NSLog(@"Relative path:%@",[url relativePath]); NSLog(@"path components as array%@",[url pathComponents]); NSLog(@"Paramter string:%@",[url parameterString]); NSLog(@"Query:%@",[url query]); NSLog(@"Fragment:%@",[url fragment]); }
输出:
Scheme:https Host:free-api.heweather.com Port:(null) Path:/v5/weather Relative path:/v5/weather path components as array( "/", v5, weather ) Paramter string:(null) Query:city=%E5%8C%97%E4%BA%AC%E5%B8%82&key=a87a9fb94f824080a4f8c60106abeee4 Fragment:(null)
<h6>
NSURL 也有一个类方法 +URLWithString:relativeToURL: 可以根据一个base URL地址和关联字符串来构造URL。这个方法的行为由于其对子目录的/符号的处理而变得非常混乱无序。
NSURL *baseURL = [NSURL URLWithString:@"http://example.com/v1/"]; [NSURL URLWithString:@"foo" relativeToURL:baseURL]; // http://example.com/v1/foo [NSURL URLWithString:@"foo?bar=baz" relativeToURL:baseURL]; // http://example.com/v1/foo?bar=baz [NSURL URLWithString:@"/foo" relativeToURL:baseURL]; // http://example.com/foo [NSURL URLWithString:@"foo/" relativeToURL:baseURL]; // http://example.com/v1/foo [NSURL URLWithString:@"/foo/" relativeToURL:baseURL]; // http://example.com/foo/ [NSURL URLWithString:@"http://example2.com/" relativeToURL:baseURL]; // http://example2.com/
之前做过一个项目,拼接图片的url,就使用了+URLWithString:relativeToURL: 方法