@@ -10,36 +10,63 @@ import Foundation
10
10
let client = OtoClient ( withEndpoint: " http://localhost:8080/oto " )
11
11
let service = MyService ( withClient: client)
12
12
13
- let resp = service. doSomething ( request : DoSomethingRequest (
13
+ service. doSomething ( withRequest : DoSomethingRequest (
14
14
name: " Mat "
15
- ) )
16
- print ( resp. greeting)
15
+ ) ) { ( response, err) -> ( ) in
16
+ print ( " done " )
17
+ }
17
18
18
19
class OtoClient {
19
20
var endpoint : String
20
21
init ( withEndpoint url: String ) {
21
22
self . endpoint = url
22
23
}
23
-
24
24
}
25
25
26
26
class MyService {
27
27
var client : OtoClient
28
28
init ( withClient client: OtoClient ) {
29
29
self . client = client
30
30
}
31
- func doSomething( request: DoSomethingRequest ) -> DoSomethingResponse {
32
- let resp = DoSomethingResponse (
33
- greeting: " Hi \( request. name) "
34
- )
35
- return resp
31
+ func doSomething( withRequest doSomethingRequest: DoSomethingRequest , completion: ( _ response: DoSomethingResponse ? , _ error: Error ? ) -> ( ) ) {
32
+ //var request = URLRequest(url: URL(string: "\(self.client.endpoint)/MyService/MyMethod")!)
33
+ // https://jsonplaceholder.typicode.com/todos/1
34
+ var request = URLRequest ( url: URL ( string: " https://jsonplaceholder.typicode.com/todos/1 " ) !)
35
+
36
+ request. httpMethod = " POST "
37
+ request. addValue ( " application/json; charset=utf-8 " , forHTTPHeaderField: " Content-Type " )
38
+ request. addValue ( " application/json; charset=utf-8 " , forHTTPHeaderField: " Accept " )
39
+ var jsonData : Data
40
+ do {
41
+ jsonData = try JSONEncoder ( ) . encode ( doSomethingRequest)
42
+ } catch let jsonEncodeErr {
43
+ print ( " TODO: handle JSON encode error: \( jsonEncodeErr) " )
44
+ return
45
+ }
46
+ request. httpBody = jsonData
47
+ let session = URLSession ( configuration: URLSessionConfiguration . default)
48
+ let task = session. dataTask ( with: request) { ( data, response, error) in
49
+ if let err = error {
50
+ print ( " TODO: handle response error: \( err) " )
51
+ return
52
+ }
53
+ var doSomethingResponse : DoSomethingResponse
54
+ do {
55
+ doSomethingResponse = try JSONDecoder ( ) . decode ( DoSomethingResponse . self, from: data!)
56
+ } catch let err {
57
+ print ( " TODO: handle JSON decode error: \( err) " )
58
+ return
59
+ }
60
+ print ( " \( doSomethingResponse) " )
61
+ }
62
+ task. resume ( )
36
63
}
37
64
}
38
65
39
- struct DoSomethingRequest {
66
+ struct DoSomethingRequest : Encodable {
40
67
var name : String = " "
41
68
}
42
69
43
- struct DoSomethingResponse {
70
+ struct DoSomethingResponse : Decodable {
44
71
var greeting : String = " "
45
72
}
0 commit comments