LoginSignup
2
3

More than 5 years have passed since last update.

Swiftでurlからhost名抽出の際にはNSURLComponentsを使った方が良さ気

Posted at

元々はNSURLのhostメソッドを使っていたのですが、NSURLのhostメソッドは RFC 1808 に準拠しており、以下のようなURLではnilが返ってきてしまうようだ。

http://test.com?abc

なので、単純にhost名だけが欲しい場合は、NSURLComponentsのhostメソッドを使った方が安全だと思いました。

let url: String = "http://test.com?abc"
if let component: NSURLComponents = NSURLComponents(string: url) {
    print(component.host)  // Optional("test.com")
}
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3