簡體   English   中英

JSON可以快速不同的方式進行解析。 使用哪一個?

[英]JSON parsing in swift different ways. Which one to use?

我一直在快速跟蹤JSON解析教程。 它具有以下提到的用於解析和檢索數據的代碼。

func jsonParsingFromURL () {
        let url = NSURL(string: "http://theappguruz.in//Apps/iOS/Temp/json.php")
        let request = NSURLRequest(URL: url!)

        NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
            self.startParsing(data!)
        }
    }

    func jsonParsingFromFile()
    {
        let path: NSString = NSBundle.mainBundle().pathForResource("days", ofType: "json")!
        let data : NSData = try! NSData(contentsOfFile: path as String, options: NSDataReadingOptions.DataReadingMapped)

        self.startParsing(data)
    }

    func startParsing(data :NSData)
    {
        let dict: NSDictionary!=(try! NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers)) as! NSDictionary

        for var i = 0 ; i < (dict.valueForKey("MONDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("MONDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("TUESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("TUESDAY") as! NSArray) .objectAtIndex(i))
        }
        for var i = 0 ; i < (dict.valueForKey("WEDNESDAY") as! NSArray).count ; i++
        {
            arrDict.addObject((dict.valueForKey("WEDNESDAY") as! NSArray) .objectAtIndex(i))
        }
        tvJSON .reloadData()
    }

很好,但我無法理解生產線的狀況-

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                self.startParsing(data!)

我看到了另一個教程,該教程使用以下函數解析JSON-

//Making the API Request

var request: NSURLRequest = NSURLRequest(URL: url)
var connection: NSURLConnection = NSURLConnection(request: request, delegate: self, startImmediately: false)
//Preparing for the response

//聲明一個數組,如下所示

var data: NSMutableData = NSMutableData()

//接收響應

1.

func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
   // Received a new request, clear out the data object
   self.data = NSMutableData()
}
2.

func connection(connection: NSURLConnection!, didReceiveData data: NSData!) {
   // Append the received chunk of data to our data object
   self.data.appendData(data)
}
3.

func connectionDidFinishLoading(connection: NSURLConnection!) {
   // Request complete, self.data should now hold the resulting info
   // Convert the retrieved data in to an object through JSON deserialization
   var err: NSError
   var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary

   if jsonResult.count>0 && jsonResult["results"].count>0 {
      var results: NSArray = jsonResult["results"] as NSArray
      self.tableData = results
      self.appsTableView.reloadData()

   }
} 

那么上述兩種編碼之間的區別是什么,建議使用哪種編碼。 也請談一談

NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
                    self.startParsing(data!)

謝謝!

首先,也是最重要的是,iOS 9中不推薦使用NSURLConnection 。您應該改用NSURLSession

至於您的問題,它們是關於異步網絡讀取而不是JSON解析的。

NSURLConnection:

NSURLConnection至少有兩種使用方式。

  1. 您可以設置一個委托,啟動連接,然后等待您的委托方法(例如connection:didReceiveData:被調用。
  2. 您可以使用帶有完成塊的類方法sendAsynchronousRequest

sendAsynchronousRequest方法更易於實現,但功能不那么強大。 在接收到所有數據之前,您不會被呼叫,因此您無法執行諸如顯示進度指示器或將數據保存到磁盤時將其保存到磁盤的操作,以避免將所有內容保存在內存中。

如果您不需要這些東西,我建議您使用基於塊的sendAsynchronousRequest方法。

NSURLSession:

NSURLSession替代NSURLConnection ,它還提供了基於委托的方法和基於塊的方法,其優缺點類似於NSURLConnection

使用NSURLSession ,如果您不需要細粒度的控制,則使用系統的共享會話( NSURLSession.sharedSession() )更容易。 然后,您可以使用NSURLSession方法dataTaskWithRequest:completionHandler:創建一個NSURLSessionTask,並開始使用resume()方法運行的任務。 就像NSURLConnection一樣,當下載完成時,它會調用您的完成塊(關閉)。

NSURLSession還允許您將數據直接下載到磁盤,建立安全連接,在下載數據時將其分塊獲取,以及許多其他選項(您可能需要也可能不需要)。

編輯:

這是NSURLSession類參考中有關sharedSession的摘錄:

  • (NSURLSession *)sharedSession討論對於基本請求,URL會話類提供了一個共享的單例會話對象,該對象為您提供了合理的默認行為。 通過使用共享會話,您只需幾行代碼就可以將URL的內容提取到內存中。

與其他會話類型不同,您不創建共享會話。 您只需通過調用[NSURLSession sharedSession]來請求它。 如此一來,您將不提供委托或配置對象。 因此,對於共享會話:

當數據從服務器到達時,您無法增量獲取。

您不能顯着自定義默認的連接行為。

您執行身份驗證的能力受到限制。

您的應用未運行時,您無法執行后台下載或上傳。

共享會話使用共享的NSURLCache,NSHTTPCookieStorage和NSURLCredentialStorage對象,使用共享的自定義網絡協議列表(使用registerClass:和unregisterClass:配置),並且基於默認配置。

在使用共享會話時,通常應避免自定義緩存,cookie存儲或憑據存儲(除非您已經使用NSURLConnection進行了此操作),因為很有可能最終您將超出默認會話的功能,此時,您必須以與您的自定義網址會話配合使用的方式來重寫所有這些自定義設置。

換句話說,如果您要對緩存,cookie,身份驗證或自定義網絡協議進行任何操作,則可能應該使用[自定義]會話,而不是[共享]會話。

(我在報價單中修正了蘋果文檔中的一些錯字。我的更改在最后一句中放在方括號中。)

在線搜索NSURLSession SwiftNSURLSessionDataTask Swift ,您應該能夠找到有關使用NSURLSession的教程。 實際上很容易。

阿拉莫火

您也可以在“ AlamoFire”上進行搜索。 這是一個輕量級的Swift框架,可提供輕松的異步下載,包括內置的JSON處理。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM