首页 > 解决方案 > Swift:JSON 解析未显示在 UILabel 中,但可以使用 Alamofire 在输出窗口中看到

问题描述

我是编码新手,似乎没有显示每日报价UILabel。使用http://quotes.rest/qod.json 输出控制台显示结果,但UILabel. 任何帮助是极大的赞赏。

以下是来自网站的 JSON 格式:

{
    "success": {
        "total": 1
    },
    "contents": {
        "quotes": [
            {
                "quote": "You make a living by what you earn",
                "length": "69",
                "author": "Winston  Churchill",
                "tags": [

                    "inspire"
                ],
                "category": "inspire",

                "id": "XZiOy4u9_g4Zmt7EdyxSIgeF"
            }
        ],
        "copyright": "2017-19 theysaidso.com"
    }
}

我用来解析上述 JSON 的 Swift 代码是:

import Alamofire
import SwiftyJSON


class DailyQuotes {


    private var _quotes: String!
    private var _author: String!

    var quotes: String
    {
        if _quotes == nil
        {
            _quotes = ""
        }
        return _quotes
    }



    /// Downloading Current Weather Data


    func downloadQuotes(completed: @escaping DownloadComplete){


            Alamofire.request(QuotesDaily).responseJSON 
{ (response) in

                let result = response.result
                print(result.value)
                let json = JSON(result.value!)


             self._quotes = json["contents"]["quotes"]["quote"].stringValue

                completed()
            }
             }


} 

ViewConrtroller.swift

func  updateQuotesUI()
{
   quoteLabel.text = dailyQuotes.quotes
    }

标签: iosswiftalamofireswift4

解决方案


引号是一个数组

let arr = json["contents"]["quotes"].arrayValue
self._quotes = arr[0]["quote"].stringValue

推荐阅读