我正在尝试在应用中显示下载的HTML页面。请在不使用任何第三方库的情况下解释最简单的方法。
欢呼声,
答案 0 :(得分:0)
您可以在应用中显示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
答案 1 :(得分:0)
您应该使用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()
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.
}
}
答案 2 :(得分:-1)
您可以将网站直接下载到NSData对象中,如本例所示(Objective-C);
NSURL *tutorialsUrl = [NSURL URLWithString:@"http://www.raywenderlich.com/tutorials"];
NSData *tutorialsHtmlData = [NSData dataWithContentsOfURL:tutorialsUrl];
Swift示例;
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!)
雷在这里有一个很棒的教程;
https://www.raywenderlich.com/14172/how-to-parse-html-on-ios