包裝JSON結果在一本字典,我試圖檢索JSON,並在迅速字典包裹它,不能找出問題所在。問題迅速
我的SWIFT代碼是:
let apiRequest = NSURLRequest(URL: "my api url")
NSURLConnection.sendAsynchronousRequest(apiRequest, queue: processingQueue) {response, data, error in
if error != nil {
completion(results: nil,error: error)
return
}
var JSONError : NSError?
let resultsDictionary = NSJSONSerialization.JSONObjectWithData(data, options:NSJSONReadingOptions(0), error: &JSONError) as? NSDictionary
if JSONError != nil {
completion(results: nil, error: JSONError)
return
}
// This next line causes an error that 'unexpectedly found nil while unwrapping an Optional value'
let photosContainer = resultsDictionary!["ArrayOfPhotoDTO"] as NSDictionary
let photosReceived = photosContainer["PhotoDTO"] as [NSDictionary]
如果我設置一個斷點,然後我resultsdictionary是零,但是我的數據變量似乎無誤。 _bytes視圖顯示
"[{\"$id\":\"1\",\"PhotoID\":57,\"JobID\":2346,\"DateAdded\":\"28/11/2014 12:00:00 AM\",\"Location\":\"Beverly Hills (1).JPG\",\"Filename\":\"Beverly Hills (1).JPG\",\"Caption\":\"Beverly Hills (1).JPG\"},"
JSONError爲零。
如果我打電話給我的API直接我得到以下結果:
[
{
"$id": "1",
"PhotoID": 57,
"JobID": 2346,
"DateAdded": "28/11/2014 12:00:00 AM",
"Location": "Beverly Hills (1).JPG",
"Filename": "Beverly Hills (1).JPG",
"Caption": "Beverly Hills (1).JPG"
},
我在做什麼錯?
當你在瀏覽器中直接調用你的API時,你會得到XML?! – MrBr 2015-03-02 12:49:02
對不起,API返回JSON,但我使用瀏覽器擴展名來格式化爲xml! – Evonet 2015-03-02 12:50:07
我真的建議你使用類似SwiftyJSON的解析結果。標準的方式是冗長的,這使得很難追蹤錯誤。 (https://github.com/SwiftyJSON/SwiftyJSON) – Raymond 2015-03-02 12:55:01