我正在尝试在应用程序中显示下载的 HTML 页面。请说明在不使用任何第三方库的情况下最简单的方法。
干杯,
无需下载即可在应用程序中显示 html 页面
let pageUrl = NSURL (string: "http://www.stackoverflow.com");
let req = NSURLRequest(URL: url!);
如果你想显示一个本地文件,你可以像这样显示
let htmlfilePath = NSBundle.mainBundle().URLForResource("filename", withExtension: "html");
let req = NSURLRequest(URL: htmlfilePath !);
webview.loadRequest(req);
要下载一个文件,你可以使用普通的 NSURLSession
您应该使用 NSURLSession dataTaskWithURL 异步下载您的网站数据:
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()
loadHTML()
}
func loadHTML() {
guard let url = URL(string: stackoverflowLink) else { return }
print("LOADING URL")
URLSession.shared.dataTask(with: url) { data, response, error in
guard
let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let htmlCode = String(data: data, encoding: .utf8) // make sure you use the correct String Encoding
else { return }
print(htmlCode)
print("URL LOADED")
}.resume()
}
}
您可以像本例(Objective-C)一样将网站直接下载到 NSData 对象中;
NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
快速示例;
let aString = "http://fbcdn-sphotos-g-a.akamaihd.net/hphotos-ak-xfp1/t31.0-8/q88/s720x720/10848858_907722502601079_2834541930671169073_o.jpg"
let url = NSURL(string: aString)
let data = NSData(contentsOfURL: url!)
Ray 在这里有一个很棒的教程;
https://www.raywenderlich.com/14172/how-to-parse-html-on-ios