我想解析Swift 3中的JSON數據。當我嘗試打印整個有問題時。NSURLSession已被重命名爲URLSession
這是我的JSON文件的控制檯輸出:
{
"nameJt1": "01/07/1985",
"codeVideo1": "_NfijT6mt6A",
"nameJt2": "02/07/1985",
"codeVideo1": "XCabcwrxbNc",
"nameJt3": "03/07/1985",
"codeVideo3": "XCabcwrxbNc"
}
這是我的代碼來解析文件:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Jt1Label: UILabel!
@IBOutlet weak var Jt2Label: UILabel!
@IBOutlet weak var Jt3Label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
//1
let urlAsString = "http://tvlaayoune.ma/youtubeJT"
let url = NSURL(string: urlAsString)!
let urlSession = NSURLSession.sharedSession()
//2
let jsonQuery = urlSession.dataTaskWithURL(url, completionHandler: { data, response, error -> Void in
if (error != nil) {
println(error.localizedDescription)
}
var err: NSError?
// 3
var jsonJt = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &err) as! NSDictionary
if (err != nil) {
println("JSON Error \(err!.localizedDescription)")
}
// 4
let nameJt1: String! = jsonJt["nameJt1"] as! String
let nameJt2: String! = jsonJt["nameJt2"] as! String
let nameJt3: String! = jsonJt["nameJt3"] as! String
let codeVideo: String! = jsonJt["codeVideo"] as! String
dispatch_async(dispatch_get_main_queue(), {
Jt1Label.text = nameJt1
Jt1Labe2.text = nameJt2
Jt1Labe3.text = nameJt3
})
})
// 5
jsonQuery.resume()
}
}
我不明白是什麼問題。任何人都可以幫我一把嗎?先謝謝你。
這是顯示的代碼截圖:
什麼問題?如何解析你的JSON?如果你告訴我們你的預期會有所幫助。錯誤信息的含義是什麼?它就在描述中。從你的代碼中散佈的// 1,// 2,// 3我懷疑你已經粘貼了你在教程中找到的一些代碼並嘗試去適應它,但是你仍然沒有明確地提出一個問題。 – Abizern
只需單擊紅色圖標Xcode就會提示修復。是的'NS'前綴被刪除,現在它只是URLSession –