3

UILabel.text is not updated inside the main thread. labelOne is updated but labelTwo which is to show translated word is not updated. When I print translatedWord it prints right string to console but UILabel is not updated.

datatask = session.dataTask(with: request, completionHandler: {data, response, error in
    if error == nil {
        let receivedData = try? JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]

        DispatchQueue.main.async {
            self.labelOne.text = wordTobeTranslated

            let data = "\(String(describing: receivedData!["text"]))"
            let all =   data.components(separatedBy: "(")
            let afterAll = all[2]
            let last = afterAll.components(separatedBy:")" )

            self.translatedWord = last[0]

            self.importantWords.append(last[0])
            self.labelTwo.text = self.translatedWord
            print(self.translatedWord)
        }
    }
})
datatask?.resume()
Rob
  • 415,655
  • 72
  • 787
  • 1,044
Selçuk Yıldız
  • 539
  • 1
  • 5
  • 14

3 Answers3

0

Some tips to debug your issue:

  1. Try to set some hard coded string to labelTwo and check whether it is displaying. (or)
  2. Update any value for labelTwo in Storyboard and check whether is is displaying.

If string is displayed from any of the above steps, then labelTwo is configured correctly in storyboard.

You can also try self.labelTwo.layoutIfNeeded() method after updating the text to force update the UI.

If none of the steps helps you, check the Font color of UILabel. If it is same as background color, it would not be seen.

Anand
  • 1,820
  • 2
  • 18
  • 25
0

Looking at your code sample, it would appear that you’re trying to retrieve:

describing: receivedData!["text"]

from:

\(String(describing: receivedData!["text"]))

The problem is that the \(...) in a String literal results in string interpolation where the expression inside \( and ) will be evaluated and that’s what will be place in the string. And the String(describing: ...) will interpret the value and return a string representation. So, let’s say that receivedData!["text"] contained the word “Foo”. Then

let data = "\(String(describing: receivedData!["text"]))"

Would result in data containing the string, Optional("Foo").

If you want to remove that Optional(...) part, you should either unwrap the optional or use a nil-coalescing operator, ??. And frankly, rather than using string interpolation at all, I’d just do:

let data = String(describing: receivedData?["text"] ?? "")
Rob
  • 415,655
  • 72
  • 787
  • 1,044
0

I know this is an old question, but for new searchers: Try setting number of lines of UILabel to Zero. It might be a constraints issue.

mahdi
  • 439
  • 3
  • 15