Swift: 值未加载到文本字段

Swift: Value does not load to text field

当屏幕加载时,它从 REST 调用中获取响应,然后更新 UI。
Flow 工作正常,但不知何故它没有更新 textfield 的值。适用于标签。

标签已更新,文本字段未更新。

override func viewDidLoad() {
        super.viewDidLoad()
        getContactInfo(id) //Rest call
}

Part of the rest call

let task = session.dataTaskWithRequest(request) { (data, responseData, error) -> Void in
                if let response = responseData as? NSHTTPURLResponse {
                    self.statusCode = response.statusCode
                    print("Response code: \(response)")
                }

                do {
                    if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary {
                        //json parsing
                    }

                } catch {
                    print(error)

                }

                if(self.statusCode != 200) {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                    print("Error could not parse JSON: '\(jsonStr)'")
                }
                else {
                    let name = self.contact?.firstName
                    print("Everything Looks good: \(name!)")
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.updateUI()
                    })
                }
            }
            task?.resume()
      //  }

    }

Update UI

private func updateUI() {
        print("Refresh UI1")
        if contact != nil {
            print("Refresh UI2")
            self.firstName.text = (contact?.firstName)!
            self.name.text = (contact?.firstName)!
        }

    }

控制台输出

Everything Looks good: Derp
Refresh UI1
Refresh UI2

Note: Is it the right way to do it?(I am new to iOS development)

试试这个,

private func updateUI() {

 print("Refresh UI1")
        if contact != nil {
            print("Refresh UI2")
             dispatch_async(dispatch_get_main_queue()) {
              self.firstName.text = (contact?.firstName)!
              self.name.text = (contact?.firstName)!
             }
           }
   }

如何在异步线程上更新 UI 的正确方法如下:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { () -> Void in
    dispatch_async(dispatch_get_main_queue(), { () -> Void in
        // Update UI
    })
})

希望对您有所帮助!