Как добавить строки для каждого цикла в Swift - PullRequest
0 голосов
/ 21 октября 2019

Я хочу проанализировать строку json и отобразить в UITextView. Я получаю данные со строкой HTML с ключом и значениями. Ниже приведен пример строкового ответа от сервера:

   {"":"<strong>Adidas<\/strong><br>Enjoy 10% off","Period":"10 Oct 2019 - 11 Nov 2019","Description":"<p>Enjoy 30% off 
   "Terms & Conditons":"<ol>\n<li>It's available only in peak hours<\/li>\n}

Мне нужно отобразить как приведенный ниже формат с HTML,

Expected output: 
      Adidas
      Enjoy 10% off
      Period:
      10 Oct 2019 - 11 Nov 2019
      Description:
      Enjoy 30% off.
      Terms & Conditons:
      It's available only in peak hours

Я использовал словарь и извлек данные, нопроблема в том, что порядок данных не в порядке.

   func setupData(responseString : String)
   {
    // Convert string to dictionary for extracting the keys and values
    // Need to maintain the order while adding the data
    let content = convertToDictionary(text: responseString)
    var text : String = ""
    if let contentDataDict = content
    {
        for (key, value) in  contentDataDict
        {
         // want to append the key and values in the sequence order
                textView.attributedText = text.htmlToAttributedString
            }

        }
    } 

Как проанализировать и отобразить данные в соответствии с ожидаемым выводом.

1 Ответ

0 голосов
/ 21 октября 2019

Деван, ты прав, думая, что словарь не будет работать. Вам лучше загрузить HTML в массив. Я использовал псевдокод для представления нового convertToArray вместо вашего convertToDictionary, поскольку вы не указали весь исходный код

struct Component {
  field: String
  value: String
}

func convertToArray(response: String) -> [Component] [
  let components = [Component]()
  for entries in response {
    //extract key/value pairs from html as before
    //then create a component struct with them and add it to the array
    components.append(Component(field: key, value: value)
  }
  return components //now a sequence of structs represent your data in order
}


func setupData(responseString : String) {
  let components: [Component] = convertToArray(text: responseString)
  for component in components {
     //add component.field and component.value to your attributed text string
     //and then display as before
  }
}

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...