【发布时间】:2017-02-10 17:37:14
【问题描述】:
我是 Swift 和 iOS 开发的新手,但我正在尝试下载和解析存储在 MySQL 数据库中的数据。
我不断收到错误:
Domain=NSCocoaErrorDomain 代码=3840 "没有价值。" UserInfo={NSDebugDescription=无值。}
我在下面发布了我的代码,但我认为问题不在于 parseJSON 函数,而是在数据的实际下载中,因为当我打印“数据”时它返回“”。
这是我的代码:
//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)显示了什么? -
尝试在邮递员或其他地方执行此操作,并检查是否真的有东西
-
我已经尝试打印数据并返回", "Body_Part": "武器" },'
标签: ios mysql json swift xcode