我有一個具有諸如url,title和timestamp等屬性的文件的數據庫。當我加載某個視圖控制器時,我正在獲取文件數據並將其加載到tableview中。因爲有多個文件,每個文件都有它們的3個屬性,所以我試圖將數據保存在數組中,然後遍歷數組中的每個對象並提取JSON數據。截至目前,GET請求和響應都是成功的,但該數組仍然爲零。我的方法錯了嗎?在數組中存儲提取的json字典導致nil
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
guard let data = data, response = response else
{
print("No data or response!")
return
}
let strData = NSString(data: data, encoding: NSUTF8StringEncoding)
print("Body: \(strData)", terminator: "")
do {
self.fetchedArray = try NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves) as? NSArray
print("fetched array count is %i \(self.fetchedArray!.count)")
if let jsonArray: NSArray = self.fetchedArray{
for var i = 0; i<jsonArray.count; ++i {
let dictResult = jsonArray.objectAtIndex(i) as! NSDictionary
let recording = Recordings()
recording.trackURL = dictResult["url"] as? String
recording.trackTimestamp = dictResult["timestamp"] as? String
recording.trackAuthor = dictResult["author"] as? String
recording.trackTitle = dictResult["title"] as? String
self.recordings?.addObject(recording)
}
}
else
{
// No error thrown, but not NSDictionary
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
print("No error thrown but could not parse JSON: '\(jsonStr)'")
}
}
catch let parseError {
// Log the error thrown by `JSONObjectWithData`
print(parseError)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
print("Error thrown. could not parse JSON: '\(jsonStr)'")
}
})
task.resume()
由於現在它的執行倒數第二個else語句print("No error thrown but could not parse JSON: '\(jsonStr)'")
,並打印出所有的數據。
數據的日誌序列之前:
Response: <NSHTTPURLResponse: 0x7c349990> { URL: http://127.0.0.1:5000/auth/serve_current_user_files } { status code: 200, headers {
"Content-Length" = 239;
"Content-Type" = "application/json";
Date = "Sat, 03 Oct 2015 02:53:00 GMT";
Server = "Werkzeug/0.10.4 Python/2.7.10";
"Set-Cookie" = "session=eyJfZnJlc2giOnRydWUsIl9pZCI6eyIgYiI6Ik16RXhaRGs0TldVM1lUQmxNREJrWlRNeFpqZ3pZMkl3T1dRNE5EZzVPREk9In0sInVzZXJfaWQiOiIxIn0.CPDUjA.Mm56VPuZPIokCZVoRw7X2ySz960; HttpOnly; Path=/";
} }Body: Optional({
"recordings": [
{
"author": 1,
"timestamp": "Sun, 27 Sep 2015 17:44:54 GMT",
"title": "Test1.m4a",
"url": "/Users/allahesharghi/Desktop/Omid/pythonprojects/sound/sound/uploads/omid1/Test1.m4a"
}
]
確保數據是有效的。
在print(「Body:\(strData)」,terminator:「」)它打印出你想要的結果嗎? – wei
執行的唯一打印語句是在第二個到最後一個else語句之內的打印,因爲該數組是從nil出來的。數據看起來正確。 – Brosef
我的意思是在串行化json對象之前,確保數據是正確的。或者在這裏發佈你的日誌,那將更容易發現錯誤。 – wei