Swift JSON "POST" массив данных запроса - PullRequest
0 голосов
/ 19 января 2020

Я не могу удалить массив из вывода данных, попытался определить структуру с количеством кавычек, которые я получаю из данных, и попытался ввести его, но я не могу, так как мне нужно удалить скобки массива из JSON Ответ первым. Застрял здесь на некоторое время, Первый раз используя JSON POST тип.

if let requestUrl = url {
            // Prepare URL Request Object
            var request = URLRequest(url: requestUrl)
            request.httpMethod = "POST"
            // HTTP Request Parameters which will be sent in HTTP Request Body
            let postString = ["freq": freqId]
            // Set HTTP Request Body
            request.httpBody = try? JSONSerialization.data(withJSONObject: postString, options: [] );
            // Perform HTTP Request
            let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                // Check for Error
                if let error = error {
                    self.delegate?.didGetError(error: error)
                    return
                }
                // Convert HTTP Response Data to a String
                if let data = data, let dataString = String(data: data, encoding: .utf8) {
                    print(dataString)
                    let quotes = DataModel(quotes: dataString)
                    self.delegate?.didGetData(data: quotes)
                }
            }
            task.resume()
        }
        else {
            fatalError()
        } 

Ответ:

["10 years from now , you'll look back and say I'm glad I started trading","I always define my risk and I don't have to worry about it","For trading success , there's a realization that when you don't care , you do well and when you try too hard , you don't .","Necessity never made a good bargain.","When a falling stock becomes a screaming buy because it cannot conceivably drop further , try to buy it thirty percent lower .","There are infinite number of ways to make money in markets & in life , Find ONE that works for you.","Get comfortable with being uncomfortable !.","The markets are always changing , and they are always the same.","You can't control how you feel . But you can always to choose how you act !","If what you're looking for is an excuse you'll find one !"]

Снимок экрана

1 Ответ

0 голосов
/ 19 января 2020

Похоже, что ответ является массивом, а не строкой, поэтому измените обработку data на

guard let data = data else {
    //error handling...
    return
}

do {
    if let array = try JSONSerialization.jsonObject(with: data) as? [String] {
        let quotes = DataModel(quotes: array)
        self.delegate?.didGetData(data: quotes)
    }
} catch {
    print(error)
    //error handling...
}

Это предполагает, что DataModel можно инициализировать с помощью массива, если не нужно сделайте что-то вроде ниже, чтобы сначала объединить элементы массива в строку

let string = array.joined(separator: " ")

Глядя на скриншот, я подозреваю, что это не так просто, но лучший способ обработки содержимого массива выходит за рамки этого вопроса

...