@@ -25,7 +25,11 @@ struct ContentView: View {
25
25
TextField ( " Username " , text: $name)
26
26
SecureField ( " Password " , text: $password)
27
27
Button (
28
- action: self . register,
28
+ action: {
29
+ Task {
30
+ await self . register ( )
31
+ }
32
+ } ,
29
33
label: {
30
34
Text ( " Register " )
31
35
. padding ( )
@@ -38,8 +42,8 @@ struct ContentView: View {
38
42
} . padding ( 100 )
39
43
}
40
44
41
- func register( ) {
42
- guard let url = URL ( string: " http://localhost :7000/invoke " ) else {
45
+ func register( ) async {
46
+ guard let url = URL ( string: " http://127.0.0.1 :7000/invoke " ) else {
43
47
fatalError ( " invalid url " )
44
48
}
45
49
var request = URLRequest ( url: url)
@@ -50,27 +54,21 @@ struct ContentView: View {
50
54
}
51
55
request. httpBody = jsonRequest
52
56
53
- let task = URLSession . shared. dataTask ( with: request as URLRequest ) { data, response, error in
54
- do {
55
- if let error = error {
56
- throw CommunicationError ( reason: error. localizedDescription)
57
- }
58
- guard let httpResponse = response as? HTTPURLResponse else {
59
- throw CommunicationError ( reason: " invalid response, expected HTTPURLResponse " )
60
- }
61
- guard httpResponse. statusCode == 200 else {
62
- throw CommunicationError ( reason: " invalid response code: \( httpResponse. statusCode) " )
63
- }
64
- guard let data = data else {
65
- throw CommunicationError ( reason: " invald response, empty body " )
66
- }
67
- let response = try JSONDecoder ( ) . decode ( Response . self, from: data)
68
- self . setResponse ( response. message)
69
- } catch {
70
- self . setResponse ( " \( error) " )
57
+ do {
58
+ let ( data, response) = try await URLSession . shared. data ( for: request)
59
+
60
+ guard let httpResponse = response as? HTTPURLResponse else {
61
+ throw CommunicationError ( reason: " invalid response, expected HTTPURLResponse " )
62
+ }
63
+ guard httpResponse. statusCode == 200 else {
64
+ throw CommunicationError ( reason: " invalid response code: \( httpResponse. statusCode) " )
71
65
}
66
+ let jsonResponse = try JSONDecoder ( ) . decode ( Response . self, from: data)
67
+
68
+ self . response = jsonResponse. message
69
+ } catch {
70
+ self . response = error. localizedDescription
72
71
}
73
- task. resume ( )
74
72
}
75
73
76
74
func setResponse( _ text: String ) {
0 commit comments