2017-09-04 72 views
-5

我想解析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() 
    } 
} 

我不明白是什麼問題。任何人都可以幫我一把嗎?先謝謝你。

這是顯示的代碼截圖:

enter image description here

+0

什麼問題?如何解析你的JSON?如果你告訴我們你的預期會有所幫助。錯誤信息的含義是什麼?它就在描述中。從你的代碼中散佈的// 1,// 2,// 3我懷疑你已經粘貼了你在教程中找到的一些代碼並嘗試去適應它,但是你仍然沒有明確地提出一個問題。 – Abizern

+0

只需單擊紅色圖標Xcode就會提示修復。是的'NS'前綴被刪除,現在它只是URLSession –

回答

1

該錯誤不涉及您的JSON數據結構。

如果您單擊代碼列中的紅色圓圈,則建議的修復將使用URLSession替換NSURLSession。您也可以手動執行此操作。

有很多資源可以幫助您使用Swift和JSON,但看看這篇文章 - 它涵蓋了這兩個主題,並且包含了有關從NSURLSession ...到URLSession更改的一些內容。

https://grokswift.com/updating-nsurlsession-to-swift-3-0/

+2

是的。 (投票。)Xcode甚至可能會提出爲你做出改變。對於OP,注意你應該使用Swift本地類型而不是Objective-C版本,所以應該用'Dictionary'來替換'NSDictionary'。你甚至可以使用'[String:Any]',這樣你就可以獲取鍵/值對,而不必將鍵轉換爲String。 –

相關問題