<code class="hljs objectivec"><span class="hljs-built_in">NSURL</span> *url = [<span class="hljs-built_in">NSURL</span> URLWithString: <span class="hljs-string">@"http://www.onevcat.com/2011/11/debug/;param?p=307#more-307"</span>]; <span class="hljs-built_in">NSLog</span>(@“Scheme: %@”, [url scheme]); <span class="hljs-built_in">NSLog</span>(@“Host: %@”, [url host]); <span class="hljs-built_in">NSLog</span>(@“Port: %@”, [url port]); <span class="hljs-built_in">NSLog</span>(@“Path: %@”, [url path]); <span class="hljs-built_in">NSLog</span>(@“Relative path: %@”, [url relativePath]); <span class="hljs-built_in">NSLog</span>(@“Path components as array: %@”, [url pathComponents]); <span class="hljs-built_in">NSLog</span>(@“Parameter string: %@”, [url parameterString]); <span class="hljs-built_in">NSLog</span>(@“Query: %@”, [url query]); <span class="hljs-built_in">NSLog</span>(@“Fragment: %@”, [url fragment]); </code>
將得到以下輸出:
沒什麼值得多說的~相當方便就能得到所要結果的方法~ 另外,在由NSString
生成NSURL
對象時,有可能會出現NSString
中包含百分號各類括號冒號等對於url來說的非法字符如果直接進行轉換的話將得到nil。在對於復雜url進行轉換前,可以先試試對待轉換的NSString發送 stringByAddingPercentEscapesUsingEncoding:
將其轉換為合法的url字符串(其實目的就是保證非法字符用UTF8編碼..) 比如這樣:
<code class="hljs objectivec"><span class="hljs-built_in">NSString</span> *fixedStr = [reqStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; </code>