Swift Haneke: Json Data in TextView

1.5k views Asked by At

I used the Haneke Framework to get Data from a Site. With the Haneke Framework i also can get Images from a site, and these Images i can present on a UIImageView. Now i wanted to get some text from a site.

I did it like this:

 cache.fetch(URL: URL).onSuccess { JSON in
            println(JSON.dictionary?["index"])

It printed me all the data from "Index".

Now i want, that all the data from "Index" should be presented on a UITextView.

  self.textView.text = JSON.dictionary["index"]

But it doesn't work. I get the error:

Cannot assign a value of type 'AnyObject' to a value of type 'String!'

I have to unwrap it or?

3

There are 3 answers

0
vadian On BEST ANSWER

Finally, this prints out all records of the JSON text. The structure is an array of dictionaries. The text is very simply formatted (two tab characters between key and value).

  cache.fetch(URL: url).onSuccess { JSON in
    if let index = JSON.dictionary?["index"] as? [Dictionary<String,String>] {
      var resultString = ""
      for anItem in index {
        for (key, value) in anItem {
          resultString += "\(key)\t\t\(value)\n"
        }
        resultString += "\n\n"
      }
      self.textView.text = resultString
    }
  }
}
6
vadian On

the compiler doesn't know the type of the dictionary item. If you know it's always a String make a forced downcast from AnyObject to String

self.textView.text = JSON.dictionary["index"] as! String
21
vadian On

as we've revealed that JSON.dictionary["index"] is an Array, this is a safe syntax assuming that the array contains only one item

if let indexTextArray = JSON.dictionary?["index"] as? [String] {
  if !indexTextArray.isEmpty {
      self.textView.text = indexTextArray.first!
  }
}