Swift:值不会加载到文本字段

时间:2015-07-23 18:40:54

标签: ios swift ios8

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

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

textfield
  
    

其余部分电话

  
override func viewDidLoad() {
        super.viewDidLoad()
        getContactInfo(id) //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()
      //  }

    }

控制台输出

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

    }
  
    

注意:这是正确的方法吗?(我是iOS开发的新手)

  

2 个答案:

答案 0 :(得分:1)

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

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

希望它有所帮助!

答案 1 :(得分:0)

试试这个,

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)!
             }
           }
   }