Search code examples
swiftnsurl

Get the HTML content when hitting URL in swift 3


My question is i want to hit the url and when i hit the url on server side the php return the results just echo in php and i have to save that result in variable in swift 3, i tried the below code:

let URLstr = URL(string: strURL)
let request = URLRequest(url: URLstr!)
request.httpMethod = "POST"
print (request)

I didn't get the content of URL in swift which is much easier in objective C.


Solution

  • Use the string initializer with the url.

    do {
      let contents = try String(contentsOf: URLstr, encoding: .ascii)
    } catch {
      // handle error
    }
    

    Or you can use URLSession.

    let task = URLSession.shared.dataTask(with: URLStr) { data, response, error in
       guard data != nil else { // no data }
       let contents = String(data: data!, encoding: .ascii)  
    }
    task.resume()