teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

修正

2016/08/06 12:43

投稿

_Kentarou
_Kentarou

スコア8490

answer CHANGED
@@ -1,4 +1,78 @@
1
1
  内部的にはOS標準の通信クラス[NSURLSession](https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSURLSession_class/)を使用しているので、`NSURLSession`クラスを勉強するのが良いと思います。
2
2
 
3
3
  [NSURLSession経由でHTTP requestを投げるサンプルコード Swift版](http://qiita.com/nyamage/items/48d5ee30869daaf70f7f)
4
- [Alamofireならとってもシンプル!SwfitでiOSアプリを作るための基礎知識](https://www.webprofessional.jp/2016/06/3100/)
4
+ [Alamofireならとってもシンプル!SwfitでiOSアプリを作るための基礎知識](https://www.webprofessional.jp/2016/06/3100/)
5
+
6
+ ---
7
+
8
+ `URLStringConvertible`の定義は以下の様になっています。
9
+
10
+ ```swift
11
+ public protocol URLStringConvertible {
12
+ var URLString: String { get }
13
+ }
14
+
15
+ extension String: URLStringConvertible {
16
+ public var URLString: String {
17
+ return self
18
+ }
19
+ }
20
+
21
+ extension NSURL: URLStringConvertible {
22
+ public var URLString: String {
23
+ return absoluteString
24
+ }
25
+ }
26
+
27
+ extension NSURLComponents: URLStringConvertible {
28
+ public var URLString: String {
29
+ return URL!.URLString
30
+ }
31
+ }
32
+
33
+ extension NSURLRequest: URLStringConvertible {
34
+ public var URLString: String {
35
+ return URL!.URLString
36
+ }
37
+ }
38
+ ```
39
+
40
+ `URLStringConvertible`に準拠しているクラスを渡すことができるということです。
41
+
42
+ 以下のサンプルは`String`、`NSURL`、`NSURLRequest`、`NSURLComponents`どれでも第2引数の`URLString`に渡す事ができます。
43
+
44
+ ```swift
45
+ import UIKit
46
+ import Alamofire
47
+
48
+ class ViewController: UIViewController {
49
+
50
+ override func viewDidLoad() {
51
+ super.viewDidLoad()
52
+
53
+ // String
54
+ let stringURL = "https://httpbin.org/get"
55
+
56
+ // NSURL
57
+ let nsURL = NSURL(string: "https://httpbin.org/get")!
58
+
59
+ // NSURLRequest
60
+ let nsURLRequest = NSURLRequest(URL: nsURL)
61
+
62
+ // NSURLComponents
63
+ let nsURLcomponents = NSURLComponents(string:"https://httpbin.org/get")!
64
+
65
+ Alamofire.request(.GET, nsURLcomponents, parameters: ["foo": "bar"])
66
+ .responseJSON { response in
67
+ print(response.request) // original URL request
68
+ print(response.response) // URL response
69
+ print(response.data) // server data
70
+ print(response.result) // result of response serialization
71
+
72
+ if let JSON = response.result.value {
73
+ print("JSON: \(JSON)")
74
+ }
75
+ }
76
+ }
77
+ }
78
+ ```