回答編集履歴

1

修正

2016/08/06 12:43

投稿

_Kentarou
_Kentarou

スコア8490

test CHANGED
@@ -5,3 +5,151 @@
5
5
  [NSURLSession経由でHTTP requestを投げるサンプルコード Swift版](http://qiita.com/nyamage/items/48d5ee30869daaf70f7f)
6
6
 
7
7
  [Alamofireならとってもシンプル!SwfitでiOSアプリを作るための基礎知識](https://www.webprofessional.jp/2016/06/3100/)
8
+
9
+
10
+
11
+ ---
12
+
13
+
14
+
15
+ `URLStringConvertible`の定義は以下の様になっています。
16
+
17
+
18
+
19
+ ```swift
20
+
21
+ public protocol URLStringConvertible {
22
+
23
+ var URLString: String { get }
24
+
25
+ }
26
+
27
+
28
+
29
+ extension String: URLStringConvertible {
30
+
31
+ public var URLString: String {
32
+
33
+ return self
34
+
35
+ }
36
+
37
+ }
38
+
39
+
40
+
41
+ extension NSURL: URLStringConvertible {
42
+
43
+ public var URLString: String {
44
+
45
+ return absoluteString
46
+
47
+ }
48
+
49
+ }
50
+
51
+
52
+
53
+ extension NSURLComponents: URLStringConvertible {
54
+
55
+ public var URLString: String {
56
+
57
+ return URL!.URLString
58
+
59
+ }
60
+
61
+ }
62
+
63
+
64
+
65
+ extension NSURLRequest: URLStringConvertible {
66
+
67
+ public var URLString: String {
68
+
69
+ return URL!.URLString
70
+
71
+ }
72
+
73
+ }
74
+
75
+ ```
76
+
77
+
78
+
79
+ `URLStringConvertible`に準拠しているクラスを渡すことができるということです。
80
+
81
+
82
+
83
+ 以下のサンプルは`String`、`NSURL`、`NSURLRequest`、`NSURLComponents`どれでも第2引数の`URLString`に渡す事ができます。
84
+
85
+
86
+
87
+ ```swift
88
+
89
+ import UIKit
90
+
91
+ import Alamofire
92
+
93
+
94
+
95
+ class ViewController: UIViewController {
96
+
97
+
98
+
99
+ override func viewDidLoad() {
100
+
101
+ super.viewDidLoad()
102
+
103
+
104
+
105
+ // String
106
+
107
+ let stringURL = "https://httpbin.org/get"
108
+
109
+
110
+
111
+ // NSURL
112
+
113
+ let nsURL = NSURL(string: "https://httpbin.org/get")!
114
+
115
+
116
+
117
+ // NSURLRequest
118
+
119
+ let nsURLRequest = NSURLRequest(URL: nsURL)
120
+
121
+
122
+
123
+ // NSURLComponents
124
+
125
+ let nsURLcomponents = NSURLComponents(string:"https://httpbin.org/get")!
126
+
127
+
128
+
129
+ Alamofire.request(.GET, nsURLcomponents, parameters: ["foo": "bar"])
130
+
131
+ .responseJSON { response in
132
+
133
+ print(response.request) // original URL request
134
+
135
+ print(response.response) // URL response
136
+
137
+ print(response.data) // server data
138
+
139
+ print(response.result) // result of response serialization
140
+
141
+
142
+
143
+ if let JSON = response.result.value {
144
+
145
+ print("JSON: \(JSON)")
146
+
147
+ }
148
+
149
+ }
150
+
151
+ }
152
+
153
+ }
154
+
155
+ ```