@@ -25,11 +25,12 @@ struct ContentView: View {
25
25
VStack ( alignment: . leading, spacing: 20 ) {
26
26
TextField ( " Username " , text: $name)
27
27
SecureField ( " Password " , text: $password)
28
- let buttonDisabled = name. isEmpty || password. isEmpty
28
+ let inputIncomplete = name. isEmpty || password. isEmpty
29
29
Button {
30
30
Task {
31
31
isLoading = true
32
- response = await self . register ( )
32
+ do { response = try await self . register ( ) }
33
+ catch { response = error. localizedDescription }
33
34
isLoading = false
34
35
}
35
36
} label: {
@@ -45,13 +46,13 @@ struct ContentView: View {
45
46
}
46
47
}
47
48
}
48
- . disabled ( buttonDisabled || isLoading)
49
- . opacity ( buttonDisabled ? 0.5 : 1 )
49
+ . disabled ( inputIncomplete || isLoading)
50
+ . opacity ( inputIncomplete ? 0.5 : 1 )
50
51
Text ( response)
51
52
} . padding ( 100 )
52
53
}
53
54
54
- func register( ) async -> String {
55
+ func register( ) async throws -> String {
55
56
guard let url = URL ( string: " http://127.0.0.1:7000/invoke " ) else {
56
57
fatalError ( " invalid url " )
57
58
}
@@ -63,21 +64,17 @@ struct ContentView: View {
63
64
}
64
65
request. httpBody = jsonRequest
65
66
66
- do {
67
- let ( data, response) = try await URLSession . shared. data ( for: request)
67
+ let ( data, response) = try await URLSession . shared. data ( for: request)
68
68
69
- guard let httpResponse = response as? HTTPURLResponse else {
70
- return " invalid response, expected HTTPURLResponse "
71
- }
72
- guard httpResponse. statusCode == 200 else {
73
- return " invalid response code: \( httpResponse. statusCode) "
74
- }
75
-
76
- let jsonResponse = try JSONDecoder ( ) . decode ( Response . self, from: data)
77
- return jsonResponse. message
78
- } catch {
79
- return error. localizedDescription
69
+ guard let httpResponse = response as? HTTPURLResponse else {
70
+ throw CommunicationError ( reason: " invalid response, expected HTTPURLResponse " )
71
+ }
72
+ guard httpResponse. statusCode == 200 else {
73
+ throw CommunicationError ( reason: " invalid response code: \( httpResponse. statusCode) " )
80
74
}
75
+
76
+ let jsonResponse = try JSONDecoder ( ) . decode ( Response . self, from: data)
77
+ return jsonResponse. message
81
78
}
82
79
}
83
80
@@ -86,3 +83,10 @@ struct ContentView_Previews: PreviewProvider {
86
83
ContentView ( )
87
84
}
88
85
}
86
+
87
+ struct CommunicationError : Error , CustomStringConvertible {
88
+ let reason : String
89
+ var description : String {
90
+ self . reason
91
+ }
92
+ }
0 commit comments