Hello,
I need help reading the data from my MySQL database.
I would like to have the data read out in a loop and later add it to the NavigationView > List.
Can someone point out my mistakes here?
Or am I on the wrong track here?
Or is there another way to read data from a database?
I have an API file on my server (no Localhost)
<?php
// Create connection
$con=mysqli_connect("my-mysql-domain.com","usernmae","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Tablename";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($con);
?>
my php gives me the following output:
[{"id":"1","nachname":"Tester Name","vorname":"Tester Vorname","nummer":"123","mail":"muster@meinedomain.de","adresse":"Musterstrasse","plz":"12345","ort":"Ortname","title":"Beispieltitle","post":"Hier der Inhalt"},{"id":"2","nachname":"Smith","vorname":"Jin","nummer":"567","mail":"no mail","adresse":"Street","plz":"12345","ort":"Berlin","title":"","post":""}]
now to the Swift:
Swift-File StockModel.swift
import UIKit
import SwiftUI
class StockModel: NSObject, ObservableObject {
//properties of a stock
var id: String?
var nachname: String?
var vorname: String?
var nummer: String?
var mail: String?
var adresse: String?
var plz: String?
var ort: String?
var title: String?
var post: String?
//empty constructor
override init()
{
}
//construct with @nachname and @vorname parameters
init(id: String, nachname: String, vorname: String, nummer: String, mail: String, adresse: String, plz: String, ort: String, title: String, post: String) {
self.id = id
self.nachname = nachname
self.vorname = vorname
self.nummer = nummer
self.mail = mail
self.adresse = adresse
self.plz = plz
self.ort = ort
self.title = title
self.post = post
}
//prints a stock's name and price
override var description: String {
return "Nachname: \(String(describing: nachname)), Vorname: \(String(describing: vorname))"
}
}
Swift-File FeedModel.swift
import UIKit
import SwiftUI
/*
protocol FeedModelProtocol: class {
func itemsDownloaded(items: NSArray)
}
*/
protocol FeedModelProtocol: AnyObject {
func itemsDownloaded(items: NSArray)
}
class FeedModel: NSObject, URLSessionDataDelegate, ObservableObject {
@Published var fcdmember: [StockModel] = []
weak var delegate: FeedModelProtocol!
let urlPath = "https://my-domain.com/api/stock_service.php"
func downloadItems() {
let url: URL = URL(string: urlPath)!
let defaultSession = Foundation.URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: url) { (data, response, error) in
if error != nil {
print("Error")
}else {
print("stocks downloaded")
//self.parseJSON(data!)
parseJSON(data!)
}
}
task.resume()
}
}
func parseJSON(_ data:Data) {
var jsonResult = NSArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: data, options:JSONSerialization.ReadingOptions.allowFragments) as! NSArray
} catch let error as NSError {
print(error)
}
var jsonElement = NSDictionary()
let stocks = NSMutableArray()
for i in 0 ..< jsonResult.count {
jsonElement = jsonResult[i] as! NSDictionary
let stock = StockModel() //the following insures none of the JsonElement values are nil through optional binding if let name = jsonElement["name"] as? String, let price = jsonElement["price"] as? String { print(name) print(price) stock.name = name stock.price = price } stocks.add(stock) } DispatchQueue.main.async(execute: { () -> Void in
//the following insures none of the JsonElement values are nil through optional binding
if let id = jsonElement["id"] as? String,
let nachname = jsonElement["nachname"] as? String,
let vorname = jsonElement["vorname"] as? String,
let nummer = jsonElement["nummer"] as? String,
let mail = jsonElement["mail"] as? String,
let adresse = jsonElement["adresse"] as? String,
let plz = jsonElement["plz"] as? String,
let ort = jsonElement["ort"] as? String,
let title = jsonElement["title"] as? String,
let post = jsonElement["post"] as? String
{
stock.id = id
stock.nachname = nachname
stock.vorname = vorname
stock.nummer = nummer
stock.mail = mail
stock.adresse = adresse
stock.plz = plz
stock.ort = ort
stock.title = title
stock.post = post
}
stocks.add(stock)
}
DispatchQueue.main.async(execute: { () -> Void in
//self.delegate.itemsDownloaded(items: stocks)
})
}
Swift-File ContentView.swift
import UIKit
import Foundation
struct ContentView: View {
@State private var ausgabe = StockModel()
var body: some View {
VStack {
ForEach(ausgabe, id: \.self) { item in
Text("Your name is \(ausgabe).")
}
}
.padding()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}