我是Swift和iOS開發新手,但我試圖下載和分析存儲在MySQL數據庫中的數據。爲什麼我得到錯誤「域= NSCocoaErrorDomain代碼= 3840」沒有值。「 UserInfo = {NSDebugDescription =沒有值。}'?
我不斷收到錯誤:
Domain=NSCocoaErrorDomain Code=3840 "No value." UserInfo={NSDebugDescription=No value.}
我已張貼下面我的代碼,但我不認爲這個問題是在parseJSON功能,而是在數據的實際下載,當我打印'data'返回'<>'。
這裏是我的代碼:
//properties
weak var delegate: HomeModelProtocal!
var data : NSMutableData = NSMutableData()
let urlPath: String = "http://localhost/service.php" //this will be changed to the path where service.php lives
// Function to download the incoming JSON data
func downloadItems(){
let url: URL = URL(string: urlPath)!
var session: URLSession!
let configuration = URLSessionConfiguration.default
session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
let task = session.dataTask(with: url)
task.resume()
}
func urlSession(_ session: URLSession, task: URLSessionDataTask, didCompleteWithError error: Error?) {
self.data.append(data as Data)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
if error != nil{
print("Failed to download data")
}else{
print("Data downloaded")
print(data)
self.parseJSON()
}
}
func parseJSON(){
var jsonResult: NSMutableArray = NSMutableArray()
do{
jsonResult = try JSONSerialization.jsonObject(with: self.data as Data, options: []) as! NSMutableArray
} catch let error as NSError {
print("**** sake its happened again \(error)")
}
var jsonElement: NSDictionary = NSDictionary()
let locations: NSMutableArray = NSMutableArray()
for i in 0 ..< jsonResult.count{
jsonElement = jsonResult[i] as! NSDictionary
let location = LocationModel()
//the following insures none of the JsonElement values are nil through optional binding
if let exerciseName = jsonElement["stationName"] as? String,
let bodyPart = jsonElement["buildYear"] as? String
{
print(exerciseName, bodyPart)
location.exerciseName = exerciseName
location.bodyPart = bodyPart
}
locations.add(location)
}
DispatchQueue.main.async(execute: {() -> Void in
self.delegate.itemsDownloaded(items:locations)
})
}
也許反應是空的?你的'print(data)'顯示了什麼? –
嘗試這樣做,在郵遞員或其他地方,並檢查,如果事情是真的有 –
我試圖打印數據,並將其返回<> 當我查看我使用的網址我得到這個返回: 「[ { 「Exercise_Id」:「1」, 「Exercise_Name」:「Barbell Curl」, 「Body_Part」:「Arms」 },' – MHDev