Swift 上表滞后的 JSON 数据

发布时间: 2017/3/5 17:00:48
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我和我的表显示 JSON 数据有问题。当它显示时,它目前还落后于每当我向上和向下滚动。我知道有的使用盛大中央调度方法 (GCD),然而,我也不知道如何做到这一点。

这是我我只是抓住 JSON 数据字典的 viewDidLoad() 方法中的代码片段︰

// Convert URL to NSURL
    let url = NSURL(string: apiURL)

    let jsonData: NSData?

    do {
        /*
        Try getting the JSON data from the URL and map it into virtual memory, if possible and safe.
        DataReadingMappedIfSafe indicates that the file should be mapped into virtual memory, if possible and safe.
        */
        jsonData = try NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
    } catch let error as NSError
    {
        showErrorMessage("Error in retrieving JSON data: \(error.localizedDescription)")
        return
    }

    if let jsonDataFromApiURL = jsonData
    {
        // The JSON data is successfully obtained from the API

        /*
        NSJSONSerialization class is used to convert JSON and Foundation objects (e.g., NSDictionary) into each other.
        NSJSONSerialization class's method JSONObjectWithData returns an NSDictionary object from the given JSON data.
        */

        do
        {
            let jsonDataDictionary = try NSJSONSerialization.JSONObjectWithData(jsonDataFromApiURL, options: NSJSONReadingOptions.MutableContainers) as? NSDictionary

            // Typecast the returned NSDictionary as Dictionary<String, AnyObject>
            dictionaryOfRecipes = jsonDataDictionary as! Dictionary<String, AnyObject>

            // Grabs all of the matched recipes
            // This will return an array of all of the matched recipes
            matchedRecipes = dictionaryOfRecipes["matches"] as! Array<AnyObject>

            // Returns the first 10 recipes shown in the JSON data
            recipeCount = matchedRecipes.count

        }catch let error as NSError
        {
            showErrorMessage("Error in retrieving JSON data: \(error.localizedDescription)")
            return
        }
    }

    else
    {
        showErrorMessage("Error in retrieving JSON data!")
    }

谢谢你 !

解决方法 1:

我已经搞明白了。它不只

dispatch_async(dispatch_get_main_queue())

因为那只用主线程,并且你应该只使用,当您显示 JSON 信息到视图上的时。如果我正确理解这,你都可以使用︰

 dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)){}

每当你正在下载的数据,例如图像,展示到视图上前。这里是为有兴趣的人的示例代码︰

    //-----------------
    // Set Recipe Image
    //-----------------
    dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0))
    {
        // This grabs the Image URL from JSON
        let imageURL = recipeDataDict["imageUrlsBySize"] as! NSDictionary
        let imageSize90 = imageURL["90"] as! String

        // Create an NSURL from the given URL
        let url = NSURL(string: imageSize90)

        var imageData: NSData?

        do {
            /*
            Try getting the thumbnail image data from the URL and map it into virtual memory, if possible and safe.
            DataReadingMappedIfSafe indicates that the file should be mapped into virtual memory, if possible and safe.
            */
            imageData = try NSData(contentsOfURL: url!, options: NSDataReadingOptions.DataReadingMappedIfSafe)
        } catch let error as NSError
        {
            self.showErrorMessage("Error in retrieving thumbnail image data: \(error.localizedDescription)")
        }
        dispatch_async(dispatch_get_main_queue(),
        {
            if let image = imageData
            {
                // Image was successfully gotten
                cell.recipeImage!.image = UIImage(data: image)
            }
            else
            {
                self.showErrorMessage("Error occurred while retrieving recipe image data!")
            }
        })
    }

只是没有 main_queue 线程 dispatch_get_global_queue 之前,图像会下载很慢 (但不是远远落在后面的表)。然而,一旦我在 main_queue 中添加显示 JSON 数据之前,它下载立即 (或几乎立即),没有任何进一步落后于。

有关的详细信息︰ https://tetontech.wordpress.com/2014/06/04/swift-ios-and-grand-central-dispatch/

赞助商