我有以下无法解决的问题,可能是因为我不太了解urlsessions。所以我有一个mysql数据库和一个php脚本,可以获取数据库的某些值。我定义了自己的简单类,该类具有某些属性,这些属性来自mysql中的表,并且在该自定义类中定义了一种方法,该方法检索此数据并将这些检索出的值分配给该对象。我执行此操作的代码如下(在我的代码中可能效率很低...),我在Xcode的操场文件中尝试过,该类称为foodClass(因为数据库与食物有关):
import UIKit
class foodClass {
var description : String?
var price : Float?
func downloadDish(){
let requestURL = NSURL(string: "http://localhost/downloadDishes.php")
let request = NSMutableURLRequest(url: requestURL! as URL)
request.httpMethod = "POST"
//example id, which tells php which food to pick
let postString = "id=\(12)"
let utf8PostString = postString.data(using: .utf8)
let task = URLSession.shared.uploadTask(with: request as URLRequest, from: utf8PostString){
data, response, error in
if error != nil {
DispatchQueue.main.async {
print("no connection maybe?")
}
}
else {
if data != nil {
do {
let dishJSON = try JSONSerialization.jsonObject(with: data!) as! NSDictionary
let disharray = dishJSON["dishes"] as! NSArray
//print to make sure that we get a response
print(disharray[0])
let tempdish = disharray[0] as! NSArray
self.description = tempdish[2] as! String
self.price = (tempdish[3] as? NSNumber)?.floatValue ?? 4.99
} catch {
print(error)
}
}
}
}
task.resume()
}
}
//test it out
var dish = foodClass()
dish.downloadDish()
print(dish.description)
因此,打印语句“ print(disharray [0])”准确显示了数据库中的内容,因此从数据库中检索数据没有任何问题。但是在调用函数downloadDish()之后,某种程度上属性说明和价格没有被初始化。也许我不了解有关类和URL会话的关键信息。