Skip to content

Commit 3c8345f

Browse files
committed
Update ContentView.swift
1 parent 2b48c13 commit 3c8345f

File tree

1 file changed

+25
-18
lines changed

1 file changed

+25
-18
lines changed

Examples/LocalDebugging/MyApp/MyApp/ContentView.swift

Lines changed: 25 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,15 @@ struct ContentView: View {
2525
VStack(alignment: .leading, spacing: 20) {
2626
TextField("Username", text: $name)
2727
SecureField("Password", text: $password)
28-
let buttonDisabled = name.isEmpty || password.isEmpty
28+
let inputIncomplete = name.isEmpty || password.isEmpty
2929
Button {
3030
Task {
3131
isLoading = true
32-
response = await self.register()
32+
do {
33+
response = try await self.register()
34+
} catch {
35+
response = error.localizedDescription
36+
}
3337
isLoading = false
3438
}
3539
} label: {
@@ -45,13 +49,13 @@ struct ContentView: View {
4549
}
4650
}
4751
}
48-
.disabled(buttonDisabled || isLoading)
49-
.opacity(buttonDisabled ? 0.5 : 1)
52+
.disabled(inputIncomplete || isLoading)
53+
.opacity(inputIncomplete ? 0.5 : 1)
5054
Text(response)
5155
}.padding(100)
5256
}
5357

54-
func register() async -> String {
58+
func register() async throws -> String {
5559
guard let url = URL(string: "http://127.0.0.1:7000/invoke") else {
5660
fatalError("invalid url")
5761
}
@@ -63,21 +67,17 @@ struct ContentView: View {
6367
}
6468
request.httpBody = jsonRequest
6569

66-
do {
67-
let (data, response) = try await URLSession.shared.data(for: request)
70+
let (data, response) = try await URLSession.shared.data(for: request)
6871

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
72+
guard let httpResponse = response as? HTTPURLResponse else {
73+
throw CommunicationError(reason: "Invalid response, expected HTTPURLResponse.")
74+
}
75+
guard httpResponse.statusCode == 200 else {
76+
throw CommunicationError(reason: "Invalid response code: \(httpResponse.statusCode)")
8077
}
78+
79+
let jsonResponse = try JSONDecoder().decode(Response.self, from: data)
80+
return jsonResponse.message
8181
}
8282
}
8383

@@ -86,3 +86,10 @@ struct ContentView_Previews: PreviewProvider {
8686
ContentView()
8787
}
8888
}
89+
90+
struct CommunicationError: LocalizedError {
91+
let reason: String
92+
var errorDescription: String? {
93+
self.reason
94+
}
95+
}

0 commit comments

Comments
 (0)