如何在swift2中下载页面,而不使用第三方库? [英] How to download a page in swift2 without using third party libraries?
本文介绍了如何在swift2中下载页面,而不使用第三方库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正试图在应用程式中显示下载的HTML页面。请说明最简单的方式,不用任何第三方图书馆。
I am trying to show the downloaded HTML page in the app. Please explain the simplest way to do so without using any third party libraries.
欢呼,
推荐答案
您应该使用NSURLSession dataTaskWithURL异步下载您的网站数据:
You should use NSURLSession dataTaskWithURL to download your website data asynchronously:
import UIKit
class ViewController: UIViewController {
let stackoverflowLink = "https://stackoverflow.com/questions/36315798/how-to-download-a-page-in-swift2-without-using-third-party-libraries"
override func viewDidLoad() {
super.viewDidLoad()
guard let url = NSURL(string: stackoverflowLink) else { return }
print("LOADING URL")
NSURLSession.sharedSession().dataTaskWithURL(url) { (data, response, error) -> Void in
guard
let httpURLResponse = response as? NSHTTPURLResponse where httpURLResponse.statusCode == 200,
let data = data where error == nil,
let htmlCode = String(data: data, encoding: NSUTF8StringEncoding) // make sure you use the correct String Encoding
else { return }
print( htmlCode)
print("URL LOADED")
}.resume()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
这篇关于如何在swift2中下载页面,而不使用第三方库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文