I would like an experieced coder to just go over my HTTP “go to” code for implementing MySQL data services via PHP web services (LAMP).
Firebase just lack INNER JOIN
I have created an “View” that works, and will send and receive JSON to a server, and then decodes it for use in a dummy test list view, however I want someone with experience to just check my guard statements, check my returns, and debug it so that the code is as safe as it can be.
We can assume nil responses via JSON, and we can assume that my table_ fields may be null.
The completed “document” will be my go to for MySQL web services implementation
//
// ContentView.swift
// MySQL-WebServices-Example
//
// Created by Alan Trundle on 09/02/2022.
//
import SwiftUI
// An Array of results:
struct arrayOfResults: Codable, Hashable {
var results: [Result]
}
// Array of Items.
struct Result: Codable, Hashable{
var table_id: Int
var table_firstname: String
var table_surname: String
}
// Example JSON with "results" key
let json = """
{
"results":[
{
"table_id": 1,
"table_firstname": "Thomas",
"table_surname": "Alwdry"
},
{
"table_id": 2,
"table_firstname": "James",
"table_surname": "Alwdry"
},
{
"table_id": 3,
"table_firstname": "Gordon",
"table_surname": "Alwdry"
}
]
}
""".data(using: .utf8)!
// End of set up
struct ContentView: View {
@State var results = [Result]()
var body: some View {
NavigationView() {
List {
Section(header: Text("Name")) {
ForEach(results, id: \.self) { result in
VStack(alignment: .leading) {
HStack() {
Image(systemName: "person.fill")
.foregroundColor(.blue)
Text(result.table_firstname)
.font(.system (size: 15))
.foregroundColor(.red)
Text(result.table_surname)
.font(.system (size: 15))
.foregroundColor(.red)
}
}
}
}
}
.navigationTitle("HTTP Demo")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
Button(action: {
Task {
results = await uploadData()!
}
}) {
Text("Click to test")
Image(systemName: "play.fill")
}
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
func encodeJSON(json: Data) -> Data? {
if let encoded = try? JSONEncoder().encode(json) {
return encoded
}
else {
print ("Failed to encode data")
return nil
}
}
func decodeJSON(json: Data) -> [Result]? {
let decoder = JSONDecoder()
if let output = try? decoder.decode(arrayOfResults.self, from: json) {
return output.results
}
else {
// Should I return nil ?
return nil
}
}
func uploadData() async -> [Result]?
{
// This URL sends back what it recieves.
// Great for testing JSON
let url = URL(string: "https://reqres.in/api/cupcakes")!
var request = URLRequest(url: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
do {
let(data, _) = try await URLSession.shared.upload(for: request, from:json)
var results = [Result]()
results = decodeJSON(json: data)!
return results
} catch {
print("Upload Failed")
// Return ?
}
// Should i return nil ?
return nil
}
Thanks Alan (Novice)