尝试将返回的JSON值存储到Swift 3中的标签中

时间:2016-12-19 00:53:10

标签: json swift3

我在视图控制器类中有以下代码:

import UIKit
class orderStatusVC: UIViewController {

    //================ Segue Initializers ================//
    var orderNumber: String = ""


    //================ Member Variables ================//
    var orderStatusTitle: String = ""
    var orderStatusDesc: String = ""


    //================ Object Outlets ================//
    @IBOutlet weak var orderStatusLabel: UILabel!
    @IBOutlet weak var orderStatusText: UITextView!



    override func viewDidLoad() {
        super.viewDidLoad()

        //Call the function to pull the JSON data
        getData()
    }

    func getData() {
        let sessionConfig = URLSessionConfiguration.default

        let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)

        guard let URL = URL(string: "http://www.mywebsite.com/checkOrderStatus.php") else {return}
        let request = NSMutableURLRequest(url: URL)

        request.httpMethod = "POST"

        // Headers
        request.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        //This is the data that is sent to the server-side script, which contains a string (a 19-digit order number)
        let bodyObject: [String: String] = [
            "orderNumber":"\(orderNumber)" as String
        ]

        request.httpBody = try! JSONSerialization.data(withJSONObject: bodyObject, options: [])


        //This code handles the response from the server-side script
        let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) in

            guard error == nil else {
                print("error calling GET")
                return
            }

            guard let responseData = data else {
                print("Error: did not receive data")
                return
            }

            do {
                guard let orderStatus = try JSONSerialization.jsonObject(with: responseData, options: []) as? [String: AnyObject] else {
                    print("error trying to convert data to JSON")
                    return
                }


                //These two lines assign the returned JSON Data to the previously declared variables under the "Member Variables" heading.

                self.orderStatusTitle = orderStatus["orderStatus"]?["statusTitle"] as! String
                self.orderStatusDesc = orderStatus["orderStatus"]?["statusDesc"] as! String


               /* ============================================
                  If I uncomment these next two lines,
                  it accurately displays the correct data
                  in the log.
                  ============================================ */

                  //print(orderStatus["orderStatus"]?["statusTitle"])
                  //print(orderStatus["orderStatus"]?["statusDesc"])



               /* ============================================
                  However, the following two lines do NOT succeed
                  at putting the returned JSON values into the
                  designated outlets
                  ============================================ */

                  self.orderStatusLabel.text = self.orderStatusTitle
                  self.orderStatusText.text = self.orderStatusDesc

                return
            } catch {
                print("Error trying to convert data to JSON")
                return
            }
        })

        task.resume()
        session.finishTasksAndInvalidate()

        return
    }
}

此代码不会产生错误,但是,当我运行脚本时,它也不会使用正确的数据填充标签/ textview。事实上 - 它根本没有显示任何内容。

我试图将“getData()”函数调用放在viewWillAppear方法中,但这并没有把我带到任何地方。

我在我的另一个应用程序中运行类似的脚本,它似乎工作得很好 - 除了我在警报控制器中使用返回的文本而不是标签 - 所以我无法弄清楚为什么这失败了。

有人有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您正在尝试在后台线程中更新de UI。您应该尝试执行以下操作

OperationQueue.main.addOperation {
    self.orderStatusLabel.text = self.orderStatusTitle
    self.orderStatusText.text = self.orderStatusDesc
}

此外,不需要以下行:

session.finishTasksAndInvalidate()