【问题标题】:Get the HTML content when hitting URL in swift 3在 swift 3 中点击 URL 时获取 HTML 内容
【发布时间】:2017-08-09 21:20:03
【问题描述】:

我的问题是我想点击 url,当我点击服务器端的 url 时,php 在 php 中只返回 echo 的结果,我必须将结果保存在 swift 3 中的变量中,我尝试了下面的代码:

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

我没有在 swift 中获得 URL 的内容,这在目标 C 中要容易得多。

【问题讨论】:

  • 寻找URLSession。您创建了请求,但没有“触发”它。
  • 尝试用 urlsession 实现这个
  • 您发布的代码的 Objective-C 版本也不起作用。这两种语言都不容易。无论哪种方式,它都是相同的 API。
  • @Larme 你能发布答案吗我非常感谢。我试过了,但他们没有触发 url。在 info.plist 我已经将 AppSecurityProtocol 添加到 yes !
  • request.httpMethod = "POST" 应该是一个 GET

标签: swift nsurl


【解决方案1】:

将字符串初始化器与 url 一起使用。

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

或者你可以使用 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()

【讨论】:

  • 如何打印响应、数据和错误?这是工作,但我想将返回内容保存到变量中
  • 我编辑了答案。我假设你想要页面中的 html。
  • 不要使用此代码。您不应从 Internet 同步加载数据。你真的应该使用URLSession
  • @rmaddy 你为什么这么说,我得到了内容......你能更具体地说明你为什么说不使用互联网同步......你有更好的 URLSession 代码来获取 htmlcontent 吗?
  • 您可以使用 DispatchQueue 并将其放在后台线程上。
【解决方案2】:

我调整了上面提供的代码。要获取 HTML 代码,请使用 URLSession。

斯威夫特 5

    let session = URLSession.shared
    let url = URL(string: "https://yourwebsiteaddress.com/")!
    let task = session.dataTask(with: url) { data, response, error in
        // Check whether data is not nil
        guard let loadedData = data else { return }
        // Load HTML code as string
        let contents = String(data: loadedData, encoding: .utf8)
        print(contents)
    }
    task.resume()

【讨论】:

    猜你喜欢
    • 2016-12-15
    • 2021-10-01
    • 1970-01-01
    • 2011-09-21
    • 2017-06-29
    • 2012-10-22
    • 2017-10-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多