Skip to content

Commit f39d76f

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

File tree

1 file changed

+22
-18
lines changed

1 file changed

+22
-18
lines changed

Examples/LocalDebugging/MyApp/MyApp/ContentView.swift

+22-18
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,12 @@ 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 { response = try await self.register() }
33+
catch { response = error.localizedDescription }
3334
isLoading = false
3435
}
3536
} label: {
@@ -45,13 +46,13 @@ struct ContentView: View {
4546
}
4647
}
4748
}
48-
.disabled(buttonDisabled || isLoading)
49-
.opacity(buttonDisabled ? 0.5 : 1)
49+
.disabled(inputIncomplete || isLoading)
50+
.opacity(inputIncomplete ? 0.5 : 1)
5051
Text(response)
5152
}.padding(100)
5253
}
5354

54-
func register() async -> String {
55+
func register() async throws -> String {
5556
guard let url = URL(string: "http://127.0.0.1:7000/invoke") else {
5657
fatalError("invalid url")
5758
}
@@ -63,21 +64,17 @@ struct ContentView: View {
6364
}
6465
request.httpBody = jsonRequest
6566

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

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)")
8074
}
75+
76+
let jsonResponse = try JSONDecoder().decode(Response.self, from: data)
77+
return jsonResponse.message
8178
}
8279
}
8380

@@ -86,3 +83,10 @@ struct ContentView_Previews: PreviewProvider {
8683
ContentView()
8784
}
8885
}
86+
87+
struct CommunicationError: Error, CustomStringConvertible {
88+
let reason: String
89+
var description: String {
90+
self.reason
91+
}
92+
}

0 commit comments

Comments
 (0)