从服务器获取JSON

问题描述 投票:0回答:1

从 2 天开始,我尝试编写一个“简单”代码(如果你知道怎么做)。但对我来说不可能。 我有一个像这样的 php 文件:

try {
    $sql = $db->prepare( "SELECT * FROM myTable" );
    $sql->execute();
    
    
    if ( $sql->rowCount() > 0) {
        
        while ($result = $sql->fetch()) {
            
            $responseData [] = array(
                "date" => $result->date,
                "ml" => $result->ml
            );
    
        }
        

        header('Content-Type: application/json');
        echo json_encode($responseData);
        
    }
    
} catch (PDOException $e) { 
    echo $e->getMessage();
    exit;
}

响应如下所示:

现在我想用 swift 创建一个表视图,它执行这个文件和这个 json 数据作为表的数据。这对我不起作用。

我尝试使用 chatgpt 支持:

var myData:[String : Any]?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        sendPostRequest { jsonResponse, error in
            if let error = error {
                print("Fehler beim Senden des POST-Requests: \(error)")
                return
            }


            self.myData = jsonResponse
            print("\(String(describing: self.myData))")
            
            //self.myTable.reloadData()
            
        }
        
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return myData?.count ?? 0
    }
    
    
    
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        cell.textLabel?.text = ""
        return cell
        
    }
    

}


func sendPostRequest(completion: @escaping ([String: Any]?, Error?) -> Void) {
    
    let apiUrl = URL(string: "https://myDomain.de/myFile.php")!


    var request = URLRequest(url: apiUrl)
    request.httpMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        // Überprüfe auf Fehler
        if let error = error {
            completion(nil, error)
            return
        }

        guard let httpResponse = response as? HTTPURLResponse,
              (200...299).contains(httpResponse.statusCode) else {
            let error = NSError(domain: "HTTP Error", code: (response as? HTTPURLResponse)?.statusCode ?? 0, userInfo: nil)
            completion(nil, error)
            return
        }

        if let data = data {
            do {
                if let jsonResponse = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
                    completion(jsonResponse, nil)
                } else {
                    let error = NSError(domain: "JSON Error", code: 0, userInfo: nil)
                    completion(nil, error)
                }
            } catch {
                completion(nil, error)
            }
        }
    }

    // Starte die Anfrage
    task.resume()
}

但我收到此错误:

Error Domain=JSON Error Code=0 "(null)"
swift
1个回答
0
投票

让我们添加一些调试步骤:

guard let data = data else { return }
//Print what you received, because it might highlight that you didn't received expected output because of wrong request etc, so always check the validity of your response in case of error. I've seen plenty of error where responses are HTML error code or unexpected responses because of bad requests: missing parameter, header, wrong url, etc.
print("Received: \(String(data: data, encoding: .utf8)")

do {
    // If you do a if let, add an else to print it's not the expected unwrapping
    // Here since there was no error thrown, it might be due to as? [String: Any]
    let jsonResponse = try JSONSerialization.jsonObject(with: data, options: [])
    if let jsonDict = jsonDict as? [String: Any] {
        completion(jsonResponse, nil)
    } else {
       print("JSON Response is NOT a [String: Any]
    }
} catch {
    completion(nil, error)
}

现在,关于你的回应,我强烈认为你的回应是一个数组,所以as?

[String: Any]
失败了,应该是这样?
[[String: Any]]
,因为你有多个对象。

您有一个

UITableView
,所以更改其余的:

var myData: [[String : Any]]?
...

let object = myData[indexPath.row]
cell.textLabel?.text = object["ml"] as? String
...

现在,关于您的解析,我建议您使用自定义

struct
而不是将数据处理到
Dictionary
中。使用
Codable
结构就更好了。

struct Model: Codable {
    let ml: String
    let date: String
}
...
var myData: [Model]?
...
let response = try JSONDecoder().decode([Model].self, from: data)
completion(response, nil)
...
cell.textLabel?.text = myData[indexPath.row].ml
© www.soinside.com 2019 - 2024. All rights reserved.