繁体   English   中英

Swift自定义updateUI()函数不适用于viewDidLoad

[英]Swift custom updateUI() function does not work on viewDidLoad

我正在开发一个应用程序,该应用程序应该从我的服务器请求一些数据。 我正在使用Alamofire做到这一点,然后使用SWXMLHash解析XML数据。 有两个View Controller,第一个是我可以写一个货件编号,然后重写函数prepareForSegue并将该编号发送到下一个View Controller,该View Controller应显示来自server和updateUI的viewDidLoad上的数据,但没有。 哪里有问题?

我的课:

class Shipment {
    private var _shipmentNumber: String!
    private var _shipmentStatus: String!
    private var _trackURL: String!

    var shipmentNumber: String {
        if _shipmentNumber == nil {
            _shipmentNumber = ""
        }
        return _shipmentNumber
    }

    var shipmentStatus: String {
        if _shipmentStatus == nil {
            _shipmentStatus = ""
        }
        return _shipmentStatus
    }

    init(spNumber: String) {
        self._shipmentNumber = spNumber

        _trackURL = "..."
    }

    func requestXmlInformation(completed: DownloadComplete) {
        let url = NSURL(string: _trackURL)!
        Alamofire.request(.GET, url).responseData { response in

            if let xmlToParse = response.data as NSData! {
                let xml = SWXMLHash.parse(xmlToParse)

                do {
                    let xmlSpWeight = try xml["fmresultset"]["resultset"]["record"]["field"].withAttr("name", "ТotalWeight")["data"].element!.text! as String

                    self._shipmentStatus = xmlSpStatus
                    print(self._shipmentStatus)
                } catch let err as NSError {
                    print(err.debugDescription)
                }
            }
        }
    }
}

我的第二个视图控制器

@IBOutlet weak var numberLbl: UILabel!
@IBOutlet weak var weightLbl: UILabel!
@IBOutlet weak var statusLbl: UILabel!
@IBOutlet weak var packageQtyLbl: UILabel!

var shipment: Shipment!

override func viewDidLoad() {
    super.viewDidLoad()
    shipment.requestXmlInformation { () -> () in
        self.updateUi()
        print(self.statusLbl.text)
    }
  }

updateUI函数:

func updateUi() {
    numberLbl.text = shipment.shipmentNumber
    weightLbl.text = shipment.shipmentWeight
    statusLbl.text = shipment.shipmentStatus
    packageQtyLbl.text = shipment.shipmentPackageQty
}

它在终端中打印数据,但我认为updateUI功能不起作用。

确保在主线程上调用了requestXmlInformation闭包中的代码。 您不应该在后台线程中更新UI。

shipment.requestXmlInformation { () -> () in
  dispatch_async(dispatch_get_main_queue(), { () -> Void in
        self.updateUi()
        print(self.statusLbl.text)
  })
}

另外,您似乎没有在requestXmlInformation方法中的任何地方调用完整的闭包

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM