kien vu
kien vu

Reputation: 75

Swift get content text response after send request to web service

I know how to get data response from url. But the data response contains html sourceenter image description here. Although I can handle it to get what I need but will be better if I know how to get only text. I use:

    let task = URLSession.shared.dataTask(with: request)
    {
        data, response, error in guard
            let data = data, error == nil else
        {
            // check for fundamental networking error
            print(error!)
            return
        }
        result = String(data: data, encoding: .utf8) ?? ""
    }
    task.resume()

Upvotes: 1

Views: 1500

Answers (2)

Barnyard
Barnyard

Reputation: 273

Unless the endpoint has an option (like a query parameter) to return only the text, then you will get whatever the server wants to send and you will need to sort it out client side.

Upvotes: 1

Craig Siemens
Craig Siemens

Reputation: 13296

You could do it like this.

let text = String(decoding: data, as: UTF8.self) // Convert data to string
    .components(separatedBy: "\n")               // Split string into multiple line 
    .first                                       // Get the first line

Upvotes: 2

Related Questions